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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6deca8c0d18ed4af044834419473e915e7b20e81 | 3,474 | hpp | C++ | src/Utilities/TmplDebugging.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/Utilities/TmplDebugging.hpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/Utilities/TmplDebugging.hpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
/// \file
/// Defines class TypeDisplayer
#pragma once
#include "Utilities/TMPL.hpp"
/*!
* \ingroup UtilitiesGroup TypeTraitsGroup
* \brief Get compiler error with type of template parameter
*
* The compiler error generated when using an object of type
* `TypeDisplayer<...>` contains the types of the template parameters. This
* effectively provides printf-debugging for metaprogramming. For example,
* \code
* TypeDisplayer<std::vector<double>> some_random_name;
* \endcode
* will produce a compiler error that contains the type `std::vector<double,
* std::allocator...>`. TypeDisplayer is extremely useful when debugging
* template metaprograms.
*
* \note The TypeDisplayer header should only be included during testing
* and debugging.
*
* \see make_list
*/
template <typename...>
struct TypeDisplayer;
/*!
* \ingroup UtilitiesGroup
* \brief Metafunction to turn a parameter pack into a typelist
*
* This metafunction is really only useful for debugging metaprograms. For
* example, the desired algorithm might be:
*
* \code
* using variables_tags_from_single_tags = tmpl::filter<
* extracted_from_variables,
* tmpl::bind<tmpl::found, tmpl::pin<mutated_tags_list>,
* tmpl::bind<std::is_same, tmpl::_1, tmpl::parent<tmpl::_1>>>>;
* \endcode
*
* However, getting the `tmpl::pin`, `tmpl::parent`, and `tmpl::bind` calls
* right can be extremely frustrating with little help as to what is going on.
* Let's introduce an error by pinning `tmpl::_1`:
*
* \code
* using variables_tags_from_single_tags = tmpl::filter<
* extracted_from_variables,
* tmpl::bind<tmpl::found, tmpl::pin<mutated_tags_list>,
* tmpl::bind<std::is_same, tmpl::pin<tmpl::_1>,
* tmpl::parent<tmpl::_1>>>>;
* \endcode
*
* The result is comparing all values in `extracted_from_variables` to
* themselves. To find this out, replace `tmpl::filter` and `tmpl::found` with
* `tmpl::transform`, and the metafunction `std::is_same` to `make_list`.
* You will then get back a "backtrace" of what the algorithm did, which is
* invaluable for getting the `tmpl::pin` and `tmpl::parent` right. That is,
*
* \code
* using variables_tags_from_single_tags2 = tmpl::transform<
* extracted_from_variables,
* tmpl::bind<tmpl::transform, tmpl::pin<mutated_tags_list>,
* tmpl::bind<make_list, tmpl::_1, tmpl::parent<tmpl::_1>>>>;
*
* TypeDisplayer<variables_tags_from_single_tags2> aeou;
* \endcode
*
* You will get an output along the lines of:
*
* \code
* src/DataStructures/DataBox.hpp:1181:40: error: implicit instantiation of
* undefined template
* 'TypeDisplayer<brigand::list<brigand::list<
* brigand::list<test_databox_tags::ScalarTag,
* test_databox_tags::Tag0>, brigand::list<test_databox_tags::ScalarTag,
* Tags::Variables<brigand::list<test_databox_tags::ScalarTag,
* test_databox_tags::VectorTag> > > >,
* brigand::list<brigand::list<test_databox_tags::VectorTag,
* test_databox_tags::Tag0>,
* brigand::list<test_databox_tags::VectorTag,
* Tags::Variables<
* brigand::list<test_databox_tags::ScalarTag,
* test_databox_tags::VectorTag> > > > > >'
* \endcode
*
* \see TypeDisplayer
*/
template <class... Ts>
struct make_list {
using type = tmpl::list<Ts...>;
};
| 35.44898 | 79 | 0.685377 | [
"object",
"vector",
"transform"
] |
6dee4434d080b448d4aec623e031844cc6ac3846 | 3,164 | cpp | C++ | PAT/PAT-A1111-Online_Map.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | PAT/PAT-A1111-Online_Map.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | PAT/PAT-A1111-Online_Map.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | //
// Created by authetic on 2018/12/28.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 520;
const int INF = 1000000000;
struct Node {
int v, dis, time;
};
int n, m, s, t, d[maxn], f[maxn], d_pre[maxn], f_pre[maxn];
vector<Node> G[maxn];
bool visit[maxn];
void Dijstra(int s, bool shortest) {
fill(d, d+maxn, INF);
fill(f, f+maxn, INF);
d[s] = 0;
f[s] = 0;
for (int i = 0; i < n; i ++ ) {
int u = -1, MIN = INF;
if (shortest) {
for (int j = 0; j < n; j ++ ) {
if (!visit[j] && d[j] < MIN) {
u = j;
MIN = d[j];
}
}
} else {
for (int j = 0; j < n; j ++ ) {
if (!visit[j] && f[j] < MIN) {
u = j;
MIN = f[j];
}
}
}
if (u == -1) return;
visit[u] = true;
for (int j = 0; j < G[u].size(); j ++ ) {
int v = G[u][j].v;
if (shortest) {
if (!visit[v]) {
if (G[u][j].dis + d[u] < d[v]) {
d[v] = G[u][j].dis + d[u];
f[v] = f[u] + G[u][j].time;
d_pre[v] = u;
} else if (G[u][j].dis + d[u] == d[v]) {
if (f[u] + G[u][j].time < f[v]) {
f[v] = f[u] + G[u][j].time;
d_pre[v] = u;
}
}
}
} else {
if (!visit[v]) {
if (G[u][j].time + f[u] < f[v]) {
d[v] = G[u][j].dis + d[u];
f[v] = f[u] + G[u][j].time;
f_pre[v] = u;
} else if (G[u][j].time + f[u] == f[v]) {
if (d[u] + G[u][j].dis < d[v]) {
f[v] = f[u] + G[u][j].time;
f_pre[v] = u;
}
}
}
}
}
}
}
void dfs(int root, vector<int> &v, bool shortest) {
if (root == s) {
v.push_back(root);
return;
}
if (shortest) {
dfs(d_pre[root], v, shortest);
} else {
dfs(f_pre[root], v, shortest);
}
v.push_back(root);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i ++ ) {
int u, v, one_way, d, time;
Node node;
scanf("%d %d %d %d %d", &u, &v, &one_way, &d, &time);
node.v = v;
node.dis = d;
node.time = time;
G[u].push_back(node);
if (!one_way) {
node.v = u;
G[v].push_back(node);
}
}
scanf("%d%d", &s, &t);
Dijstra(s, true);
//Dijstra(s, false);
for (int i = 0; i < n; i ++ ) {
cout << d_pre[i] << " ";
}
/*
vector<int> shortest, fastest;
dfs(t, shortest, true);
dfs(t, fastest, false);
for (int i = 0;i < shortest.size(); i ++ ) {
printf("%d ", shortest[i]);
}*/
return 0;
} | 26.366667 | 61 | 0.331858 | [
"vector"
] |
6df2e77c7713f093df2223adbe5cebb82deb31f3 | 8,702 | cpp | C++ | sim/Character.cpp | snumrl/MSS | 29433598a9a026a18cbc6c5a9742dee7490ab9c7 | [
"Apache-2.0"
] | 10 | 2019-01-22T11:10:43.000Z | 2022-01-06T09:26:14.000Z | sim/Character.cpp | snumrl/MSS | 29433598a9a026a18cbc6c5a9742dee7490ab9c7 | [
"Apache-2.0"
] | null | null | null | sim/Character.cpp | snumrl/MSS | 29433598a9a026a18cbc6c5a9742dee7490ab9c7 | [
"Apache-2.0"
] | 3 | 2019-08-26T12:29:21.000Z | 2021-07-26T15:13:39.000Z | #include "Character.h"
#include "SkeletonBuilder.h"
#include <tinyxml.h>
using namespace dart::dynamics;
namespace MSS
{
Character::
Character(const dart::simulation::WorldPtr& world,const std::string& path)
:mWorld(world)
{
LoadSkeleton(path);
}
void
Character::
LoadSkeleton(const std::string& path)
{
mSkeleton = MSS::SkeletonBuilder::BuildFromFile(path);
//Load BVH map
TiXmlDocument doc;
if(!doc.LoadFile(path)){
std::cout << "Can't open file : " << path << std::endl;
return;
}
TiXmlElement *skeldoc = doc.FirstChildElement("Skeleton");
std::string skelname = skeldoc->Attribute("name");
for(TiXmlElement *body = skeldoc->FirstChildElement("Joint"); body != nullptr; body = body->NextSiblingElement("Joint")){
// name
std::string name = body->Attribute("name");
// bvh
if(body->Attribute("bvh")!=nullptr){
mBVHMap.insert(std::make_pair(name,body->Attribute("bvh")));
}
}
}
void
Character::
LoadMuscles(const std::string& path)
{
TiXmlDocument doc;
if(!doc.LoadFile(path)){
std::cout << "Can't open file : " << path << std::endl;
return;
}
TiXmlElement *muscledoc = doc.FirstChildElement("Muscle");
for(TiXmlElement* unit = muscledoc->FirstChildElement("Unit");unit!=nullptr;unit = unit->NextSiblingElement("Unit"))
{
std::string name = unit->Attribute("name");
double f0 = std::stod(unit->Attribute("f0"));
double lm = std::stod(unit->Attribute("lm"));
double lt = std::stod(unit->Attribute("lt"));
double pa = std::stod(unit->Attribute("pen_angle"));
double lmax = std::stod(unit->Attribute("lmax"));
mMuscles.push_back(new MuscleLBS(name,f0,lm,lt,pa,lmax));
int num_waypoints = 0;
for(TiXmlElement* waypoint = unit->FirstChildElement("Waypoint");waypoint!=nullptr;waypoint = waypoint->NextSiblingElement("Waypoint"))
num_waypoints++;
int i = 0;
for(TiXmlElement* waypoint = unit->FirstChildElement("Waypoint");waypoint!=nullptr;waypoint = waypoint->NextSiblingElement("Waypoint"))
{
std::string body = waypoint->Attribute("body");
Eigen::Vector3d glob_pos = string_to_vector3d(waypoint->Attribute("p"));
if(i==0||i==num_waypoints-1)
// if(true)
mMuscles.back()->AddAnchor(mSkeleton->getBodyNode(body),glob_pos);
else
mMuscles.back()->AddAnchor(mSkeleton,mSkeleton->getBodyNode(body),glob_pos,2);
i++;
}
}
}
void
Character::
LoadContactPoints(const std::string& path,double threshold,dart::dynamics::BodyNode* ground)
{
std::vector<Eigen::Vector3d> joint_positions;
for(int i=0;i<mSkeleton->getNumBodyNodes();i++)
{
auto p_joint = mSkeleton->getBodyNode(i)->getParentJoint();
Eigen::Isometry3d T_body = mSkeleton->getBodyNode(i)->getTransform();
Eigen::Isometry3d T_body_to_joint = p_joint->getTransformFromChildBodyNode();
Eigen::Isometry3d T = T_body * T_body_to_joint;
joint_positions.push_back(T.translation());
}
std::ifstream ifs(path);
if(!(ifs.is_open()))
{
std::cout<<"Can't read file "<<path<<std::endl;
return;
}
std::string str;
std::string index;
std::stringstream ss;
double x,y,z;
std::vector<Eigen::Vector3d> positions;
while(!ifs.eof())
{
str.clear();
index.clear();
ss.clear();
std::getline(ifs,str);
ss.str(str);
ss>>x>>y>>z;
Eigen::Vector3d vec;
vec[0] = x;
vec[1] = y;
vec[2] = z;
positions.push_back(vec);
double min_val=1E6;
int min_index=-1;
for(int i=0;i<joint_positions.size();i++)
{
double distance = (vec-joint_positions[i]).norm();
if(min_val>distance)
{
min_val = distance;
min_index = i;
}
}
mContactPoints.push_back(new ContactPoint(mWorld,mSkeleton->getBodyNode(min_index),ground,vec));
}
for(int i =0;i<positions.size();i++)
{
for(int j=i+1;j<positions.size();j++)
{
double distance = (positions[i]-positions[j]).norm();
if(distance<threshold)
{
mContactPoints[i]->AddNeighbor(mContactPoints[j]);
mContactPoints[j]->AddNeighbor(mContactPoints[i]);
}
}
}
ifs.close();
}
void
Character::
LoadMotionGraph(const std::string& path,const std::vector<int>& seq,double time_step)
{
mMotionGraph = new MotionGraph(mSkeleton,mBVHMap,time_step);
mMotionGraph->Parse(path);
mMotionGraph->SetWalk(seq);
}
void
Character::
SetPDParameters(double kp, double kv)
{
int dof = mSkeleton->getNumDofs();
SetPDParameters(Eigen::VectorXd::Constant(dof, kp), Eigen::VectorXd::Constant(dof, kv));
}
void
Character::
SetPDParameters(const Eigen::VectorXd& kp, const Eigen::VectorXd& kv)
{
this->mKp = kp;
this->mKv = kv;
// this->mKp.segment<6>(0).setZero();
// this->mKv.segment<6>(0).setZero();
}
#include <chrono>
Eigen::VectorXd
Character::
GetSPDForces(const Eigen::VectorXd& p_desired, const Eigen::VectorXd& v_desired)
{
// std::chrono::system_clock::time_point start,end;
// start = std::chrono::system_clock::now();
auto& skel = mSkeleton;
Eigen::VectorXd q = skel->getPositions();
Eigen::VectorXd dq = skel->getVelocities();
double dt = skel->getTimeStep();
Eigen::MatrixXd M_inv = (skel->getMassMatrix() + Eigen::MatrixXd(dt*mKv.asDiagonal())).inverse();
Eigen::VectorXd qdqdt = q + dq*dt;
Eigen::VectorXd p_diff = -mKp.cwiseProduct(skel->getPositionDifferences(qdqdt,p_desired));
Eigen::VectorXd v_diff = -mKv.cwiseProduct(dq-v_desired);
Eigen::VectorXd qddot = M_inv*(-skel->getCoriolisAndGravityForces()+
p_diff+v_diff+skel->getConstraintForces());
Eigen::VectorXd tau = p_diff + v_diff - dt*mKv.cwiseProduct(qddot);
tau.head<6>().setZero();
// end = std::chrono::system_clock::now();
// std::chrono::duration<double> elapsed_seconds = end-start;
// std::cout<<"GetSPDForces "<<" takes "<<elapsed_seconds.count()<<std::endl;
return tau;
}
Eigen::VectorXd
Character::
GetSPDAccelerations(const Eigen::VectorXd& p_desired, const Eigen::VectorXd& v_desired)
{
auto& skel = mSkeleton;
Eigen::VectorXd q = skel->getPositions();
Eigen::VectorXd dq = skel->getVelocities();
double dt = skel->getTimeStep();
Eigen::MatrixXd M_inv = (skel->getMassMatrix() + Eigen::MatrixXd(dt*mKv.asDiagonal())).inverse();
Eigen::VectorXd qdqdt = q + dq*dt;
Eigen::VectorXd p_diff = -mKp.cwiseProduct(skel->getPositionDifferences(qdqdt,p_desired));
Eigen::VectorXd v_diff = -mKv.cwiseProduct(dq-v_desired);
Eigen::VectorXd cg = skel->getCoriolisAndGravityForces();
Eigen::VectorXd qddot = M_inv*(-cg+ p_diff+v_diff+skel->getConstraintForces());
Eigen::VectorXd tau = skel->getInvMassMatrix()*(p_diff + v_diff - dt*mKv.cwiseProduct(qddot)-cg);
// tau.head<6>().setZero();
for(int i =0;i<tau.rows();i++)
tau[i] = dart::math::clip(tau[i],-1000.0,1000.0);
return tau;
}
Eigen::VectorXd
Character::
GetTargetPositions(const Eigen::VectorXd& mode_lb)
{
int dof = mSkeleton->getPositions().rows();
Eigen::VectorXd p = mMotionGraph->GetMotion();
for(int i =0;i<mode_lb.rows();i++){
mMotionActions[i]->SetLB(mode_lb[i]);
mMotionActions[i]->Set(p);
}
return p;
}
std::pair<Eigen::VectorXd,Eigen::VectorXd>
Character::
GetTargetPositionsAndVelocitiesFromBVH(const Eigen::VectorXd& mode_lb)
{
Eigen::VectorXd p = GetTargetPositions(mode_lb);
mMotionGraph->SaveState();
mMotionGraph->Step();
Eigen::VectorXd p1 = GetTargetPositions(mode_lb);
mMotionGraph->LoadState();
int dof = mSkeleton->getPositions().rows();
Eigen::VectorXd target_position = p;
Eigen::VectorXd target_velocity = (p1-p)/mMotionGraph->GetTimeStep();
Eigen::VectorXd current_position = mSkeleton->getPositions();
Eigen::VectorXd current_velocity = mSkeleton->getVelocities();
mSkeleton->setPositions(target_position);
mSkeleton->setVelocities(target_velocity);
dynamic_cast<dart::dynamics::FreeJoint*>(mSkeleton->getRootJoint())->setLinearVelocity(target_velocity.segment<3>(3));
mSkeleton->computeForwardKinematics(true,false,false);
target_velocity = mSkeleton->getVelocities();
mSkeleton->setPositions(current_position);
mSkeleton->setVelocities(current_velocity);
mSkeleton->computeForwardKinematics(true,false,false);
return std::make_pair(target_position,target_velocity);
}
Eigen::VectorXd
Character::
GetIKTargetPositions(const Eigen::VectorXd& p,const Eigen::VectorXd& mode_lb)
{
if(mode_lb.rows()==0)
return p;
Eigen::VectorXd p_IK = p;
mIKAction->SetLB(mode_lb);
mIKAction->Set(p_IK);
return p_IK;
}
std::pair<Eigen::VectorXd,Eigen::VectorXd>
Character::
GetKpKv(double default_val,const Eigen::VectorXd& mode_lb)
{
int dof = mSkeleton->getPositions().rows();
Eigen::VectorXd kp = Eigen::VectorXd::Constant(dof,default_val);
Eigen::VectorXd kv = Eigen::VectorXd::Constant(dof,default_val);
for(int i =0;i<mode_lb.rows();i++){
mKpActions[i]->SetLB(mode_lb[i]);
mKpActions[i]->Set(kp);
}
for(int i =0;i<dof;i++)
kv[i] = sqrt(2*kp[i]);
return std::make_pair(kp,kv);
}
}; | 29.103679 | 138 | 0.706045 | [
"vector"
] |
6df43e3353508cff81a44cc6e2f8588e11f2fdf6 | 4,828 | cxx | C++ | arrows/mvg/epipolar_geometry.cxx | mwoehlke-kitware/kwiver | 614a488bd2b7fe551ac75eec979766d882709791 | [
"BSD-3-Clause"
] | 176 | 2015-07-31T23:33:37.000Z | 2022-03-21T23:42:44.000Z | arrows/mvg/epipolar_geometry.cxx | mwoehlke-kitware/kwiver | 614a488bd2b7fe551ac75eec979766d882709791 | [
"BSD-3-Clause"
] | 1,276 | 2015-05-03T01:21:27.000Z | 2022-03-31T15:32:20.000Z | arrows/mvg/epipolar_geometry.cxx | mwoehlke-kitware/kwiver | 614a488bd2b7fe551ac75eec979766d882709791 | [
"BSD-3-Clause"
] | 85 | 2015-01-25T05:13:38.000Z | 2022-01-14T14:59:37.000Z | // This file is part of KWIVER, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.
/**
* \file
* \brief Implementation of epipolar geometry functions.
*/
#include "epipolar_geometry.h"
#include <arrows/mvg/triangulate.h>
namespace kwiver {
namespace arrows {
namespace mvg {
/// Test corresponding points against a fundamental matrix and mark inliers
std::vector<bool>
mark_fm_inliers(vital::fundamental_matrix const& fm,
std::vector<vital::vector_2d> const& pts1,
std::vector<vital::vector_2d> const& pts2,
double inlier_scale)
{
using namespace kwiver::vital;
matrix_3x3d F = fm.matrix();
matrix_3x3d Ft = F.transpose();
std::vector<bool> inliers(std::min(pts1.size(), pts2.size()));
for(unsigned i=0; i<inliers.size(); ++i)
{
const vector_2d& p1 = pts1[i];
const vector_2d& p2 = pts2[i];
vector_3d v1(p1.x(), p1.y(), 1.0);
vector_3d v2(p2.x(), p2.y(), 1.0);
vector_3d l1 = F * v1;
vector_3d l2 = Ft * v2;
double s1 = 1.0 / sqrt(l1.x()*l1.x() + l1.y()*l1.y());
double s2 = 1.0 / sqrt(l2.x()*l2.x() + l2.y()*l2.y());
// sum of point to epipolar line distance in both images
double d = v1.dot(l2) * (s1 + s2);
inliers[i] = std::fabs(d) < inlier_scale;
}
return inliers;
}
/// Compute a valid left camera from an essential matrix
kwiver::vital::simple_camera_perspective
extract_valid_left_camera(const kwiver::vital::essential_matrix_d& e,
const kwiver::vital::vector_2d& left_pt,
const kwiver::vital::vector_2d& right_pt)
{
using namespace kwiver::vital;
/// construct an identity right camera
const vector_3d t = e.translation();
rotation_d R = e.rotation();
std::vector<vector_2d> pts;
pts.push_back(right_pt);
pts.push_back(left_pt);
std::vector<vital::simple_camera_perspective> cams(2);
const vital::simple_camera_perspective& left_camera = cams[1];
// option 1
cams[1] = vital::simple_camera_perspective(R.inverse()*-t, R);
vector_3d pt3 = triangulate_inhomog(cams, pts);
if( pt3.z() > 0.0 && left_camera.depth(pt3) > 0.0 )
{
return left_camera;
}
// option 2, with negated translation
cams[1] = vital::simple_camera_perspective(R.inverse()*t, R);
pt3 = triangulate_inhomog(cams, pts);
if( pt3.z() > 0.0 && left_camera.depth(pt3) > 0.0 )
{
return left_camera;
}
// option 3, with the twisted pair rotation
R = e.twisted_rotation();
cams[1] = vital::simple_camera_perspective(R.inverse()*-t, R);
pt3 = triangulate_inhomog(cams, pts);
if( pt3.z() > 0.0 && left_camera.depth(pt3) > 0.0 )
{
return left_camera;
}
// option 4, with negated translation
cams[1] = vital::simple_camera_perspective(R.inverse()*t, R);
pt3 = triangulate_inhomog(cams, pts);
if( pt3.z() > 0.0 && left_camera.depth(pt3) > 0.0 )
{
return left_camera;
}
// should never get here
return vital::simple_camera_perspective();
}
// Compute the fundamental matrix from a pair of cameras
kwiver::vital::fundamental_matrix_sptr
fundamental_matrix_from_cameras(kwiver::vital::camera_perspective const& right_cam,
kwiver::vital::camera_perspective const& left_cam)
{
using namespace kwiver::vital;
essential_matrix_sptr em = essential_matrix_from_cameras(right_cam, left_cam);
return essential_matrix_to_fundamental(*em, *right_cam.intrinsics(),
*left_cam.intrinsics());
}
// Compute the essential matrix from a pair of cameras
kwiver::vital::essential_matrix_sptr
essential_matrix_from_cameras(kwiver::vital::camera_perspective const& right_cam,
kwiver::vital::camera_perspective const& left_cam)
{
using namespace kwiver::vital;
rotation_d R1 = right_cam.rotation();
rotation_d R2 = left_cam.rotation();
vector_3d t1 = right_cam.translation();
vector_3d t2 = left_cam.translation();
rotation_d R(R2 * R1.inverse());
vector_3d t(t2 - R*t1);
return std::make_shared<essential_matrix_d>(R,t);
}
/// Convert an essential matrix to a fundamental matrix
kwiver::vital::fundamental_matrix_sptr
essential_matrix_to_fundamental(kwiver::vital::essential_matrix const & E,
kwiver::vital::camera_intrinsics const& right_cal,
kwiver::vital::camera_intrinsics const& left_cal)
{
using namespace kwiver::vital;
matrix_3x3d Kr_inv = right_cal.as_matrix().inverse();
matrix_3x3d Kl_invt = left_cal.as_matrix().transpose().inverse();
return std::make_shared<fundamental_matrix_d>( Kl_invt * E.matrix() * Kr_inv );
}
} // end namespace mvg
} // end namespace arrows
} // end namespace kwiver
| 33.762238 | 83 | 0.672742 | [
"geometry",
"vector"
] |
6df639d24e0d8397e6705237bcd02d613b49082f | 6,612 | hpp | C++ | src/multibody/joint/joint-data-base.hpp | Sreevis/pinocchio | 7e3f96e59047b40e678a53b3877b401af4b6d0bd | [
"BSD-2-Clause-FreeBSD"
] | 716 | 2015-03-30T16:26:45.000Z | 2022-03-30T12:26:58.000Z | src/multibody/joint/joint-data-base.hpp | Sreevis/pinocchio | 7e3f96e59047b40e678a53b3877b401af4b6d0bd | [
"BSD-2-Clause-FreeBSD"
] | 1,130 | 2015-02-21T17:30:44.000Z | 2022-03-30T09:06:22.000Z | src/multibody/joint/joint-data-base.hpp | Sreevis/pinocchio | 7e3f96e59047b40e678a53b3877b401af4b6d0bd | [
"BSD-2-Clause-FreeBSD"
] | 239 | 2015-02-05T14:15:14.000Z | 2022-03-14T23:51:47.000Z | //
// Copyright (c) 2015-2019 CNRS INRIA
// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//
#ifndef __pinocchio_multibody_joint_data_base_hpp__
#define __pinocchio_multibody_joint_data_base_hpp__
#include "pinocchio/multibody/joint/joint-base.hpp"
#include "pinocchio/multibody/joint/joint-model-base.hpp"
#define PINOCCHIO_JOINT_DATA_TYPEDEF_GENERIC(Joint,TYPENAME) \
PINOCCHIO_JOINT_MODEL_TYPEDEF_GENERIC(Joint,TYPENAME); \
typedef TYPENAME traits<Joint>::ConstraintTypeConstRef ConstraintTypeConstRef; \
typedef TYPENAME traits<Joint>::ConstraintTypeRef ConstraintTypeRef; \
typedef TYPENAME traits<Joint>::TansformTypeConstRef TansformTypeConstRef; \
typedef TYPENAME traits<Joint>::TansformTypeRef TansformTypeRef; \
typedef TYPENAME traits<Joint>::MotionTypeConstRef MotionTypeConstRef; \
typedef TYPENAME traits<Joint>::MotionTypeRef MotionTypeRef; \
typedef TYPENAME traits<Joint>::BiasTypeConstRef BiasTypeConstRef; \
typedef TYPENAME traits<Joint>::BiasTypeRef BiasTypeRef; \
typedef TYPENAME traits<Joint>::UTypeConstRef UTypeConstRef; \
typedef TYPENAME traits<Joint>::UTypeRef UTypeRef; \
typedef TYPENAME traits<Joint>::DTypeConstRef DTypeConstRef; \
typedef TYPENAME traits<Joint>::DTypeRef DTypeRef; \
typedef TYPENAME traits<Joint>::UDTypeConstRef UDTypeConstRef; \
typedef TYPENAME traits<Joint>::UDTypeRef UDTypeRef
#ifdef __clang__
#define PINOCCHIO_JOINT_DATA_TYPEDEF(Joint) PINOCCHIO_JOINT_DATA_TYPEDEF_GENERIC(Joint,PINOCCHIO_EMPTY_ARG)
#define PINOCCHIO_JOINT_DATA_TYPEDEF_TEMPLATE(Joint) PINOCCHIO_JOINT_DATA_TYPEDEF_GENERIC(Joint,typename)
#elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 4) && (__GNUC_PATCHLEVEL__ == 2)
#define PINOCCHIO_JOINT_DATA_TYPEDEF(Joint) PINOCCHIO_JOINT_DATA_TYPEDEF_GENERIC(Joint,PINOCCHIO_EMPTY_ARG)
#define PINOCCHIO_JOINT_DATA_TYPEDEF_TEMPLATE(Joint) PINOCCHIO_JOINT_DATA_TYPEDEF_GENERIC(Joint,typename)
#else
#define PINOCCHIO_JOINT_DATA_TYPEDEF(Joint) PINOCCHIO_JOINT_DATA_TYPEDEF_GENERIC(Joint,typename)
#define PINOCCHIO_JOINT_DATA_TYPEDEF_TEMPLATE(Joint) PINOCCHIO_JOINT_DATA_TYPEDEF_GENERIC(Joint,typename)
#endif
#define PINOCCHIO_JOINT_DATA_BASE_DEFAULT_ACCESSOR \
ConstraintTypeConstRef S_accessor() const { return S; } \
ConstraintTypeRef S_accessor() { return S; } \
TansformTypeConstRef M_accessor() const { return M; } \
TansformTypeRef M_accessor() { return M; } \
MotionTypeConstRef v_accessor() const { return v; } \
MotionTypeRef v_accessor() { return v; } \
BiasTypeConstRef c_accessor() const { return c; } \
BiasTypeRef c_accessor() { return c; } \
UTypeConstRef U_accessor() const { return U; } \
UTypeRef U_accessor() { return U; } \
DTypeConstRef Dinv_accessor() const { return Dinv; } \
DTypeRef Dinv_accessor() { return Dinv; } \
UDTypeConstRef UDinv_accessor() const { return UDinv; } \
UDTypeRef UDinv_accessor() { return UDinv; }
#define PINOCCHIO_JOINT_DATA_BASE_ACCESSOR_DEFAULT_RETURN_TYPE \
typedef const Constraint_t & ConstraintTypeConstRef; \
typedef Constraint_t & ConstraintTypeRef; \
typedef const Transformation_t & TansformTypeConstRef; \
typedef Transformation_t & TansformTypeRef; \
typedef const Motion_t & MotionTypeConstRef; \
typedef Motion_t & MotionTypeRef; \
typedef const Bias_t & BiasTypeConstRef; \
typedef Bias_t & BiasTypeRef; \
typedef const U_t & UTypeConstRef; \
typedef U_t & UTypeRef; \
typedef const D_t & DTypeConstRef; \
typedef D_t & DTypeRef; \
typedef const UD_t & UDTypeConstRef; \
typedef UD_t & UDTypeRef;
namespace pinocchio
{
template<typename Derived>
struct JointDataBase
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef typename traits<Derived>::JointDerived JointDerived;
PINOCCHIO_JOINT_DATA_TYPEDEF_TEMPLATE(JointDerived);
Derived & derived() { return *static_cast<Derived*>(this); }
const Derived & derived() const { return *static_cast<const Derived*>(this); }
ConstraintTypeConstRef S() const { return derived().S_accessor(); }
ConstraintTypeRef S() { return derived().S_accessor(); }
TansformTypeConstRef M() const { return derived().M_accessor(); }
TansformTypeRef M() { return derived().M_accessor(); }
MotionTypeConstRef v() const { return derived().v_accessor(); }
MotionTypeRef v() { return derived().v_accessor(); }
BiasTypeConstRef c() const { return derived().c_accessor(); }
BiasTypeRef c() { return derived().c_accessor(); }
UTypeConstRef U() const { return derived().U_accessor(); }
UTypeRef U() { return derived().U_accessor(); }
DTypeConstRef Dinv() const { return derived().Dinv_accessor(); }
DTypeRef Dinv() { return derived().Dinv_accessor(); }
UDTypeConstRef UDinv() const { return derived().UDinv_accessor(); }
UDTypeRef UDinv() { return derived().UDinv_accessor(); }
std::string shortname() const { return derived().shortname(); }
static std::string classname() { return Derived::classname(); }
void disp(std::ostream & os) const
{
using namespace std;
os << shortname() << endl;
}
friend std::ostream & operator << (std::ostream & os, const JointDataBase<Derived> & joint)
{
joint.disp(os);
return os;
}
template<typename OtherDerived>
bool operator==(const JointDataBase<OtherDerived> & other) const
{
return derived().isEqual(other.derived());
}
/// \brief Default operator== implementation
bool isEqual(const JointDataBase & other) const
{
return S() == other.S()
&& M() == other.M()
&& v() == other.v()
&& c() == other.c()
&& U() == other.U()
&& Dinv() == other.Dinv()
&& UDinv() == other.UDinv()
;
}
/// \brief Default operator== implementation
template<typename OtherDerived>
bool isEqual(const JointDataBase<OtherDerived> & /*other*/) const
{
return false;
;
}
bool operator!=(const JointDataBase<Derived> & other) const
{
return derived().isNotEqual(other.derived());
}
/// \brief Default operator!= implementation
bool isNotEqual(const JointDataBase<Derived> & other) const
{
return !(derived() == other.derived());
}
protected:
/// \brief Default constructor: protected.
inline JointDataBase() {}
}; // struct JointDataBase
} // namespace pinocchio
#endif // ifndef __pinocchio_multibody_joint_data_base_hpp__
| 38.666667 | 109 | 0.704325 | [
"model"
] |
6df8ad37c7647e789f46ed962d4827f391e70a84 | 8,121 | cpp | C++ | test/crypto_Aes128CbcEncryptedStream_TestClass.cpp | toolbrew/libtoolchain | fd98be60d1c5ca62871c16c88b8e59be05d7f0ac | [
"MIT"
] | null | null | null | test/crypto_Aes128CbcEncryptedStream_TestClass.cpp | toolbrew/libtoolchain | fd98be60d1c5ca62871c16c88b8e59be05d7f0ac | [
"MIT"
] | null | null | null | test/crypto_Aes128CbcEncryptedStream_TestClass.cpp | toolbrew/libtoolchain | fd98be60d1c5ca62871c16c88b8e59be05d7f0ac | [
"MIT"
] | null | null | null | #include <tc/Exception.h>
#include <tc/io.h>
#include <tc/cli.h>
#include <fmt/core.h>
#include "crypto_Aes128CbcEncryptedStream_TestClass.h"
#include "StreamTestUtil.h"
void crypto_Aes128CbcEncryptedStream_TestClass::runAllTests(void)
{
fmt::print("[tc::crypto::Aes128CbcEncryptedStream] START\n");
test_CreateEmptyStream_DefaultConstructor();
test_CreateValidStream_CreateConstructor();
test_RunTestCases();
fmt::print("[tc::crypto::Aes128CbcEncryptedStream] END\n");
}
void crypto_Aes128CbcEncryptedStream_TestClass::test_CreateEmptyStream_DefaultConstructor()
{
fmt::print("[tc::crypto::Aes128CbcEncryptedStream] test_CreateEmptyStream_DefaultConstructor : ");
try
{
try
{
auto stream = tc::crypto::Aes128CbcEncryptedStream();
StreamTestUtil::constructor_TestHelper(stream, 0, 0, false, false, false);
try
{
stream.read(nullptr, 0);
throw tc::Exception(".read() did not throw tc::ObjectDisposedException for uninitialized Aes128CbcEncryptedStream");
}
catch (tc::ObjectDisposedException&) {
// do nothing
}
try
{
stream.write(nullptr, 0);
throw tc::Exception(".write() did not throw tc::ObjectDisposedException for uninitialized Aes128CbcEncryptedStream");
}
catch (tc::ObjectDisposedException&) {
// do nothing
}
try
{
stream.seek(0, tc::io::SeekOrigin::Begin);
throw tc::Exception(".seek() did not throw tc::ObjectDisposedException for uninitialized Aes128CbcEncryptedStream");
}
catch (tc::ObjectDisposedException&) {
// do nothing
}
try
{
stream.setLength(0);
throw tc::Exception(".setLength() did not throw tc::ObjectDisposedException for uninitialized Aes128CbcEncryptedStream");
}
catch (tc::ObjectDisposedException&) {
// do nothing
}
try
{
stream.flush();
throw tc::Exception(".flush() did not throw tc::ObjectDisposedException for uninitialized Aes128CbcEncryptedStream");
}
catch (tc::ObjectDisposedException&) {
// do nothing
}
fmt::print("PASS\n");
}
catch (const tc::Exception& e)
{
fmt::print("FAIL ({:s})\n", e.error());
}
}
catch (const std::exception& e)
{
fmt::print("UNHANDLED EXCEPTION ({:s})\n", e.what());
}
}
void crypto_Aes128CbcEncryptedStream_TestClass::test_CreateValidStream_CreateConstructor()
{
fmt::print("[tc::crypto::Aes128CbcEncryptedStream] test_CreateValidStream_CreateConstructor : ");
try
{
try
{
tc::crypto::Aes128CbcEncryptedStream::key_t key;
tc::crypto::Aes128CbcEncryptedStream::iv_t iv;
std::shared_ptr<tc::io::IStream> base_stream;
base_stream = std::shared_ptr<tc::io::MemoryStream>(new tc::io::MemoryStream(tc::ByteData(0x100)));
auto stream = tc::crypto::Aes128CbcEncryptedStream(base_stream, key, iv);
try
{
stream.write(nullptr, 0);
throw tc::Exception(".write() did not throw tc::NotImplementedException for initialized Aes128CbcEncryptedStream");
}
catch (tc::NotImplementedException&) {
// do nothing
}
try
{
stream.setLength(0);
throw tc::Exception(".setLength() did not throw tc::NotImplementedException for initialized Aes128CbcEncryptedStream");
}
catch (tc::NotImplementedException&) {
// do nothing
}
fmt::print("PASS\n");
}
catch (const tc::Exception& e)
{
fmt::print("FAIL ({:s})\n", e.error());
}
}
catch (const std::exception& e)
{
fmt::print("UNHANDLED EXCEPTION ({:s})\n", e.what());
}
}
void crypto_Aes128CbcEncryptedStream_TestClass::test_RunTestCases()
{
fmt::print("[tc::crypto::Aes128CbcEncryptedStream] test_RunTestCases : ");
try
{
try
{
// get test cases
std::vector<crypto_Aes128CbcEncryptedStream_TestClass::TestCase> test_cases;
util_Setup_TestCases(test_cases);
for (auto itr = test_cases.begin(); itr != test_cases.end(); itr++)
{
tc::crypto::Aes128CbcEncryptedStream::key_t key;
memcpy(key.data(), itr->key.data(), itr->key.size());
tc::crypto::Aes128CbcEncryptedStream::iv_t iv;
memcpy(iv.data(), itr->iv.data(), itr->iv.size());
std::shared_ptr<tc::io::IStream> base_stream;
base_stream = std::shared_ptr<tc::io::MemoryStream>(new tc::io::MemoryStream(itr->ciphertext));
auto stream = tc::crypto::Aes128CbcEncryptedStream(base_stream, key, iv);
try
{
StreamTestUtil::constructor_TestHelper(stream, itr->ciphertext.size(), 0, true, false, true);
StreamTestUtil::read_TestHelper(stream, itr->read_offset, tc::io::SeekOrigin::Begin, itr->read_size, itr->read_size, itr->read_plaintext.size(), itr->read_offset + int64_t(itr->read_size), itr->read_plaintext.data());
}
catch (const tc::Exception& e)
{
throw tc::Exception(fmt::format("{} Failed: {}", itr->test_name, e.error()));
}
}
fmt::print("PASS\n");
}
catch (const tc::Exception& e)
{
fmt::print("FAIL ({:s})\n", e.error());
}
}
catch (const std::exception& e)
{
fmt::print("UNHANDLED EXCEPTION ({:s})\n", e.what());
}
}
void crypto_Aes128CbcEncryptedStream_TestClass::util_Setup_TestCases(std::vector<crypto_Aes128CbcEncryptedStream_TestClass::TestCase>& test_cases)
{
TestCase tmp;
test_cases.clear();
// Test vectors taken from NIST SP 800-38A
tmp.key = tc::cli::FormatUtil::hexStringToBytes("2b7e151628aed2a6abf7158809cf4f3c");
tmp.iv = tc::cli::FormatUtil::hexStringToBytes("000102030405060708090A0B0C0D0E0F");
tc::ByteData plaintext = tc::cli::FormatUtil::hexStringToBytes("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710");
tc::ByteData ciphertext = tc::cli::FormatUtil::hexStringToBytes("7649abac8119b246cee98e9b12e9197d5086cb9b507219ee95db113a917678b273bed6b8e3c1743b7116e69e222295163ff1caa1681fac09120eca307586e1a7");
tmp.test_name = "Test 1";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x00;
tmp.read_size = 0x10;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test 2";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x10;
tmp.read_size = 0x10;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test 3";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x20;
tmp.read_size = 0x10;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test 4";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x30;
tmp.read_size = 0x10;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test read all blocks";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x0;
tmp.read_size = 0x40;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test un-aligned read over blocks 1-2";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x17;
tmp.read_size = 0x11;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test un-aligned read over blocks 0-3";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x07;
tmp.read_size = 0x31;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test partial block 0 read";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x2;
tmp.read_size = 0x8;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test partial block 1 read";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x12;
tmp.read_size = 0x8;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
tmp.test_name = "Test partial block 3 read";
tmp.ciphertext = ciphertext;
tmp.read_offset = 0x32;
tmp.read_size = 0x8;
tmp.read_plaintext = tc::ByteData(plaintext.data() + tmp.read_offset, tmp.read_size);
test_cases.push_back(tmp);
} | 30.645283 | 222 | 0.715675 | [
"vector"
] |
6df8d9b2f0c017f2fdaf9bada697dfa78d161072 | 3,087 | hh | C++ | src/thread_pool.hh | asielorz/task-library | 17dd2164acb6e11374fe90d9b00f18b9baadd649 | [
"MIT"
] | null | null | null | src/thread_pool.hh | asielorz/task-library | 17dd2164acb6e11374fe90d9b00f18b9baadd649 | [
"MIT"
] | null | null | null | src/thread_pool.hh | asielorz/task-library | 17dd2164acb6e11374fe90d9b00f18b9baadd649 | [
"MIT"
] | null | null | null | #pragma once
#include "polymorphic_task.hh"
#include <vector>
#include <mutex>
#include <atomic>
#include <queue>
#include <functional>
#include <optional>
#include <span>
struct atomic_flag_lock_guard
{
[[nodiscard]] explicit atomic_flag_lock_guard(std::atomic_flag & flag_) noexcept;
~atomic_flag_lock_guard();
atomic_flag_lock_guard(atomic_flag_lock_guard const &) = delete;
atomic_flag_lock_guard & operator = (atomic_flag_lock_guard const &) = delete;
explicit operator bool() const noexcept;
private:
std::atomic_flag & flag;
bool locked;
};
struct TaskQueue
{
explicit TaskQueue(int queue_count);
auto push_task(PolymorphicTask task) -> void;
auto push_task(PolymorphicTask task, int preferred_queue_index) -> int;
auto pop_task(int preferred_queue_index) -> std::optional<PolymorphicTask>;
// To make it satisfy the executor concept.
auto run_task(PolymorphicTask task) -> void { push_task(std::move(task)); }
auto number_of_queues() const noexcept -> int { return static_cast<int>(queues.size()); }
auto number_of_queued_tasks() const noexcept -> int { return queued_tasks; }
auto has_work_queued() const noexcept -> bool { return number_of_queued_tasks() > 0; }
private:
struct LockQueue
{
auto push(PolymorphicTask && task) -> bool;
auto pop() -> std::optional<PolymorphicTask>;
private:
std::queue<PolymorphicTask> queue;
std::atomic_flag mutex;
};
std::vector<LockQueue> queues;
int round_robin_next_index = 0;
std::atomic<int> queued_tasks;
};
inline auto as_work_source(TaskQueue & queue, int preferred_queue_index);
namespace this_thread
{
auto perform_task_for(TaskQueue & task_queue) -> bool;
auto perform_task_for(TaskQueue & task_queue, int preferred_queue_index) -> bool;
auto work_until_no_tasks_left_for(TaskQueue & task_queue) -> int;
auto work_until_no_tasks_left_for(TaskQueue & task_queue, int preferred_queue_index) -> int;
}
struct WorkerThread
{
using WorkSource = std::function<std::optional<PolymorphicTask>()>;
WorkerThread(WorkSource work_source);
~WorkerThread();
WorkerThread(WorkerThread const &) = delete;
WorkerThread & operator = (WorkerThread const &) = delete;
WorkerThread(WorkerThread && other) noexcept;
WorkerThread & operator = (WorkerThread &&) noexcept;
auto work_for(WorkSource source) -> void;
auto join() -> void;
auto joinable() const noexcept -> bool { return state != nullptr; }
explicit operator bool() const noexcept { return joinable(); }
private:
struct WorkerState
{
std::mutex work_source_mutex;
WorkSource work_source;
bool stop_token = false;
bool work_source_changed = false;
};
static auto worker_main(WorkerState * & state_ptr, WorkSource initial_work_source) -> void;
std::thread thread;
WorkerState * state = nullptr;
};
auto make_workers_for_queue(TaskQueue & task_queue) -> std::vector<WorkerThread>;
auto make_workers_for_queue(TaskQueue & task_queue, int worker_count) -> std::vector<WorkerThread>;
auto assign_thread_pool_to_workers(std::span<WorkerThread> workers, TaskQueue & task_queue) -> void;
#include "thread_pool.inl"
| 28.063636 | 100 | 0.757046 | [
"vector"
] |
6df92c68a94b13d3f05f6d214ac7f753c1b3f51c | 5,290 | cpp | C++ | Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.cpp | John3/t3d_benchmarking | 27a5780ad704aa91b45ff1bb0d69ed07668d03be | [
"MIT"
] | 10 | 2015-03-12T20:20:34.000Z | 2021-02-03T08:07:31.000Z | Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.cpp | John3/t3d_benchmarking | 27a5780ad704aa91b45ff1bb0d69ed07668d03be | [
"MIT"
] | 3 | 2015-07-04T23:50:43.000Z | 2016-08-01T09:19:52.000Z | Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.cpp | John3/t3d_benchmarking | 27a5780ad704aa91b45ff1bb0d69ed07668d03be | [
"MIT"
] | 6 | 2015-11-28T16:18:26.000Z | 2020-03-29T17:14:56.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11OcclusionQuery.h"
#include "gui/3d/guiTSControl.h"
#ifdef TORQUE_GATHER_METRICS
// For TickMs define
#include "T3D/gameBase/processList.h"
#endif
GFXD3D11OcclusionQuery::GFXD3D11OcclusionQuery(GFXDevice *device)
: GFXOcclusionQuery(device),
mQuery(NULL)
{
#ifdef TORQUE_GATHER_METRICS
mTimer = PlatformTimer::create();
mTimer->getElapsedMs();
mTimeSinceEnd = 0;
mBeginFrame = 0;
#endif
}
GFXD3D11OcclusionQuery::~GFXD3D11OcclusionQuery()
{
SAFE_RELEASE(mQuery);
#ifdef TORQUE_GATHER_METRICS
SAFE_DELETE(mTimer);
#endif
}
bool GFXD3D11OcclusionQuery::begin()
{
if(GFXDevice::getDisableOcclusionQuery())
return true;
if (mQuery == NULL)
{
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_OCCLUSION;
queryDesc.MiscFlags = 0;
HRESULT hRes = D3D11DEVICE->CreateQuery(&queryDesc, &mQuery);
if(FAILED(hRes))
{
AssertFatal(false, "GFXD3D11OcclusionQuery::begin - Hardware does not support D3D11 Occlusion-Queries, this should be caught before this type is created");
}
AssertISV(hRes != E_OUTOFMEMORY, "GFXD3D11OcclusionQuery::begin - Out of memory");
}
// Add a begin marker to the command buffer queue.
D3D11DEVICECONTEXT->Begin(mQuery);
#ifdef TORQUE_GATHER_METRICS
mBeginFrame = GuiTSCtrl::getFrameCount();
#endif
return true;
}
void GFXD3D11OcclusionQuery::end()
{
if (GFXDevice::getDisableOcclusionQuery())
return;
// Add an end marker to the command buffer queue.
D3D11DEVICECONTEXT->End(mQuery);
#ifdef TORQUE_GATHER_METRICS
AssertFatal( mBeginFrame == GuiTSCtrl::getFrameCount(), "GFXD3D11OcclusionQuery::end - ended query on different frame than begin!" );
mTimer->getElapsedMs();
mTimer->reset();
#endif
}
GFXD3D11OcclusionQuery::OcclusionQueryStatus GFXD3D11OcclusionQuery::getStatus(bool block, U32 *data)
{
// If this ever shows up near the top of a profile then your system is
// GPU bound or you are calling getStatus too soon after submitting it.
//
// To test if you are GPU bound resize your window very small and see if
// this profile no longer appears at the top.
//
// To test if you are calling getStatus to soon after submitting it,
// check the value of mTimeSinceEnd in a debug build. If it is < half the length
// of time to render an individual frame you could have problems.
PROFILE_SCOPE(GFXD3D11OcclusionQuery_getStatus);
if ( GFXDevice::getDisableOcclusionQuery() )
return NotOccluded;
if ( mQuery == NULL )
return Unset;
#ifdef TORQUE_GATHER_METRICS
//AssertFatal( mBeginFrame < GuiTSCtrl::getFrameCount(), "GFXD3D11OcclusionQuery::getStatus - called on the same frame as begin!" );
//U32 mTimeSinceEnd = mTimer->getElapsedMs();
//AssertFatal( mTimeSinceEnd >= 5, "GFXD3DOcculsionQuery::getStatus - less than TickMs since called ::end!" );
#endif
HRESULT hRes;
U64 dwOccluded = 0;
if ( block )
{
while ((hRes = D3D11DEVICECONTEXT->GetData(mQuery, &dwOccluded, sizeof(U64), 0)) == S_FALSE);
}
else
{
hRes = D3D11DEVICECONTEXT->GetData(mQuery, &dwOccluded, sizeof(U64), 0);
}
if (hRes == S_OK)
{
if (data != NULL)
*data = (U32)dwOccluded;
return dwOccluded > 0 ? NotOccluded : Occluded;
}
if (hRes == S_FALSE)
return Waiting;
return Error;
}
void GFXD3D11OcclusionQuery::zombify()
{
SAFE_RELEASE( mQuery );
}
void GFXD3D11OcclusionQuery::resurrect()
{
// Recreate the query
if( mQuery == NULL )
{
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_OCCLUSION;
queryDesc.MiscFlags = 0;
HRESULT hRes = D3D11DEVICE->CreateQuery(&queryDesc, &mQuery);
AssertISV( hRes != E_OUTOFMEMORY, "GFXD3D9QueryFence::resurrect - Out of memory" );
}
}
const String GFXD3D11OcclusionQuery::describeSelf() const
{
// We've got nothing
return String();
} | 29.887006 | 164 | 0.689981 | [
"render",
"3d"
] |
6dfa099c9c101e30508f70423e6b82e0cf63401a | 901 | hh | C++ | psdaq/drp/Opal.hh | slactjohnson/lcls2 | 87fb7a7a9b5030ed7a2a472fecfca6575e233889 | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/drp/Opal.hh | slactjohnson/lcls2 | 87fb7a7a9b5030ed7a2a472fecfca6575e233889 | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/drp/Opal.hh | slactjohnson/lcls2 | 87fb7a7a9b5030ed7a2a472fecfca6575e233889 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #pragma once
#include "BEBDetector.hh"
namespace Drp {
class OpalTT;
class OpalTTSim;
class Opal : public BEBDetector
{
public:
Opal(Parameters* para, MemPool* pool);
~Opal();
nlohmann::json connectionInfo() override;
void slowupdate(XtcData::Xtc&) override;
void shutdown() override;
void write_image(XtcData::Xtc&, std::vector< XtcData::Array<uint8_t> >&, XtcData::NamesId&);
protected:
void _connect (PyObject*) override;
unsigned _configure(XtcData::Xtc&, XtcData::ConfigIter&) override;
void _event (XtcData::Xtc&,
std::vector< XtcData::Array<uint8_t> >&) override;
protected:
friend class OpalTT;
friend class OpalTTSim;
XtcData::NamesId m_evtNamesId;
unsigned m_rows;
unsigned m_columns;
OpalTT* m_tt;
OpalTTSim* m_sim;
};
}
| 24.351351 | 96 | 0.619312 | [
"vector"
] |
a3011f006ca618611cc615651b28040530178eac | 6,823 | cpp | C++ | RLSC1/vreprlsc/programming/v_repExtMtb/mtbRobotContainer.cpp | ichalkiad/RLSC_BaxterSimulation | 1a15f2b06521378af056a40c3765d7e6c6823596 | [
"MIT"
] | null | null | null | RLSC1/vreprlsc/programming/v_repExtMtb/mtbRobotContainer.cpp | ichalkiad/RLSC_BaxterSimulation | 1a15f2b06521378af056a40c3765d7e6c6823596 | [
"MIT"
] | null | null | null | RLSC1/vreprlsc/programming/v_repExtMtb/mtbRobotContainer.cpp | ichalkiad/RLSC_BaxterSimulation | 1a15f2b06521378af056a40c3765d7e6c6823596 | [
"MIT"
] | null | null | null | // Copyright 2006-2013 Dr. Marc Andreas Freese. All rights reserved.
// marc@coppeliarobotics.com
// www.coppeliarobotics.com
//
// -------------------------------------------------------------------
// This file 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.
//
// You are free to use/modify/distribute this file for whatever purpose!
// -------------------------------------------------------------------
//
// This file was automatically created for V-REP release V3.0.4 on July 8th 2013
//**************************************************
// This class represents a container for CMtbRobot
// objects.
// This container should make sure that if a MTB
// model in a V-REP scene is added/removed, that
// its corresponding CMtbRobot object is also
// added/removed.
//**************************************************
#include "mtbRobotContainer.h"
#include "Access.h"
#include "v_repLib.h"
#include "mtbGlobal.h"
CMtbRobotContainer::CMtbRobotContainer()
{
}
CMtbRobotContainer::~CMtbRobotContainer()
{
removeAll();
}
void CMtbRobotContainer::removeAll()
{
for (int i=0;i<getCount();i++)
delete _allMtbRobots[i];
_allMtbRobots.clear();
}
void CMtbRobotContainer::removeFromID(int theID)
{
for (int i=0;i<getCount();i++)
{
if (_allMtbRobots[i]->getID()==theID)
{
delete _allMtbRobots[i];
_allMtbRobots.erase(_allMtbRobots.begin()+i);
break;
}
}
}
int CMtbRobotContainer::insert(CMtbRobot* theMtbRobot)
{
int newID=0;
while (getFromID(newID)!=NULL)
newID++;
_allMtbRobots.push_back(theMtbRobot);
theMtbRobot->setID(newID);
return(newID);
}
CMtbRobot* CMtbRobotContainer::getFromID(int theID)
{
for (int i=0;i<getCount();i++)
{
if (_allMtbRobots[i]->getID()==theID)
return(_allMtbRobots[i]);
}
return(NULL);
}
CMtbRobot* CMtbRobotContainer::getFromIndex(int ind)
{
if ( (ind<0)||(ind>=getCount()) )
return(NULL);
return(_allMtbRobots[ind]);
}
CMtbRobot* CMtbRobotContainer::getFromAssociatedObject(int theAssociatedObjectID)
{
for (int i=0;i<getCount();i++)
{
if (_allMtbRobots[i]->getAssociatedObject()==theAssociatedObjectID)
return(_allMtbRobots[i]);
}
return(NULL);
}
int CMtbRobotContainer::getCount()
{
return(int(_allMtbRobots.size()));
}
void CMtbRobotContainer::startOfSimulation()
{ // Relay the message to all CMtbRobot objects:
for (int i=0;i<getCount();i++)
_allMtbRobots[i]->startOfSimulation();
}
void CMtbRobotContainer::endOfSimulation()
{ // Relay the message to all CMtbRobot objects:
for (int i=0;i<getCount();i++)
_allMtbRobots[i]->endOfSimulation();
}
void CMtbRobotContainer::actualizeForSceneContent()
{ // This is called everytime the scene content in V-REP might have changed (e.g. object added/removed/etc.)
// We need to make sure that every MTB model in V-REP's scene has exactly one CMtbRobot in this container.
// We now synchronize this container with current V-REP's scene content:
// 1. We first check which CMtbRobot is not valid anymore, and remove it
int i=0;
while (i<int(_allMtbRobots.size()))
{
CMtbRobot* mtbRobot=_allMtbRobots[i];
int associatedObject=mtbRobot->getAssociatedObject(); // this is the scene object handle
int uniqueID;
if (simGetObjectUniqueIdentifier(associatedObject,&uniqueID)==-1)
{ // the scene object doesn't exist anymore!
removeFromID(mtbRobot->getID()); // we remove its associated CMtbRobot object
i=-1; // ordering in _allMtbRobots might have changed, we start from the beginning
}
else
{ // An object with that handle exists, is its unique ID same as getAssociatedObjectUniqueId()? (a scene object handle can be re-used!)
if (uniqueID!=mtbRobot->getAssociatedObjectUniqueId())
{ // the object doesn't exist anymore! (the object was destroyed and then another object was assigned the same handle (e.g. new scene was loaded))
removeFromID(mtbRobot->getID());
i=-1; // ordering in _allMtbRobots might have changed, we start from the beginning
}
else
{ // the object still exists. Does it still have its MTB_BASE tag?
// a. Get all the developer data attached to this object (this is custom data added by the developer):
int buffSize=simGetObjectCustomDataLength(associatedObject,DEVELOPER_DATA_HEADER);
char* datBuff=new char[buffSize];
simGetObjectCustomData(associatedObject,DEVELOPER_DATA_HEADER,datBuff);
std::vector<unsigned char> developerCustomData(datBuff,datBuff+buffSize);
delete[] datBuff;
// b. From that retrieved data, try to extract sub-data with the MTB_BASE tag:
std::vector<unsigned char> mtbData;
if (!CAccess::extractSerializationData(developerCustomData,MTB_BASE,mtbData))
{ // No, there is no data with the MTB_BASE tag present! We remove this object:
removeFromID(mtbRobot->getID());
i=-1; // ordering in _allMtbRobots might have changed, we start from the beginning
}
}
}
i++;
}
// 2. Now all CMtbRobot objects in this container are up-to-date. We now go through all objects in the scene
// that have the MTB_BASE tag, and check if they have a related CMtbRobot object in this container.
// If not, we have to add a related CMtbRobot object:
int objHandle=0;
int ind=0;
while (objHandle!=-1)
{
objHandle=simGetObjects(ind++,sim_handle_all);
if (objHandle!=-1)
{ // Scene object present at index ind
// Is that scene object already associated with a CMtbRobot object?
if (getFromAssociatedObject(objHandle)==NULL)
{ // No, not yet
// Does the object have a MTB_BASE tag?
// a. Get all the developer data attached to this object (this is custom data added by the developer):
int buffSize=simGetObjectCustomDataLength(objHandle,DEVELOPER_DATA_HEADER);
char* datBuff=new char[buffSize];
simGetObjectCustomData(objHandle,DEVELOPER_DATA_HEADER,datBuff);
std::vector<unsigned char> developerCustomData(datBuff,datBuff+buffSize);
delete[] datBuff;
// b. From that retrieved data, try to extract sub-data with the MTB_BASE tag:
std::vector<unsigned char> mtbData;
if (CAccess::extractSerializationData(developerCustomData,MTB_BASE,mtbData))
{ // Yes, the tag is there. We have to add a new CMtbRobot object associated with this scene object:
CMtbRobot* mtbRobot=new CMtbRobot();
insert(mtbRobot);
int uniqueID;
simGetObjectUniqueIdentifier(objHandle,&uniqueID);
mtbRobot->setAssociatedObject(objHandle,uniqueID);
mtbRobot->readCCustomDataFromSceneObject(); // Make sure the CMtbRobot object has the same values
}
}
}
}
}
| 35.352332 | 150 | 0.683717 | [
"object",
"vector",
"model"
] |
a302cffbc6441fe96ed8ce82ae1b6ec3a33838b3 | 1,719 | cpp | C++ | openbr/gui/classifier.cpp | Rires-hy/OPENBR_SMT | 8ffd1fbe5802a1c85434119d8fc0797259cf95f4 | [
"Apache-2.0"
] | null | null | null | openbr/gui/classifier.cpp | Rires-hy/OPENBR_SMT | 8ffd1fbe5802a1c85434119d8fc0797259cf95f4 | [
"Apache-2.0"
] | null | null | null | openbr/gui/classifier.cpp | Rires-hy/OPENBR_SMT | 8ffd1fbe5802a1c85434119d8fc0797259cf95f4 | [
"Apache-2.0"
] | null | null | null | #include <QtConcurrentRun>
#include <openbr/openbr_plugin.h>
#include "classifier.h"
using namespace br;
/**** CLASSIFIER ****/
/*** PUBLIC ***/
GUIClassifier::GUIClassifier(QWidget *parent)
: QLabel(parent)
{
setAlignment(Qt::AlignCenter);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
connect(this, SIGNAL(newClassification(QString,QString)), this, SLOT(setClassification(QString,QString)));
}
void GUIClassifier::setAlgorithm(const QString &algorithm)
{
this->algorithm = algorithm;
}
/*** PUBLIC SLOTS ***/
void GUIClassifier::classify(const File &file)
{
QtConcurrent::run(this, &GUIClassifier::_classify, file);
}
/*** PRIVATE SLOTS ***/
void GUIClassifier::setClassification(const QString &key, const QString &value)
{
if (key.isEmpty()) clear();
else setText(QString("%1: <b>%2</b>").arg(key, value));
}
/*** PRIVATE ***/
void GUIClassifier::_classify(File file)
{
QString key, value;
QSharedPointer<Transform> transform = Transform::fromAlgorithm(algorithm);
TemplateList input, output;
input.append(file);
transform->projectUpdate(input, output);
foreach (const File &f, output.files() ) {
if (algorithm == "GenderClassification") key = "Gender";
else if (algorithm == "AgeRegression") key = "Age";
else key = algorithm;
if (!f.contains(key)) continue;
if (algorithm == "AgeRegression") value = QString::number(int(f.get<float>(key)+0.5)) + " Years";
else value = f.get<QString>(key);
break;
}
emit newClassification(key, value);
}
#include "moc_classifier.cpp"
| 27.285714 | 110 | 0.630599 | [
"transform"
] |
a306847f356a676ebec5df8ff276c37e3da91453 | 20,661 | cpp | C++ | src/FunctionInvocation.cpp | jiezzhang/CLSmith | a39a31c43c88352fc65e61dce270d8e1660cbcf0 | [
"BSD-2-Clause"
] | null | null | null | src/FunctionInvocation.cpp | jiezzhang/CLSmith | a39a31c43c88352fc65e61dce270d8e1660cbcf0 | [
"BSD-2-Clause"
] | null | null | null | src/FunctionInvocation.cpp | jiezzhang/CLSmith | a39a31c43c88352fc65e61dce270d8e1660cbcf0 | [
"BSD-2-Clause"
] | null | null | null | // -*- mode: C++ -*-
//
// Copyright (c) 2007, 2008, 2009, 2010, 2011 The University of Utah
// All rights reserved.
//
// This file is part of `csmith', a random generator of C programs.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
// This file was derived from a random program generator written by Bryan
// Turner. The attributions in that file was:
//
// Random Program Generator
// Bryan Turner (bryan.turner@pobox.com)
// July, 2005
//
#include "FunctionInvocation.h"
#include <cassert>
#include "Common.h"
#include "CGContext.h"
#include "Effect.h"
#include "Expression.h"
#include "ExpressionVariable.h"
#include "ExpressionFuncall.h"
#include "Function.h"
#include "FunctionInvocationBinary.h"
#include "FunctionInvocationUnary.h"
#include "FunctionInvocationUser.h"
#include "Type.h"
#include "Block.h"
#include "VectorFilter.h"
#include "FactMgr.h"
#include "random.h"
#include "Variable.h"
#include "Bookkeeper.h"
#include "SafeOpFlags.h"
#include "CVQualifiers.h"
#include "Error.h"
#include "Probabilities.h"
#include "CompatibleChecker.h"
#include "DepthSpec.h"
#include "Constant.h"
#include "CGOptions.h"
#include "CLSmith/ExpressionVector.h"
using namespace std;
///////////////////////////////////////////////////////////////////////////////
/*
* XXX
*/
FunctionInvocation *
FunctionInvocation::make_random(bool is_std_func,
CGContext &cg_context,
const Type* type,
const CVQualifiers* qfer)
{
FunctionInvocation *fi = 0;
// If we are looking for a program-defined function, try to find one.
if (!is_std_func) {
Function* callee = NULL;
if (pure_rnd_flipcoin(50)) {
callee = Function::choose_func(get_all_functions(), cg_context, type, qfer);
}
if (callee != NULL) {
FunctionInvocationUser *fiu = new FunctionInvocationUser(callee, true, NULL);
fiu->build_invocation(callee, cg_context);
fi = fiu;
if (!fiu->failed) {
cg_context.get_current_func()->fact_changed |= fiu->func->fact_changed;
}
}
else if (!Function::reach_max_functions_cnt()) {
fi = FunctionInvocationUser::build_invocation_and_function(cg_context, type, qfer);
} else {
// we can not find/create a function because we reach the limit, so give up
fi = new FunctionInvocationUser(NULL, false, NULL);
fi->failed = true;
return fi;
}
}
// now use standard functions, i.e., binary/unary operators to create an invocation
if (fi == NULL) {
int rnd_flag = rnd_flipcoin(StdUnaryFuncProb);
if (rnd_flag) {
fi = make_random_unary(cg_context, type);
} else {
fi = make_random_binary(cg_context, type);
}
}
assert(fi != 0);
return fi;
}
/*
* TODO: FIX! This is a bogus constructor, used only by the `OutputMain'.
* The problem is, there is no representation for the calling function,
* so we "just use" `*target'. Bah!
*/
FunctionInvocation *
FunctionInvocation::make_random(Function *target,
CGContext &cg_context)
{
FunctionInvocationUser *fi = new FunctionInvocationUser(target, true, NULL);
fi->build_invocation(target, cg_context);
ERROR_GUARD_AND_DEL1(NULL, fi);
assert(!fi->failed);
return fi;
}
/*
*
*/
FunctionInvocation *
FunctionInvocation::make_random_unary(CGContext &cg_context, const Type* type)
{
DEPTH_GUARD_BY_TYPE_RETURN(dtFunctionInvocationRandomUnary, NULL);
assert(type);
eUnaryOps op = (eUnaryOps)(rnd_upto(MAX_UNARY_OP, UNARY_OPS_PROB_FILTER));
ERROR_GUARD(NULL);
SafeOpFlags *flags = NULL;
if (op == eMinus && type->eType != eVector) {
flags = SafeOpFlags::make_random(sOpUnary);
ERROR_GUARD(NULL);
type = flags->get_lhs_type();
assert(type);
}
// Type restirctions for vectors.
if (type->eType == eVector) {
// Not returns signed type.
if (!type->is_signed() && op == eNot) {
op = ePlus;
}
// Unlikely, but ++ and -- might overflow.
if (type->is_signed() && (op == ePlus || op == eMinus)) {
op = eNot;
}
}
FunctionInvocation *fi = FunctionInvocationUnary::CreateFunctionInvocationUnary(cg_context, op, flags);
Expression *operand = Expression::make_random(cg_context, type);
ERROR_GUARD_AND_DEL1(NULL, fi);
fi->param_value.push_back(operand);
return fi;
}
/*
*
*/
FunctionInvocation *
FunctionInvocation::make_random_binary(CGContext &cg_context, const Type* type)
{
DEPTH_GUARD_BY_TYPE_RETURN(dtFunctionInvocationRandomBinary, NULL);
if (rnd_flipcoin(10) && Type::has_pointer_type() && type->eType != eVector) {
ERROR_GUARD(NULL);
return make_random_binary_ptr_comparison(cg_context);
}
eBinaryOps op = (eBinaryOps)(rnd_upto(MAX_BINARY_OP, BINARY_OPS_PROB_FILTER));
ERROR_GUARD(NULL);
assert(type);
SafeOpFlags *flags = SafeOpFlags::make_random(sOpBinary, op);
assert(flags);
ERROR_GUARD(NULL);
// Special stuff for vectors.
if (type->eType == eVector) {
// Only signed type can use logicals. Also no div or mod.
// TODO: Instead of changing the op, flip the sign of the type.
if (!type->is_signed() && (
op==eCmpGt || op==eCmpLt || op==eCmpGe || op==eCmpLe ||
op==eCmpEq || op==eCmpNe || op==eAnd || op==eOr ||
op==eDiv || op==eMod)) {
op = eAdd;
}
// Only unsigned can use unsafe ops.
if (type->is_signed() && (
op==eAdd || op==eSub || op==eMul || op==eDiv ||
op==eMod || op==eRShift || op==eLShift)) {
op = eAnd;
}
delete flags;
flags = SafeOpFlags::make_dummy_flags();
}
FunctionInvocationBinary *fi = FunctionInvocationBinary::CreateFunctionInvocationBinary(cg_context, op, flags);
Effect lhs_eff_accum;
CGContext lhs_cg_context(cg_context, cg_context.get_effect_context(), &lhs_eff_accum);
// Generate an expression with the correct type required by safe math operands
const Type* lhs_type = flags->get_lhs_type();
const Type* rhs_type = flags->get_rhs_type();
// More special stuff for vectors.
if (type->eType == eVector) {
lhs_type = type;
rhs_type = type;
}
assert(lhs_type && rhs_type);
Expression *lhs = Expression::make_random(lhs_cg_context, lhs_type);
ERROR_GUARD_AND_DEL1(NULL, fi);
Expression *rhs = 0;
cg_context.merge_param_context(lhs_cg_context, true);
FactMgr* fm = get_fact_mgr(&cg_context);
vector<const Fact*> facts_copy = fm->global_facts;
#if 0
if (lhs->term_type == eVariable) {
lhs_eff_accum.read_deref_volatile((ExpressionVariable*)lhs);
}
#endif
// If we are guaranteed that the LHS will be evaluated before the RHS,
// or if the LHS is pure (not merely side-effect-free),
// then we can generate the RHS under the original effect context.
if (IsOrderedStandardFunc(op)) { // || lhs_eff_accum.is_pure()) { TODO: need more thoughts on the purity issue.
rhs = Expression::make_random(cg_context, rhs_type);
}
else {
// Otherwise, the RHS must be generated under the combined effect
// of the original effect and the LHS effect.
Effect rhs_eff_context(cg_context.get_effect_context());
rhs_eff_context.add_effect(lhs_eff_accum, true);
Effect rhs_eff_accum;
CGContext rhs_cg_context(cg_context, rhs_eff_context, &rhs_eff_accum);
if (op == eLShift || op == eRShift) {
eTermType tt = MAX_TERM_TYPES;
bool not_constant = rnd_flipcoin(ShiftByNonConstantProb);
// avoid shifting negative or too much
if (!not_constant) {
rhs = lhs_type->eType == eVector ?
dynamic_cast<Expression*>(CLSmith::ExpressionVector::make_constant(rhs_type, lhs_type->SizeInBytes() * 8)) :
dynamic_cast<Expression*>(Constant::make_random_upto(lhs_type->SizeInBytes() * 8));
} else {
rhs = Expression::make_random(rhs_cg_context, rhs_type, NULL, false, true, tt);
}
}
else {
rhs = Expression::make_random(rhs_cg_context, rhs_type);
// avoid divide by zero or possible zero (reached by pointer comparison)
if ((op == eMod || op == eDiv) && (rhs->equals(0) || rhs->is_0_or_1())) {
VectorFilter f;
f.add(eMod).add(eDiv).add(eLShift).add(eRShift);
op = (eBinaryOps)(rnd_upto(MAX_BINARY_OP, &f));
fi->set_operation(op);
}
}
cg_context.merge_param_context(rhs_cg_context, true);
}
ERROR_GUARD_AND_DEL2(NULL, fi, lhs);
if (CompatibleChecker::compatible_check(lhs, rhs)) {
Error::set_error(COMPATIBLE_CHECK_ERROR);
delete lhs;
delete rhs;
delete fi;
return NULL;
}
// ordered operators such as "||" or "&&" may skip the 2nd parameter
if (IsOrderedStandardFunc(op)) {
fm->makeup_new_var_facts(facts_copy, fm->global_facts);
merge_facts(fm->global_facts, facts_copy);
}
// TODO: fix `rhs' for eLShift and eRShift and ...
// Currently, the "fix" is handled in `FunctionInvocationBinary::Output'.
fi->param_value.push_back(lhs);
fi->param_value.push_back(rhs);
return fi;
}
/*
*
*/
FunctionInvocation *
FunctionInvocation::make_random_binary_ptr_comparison(CGContext &cg_context)
{
eBinaryOps op = rnd_flipcoin(50) ? eCmpEq : eCmpNe;
ERROR_GUARD(NULL);
SafeOpFlags *flags = SafeOpFlags::make_random(sOpBinary);
ERROR_GUARD(NULL);
FunctionInvocation *fi = FunctionInvocationBinary::CreateFunctionInvocationBinary(cg_context, op, flags);
const Type* type = Type::choose_random_pointer_type();
ERROR_GUARD_AND_DEL1(NULL, fi);
Effect lhs_eff_accum;
CGContext lhs_cg_context(cg_context, cg_context.get_effect_context(), &lhs_eff_accum);
lhs_cg_context.flags |= NO_DANGLING_PTR;
Expression *lhs = Expression::make_random(lhs_cg_context, type, 0, true);
ERROR_GUARD_AND_DEL1(NULL, fi);
cg_context.merge_param_context(lhs_cg_context, true);
// now focus on RHS ...
enum eTermType tt = MAX_TERM_TYPES;
// if LHS is const, there is no need for RHS to be const as well
if (lhs->term_type == eConstant) {
tt = eVariable;
}
Expression *rhs = 0;
// If we are guaranteed that the LHS will be evaluated before the RHS,
// or if the LHS is pure (not merely side-effect-free),
// then we can generate the RHS under the original effect context.
if (IsOrderedStandardFunc(op)) { // lhs_eff_accum.is_pure()) JYTODO: purity needs to be redefined
// although we don't need care about other side effect, we do
// need to pass in NO_DANGLING_PTR flag
unsigned int old_flag = cg_context.flags;
cg_context.flags |= NO_DANGLING_PTR;
rhs = Expression::make_random(cg_context, type, 0, true, false, tt);
cg_context.flags = old_flag;
} else {
// Otherwise, the RHS must be generated under the combined effect
// of the original effect and the LHS effect.
Effect rhs_eff_context(cg_context.get_effect_context());
rhs_eff_context.add_effect(lhs_eff_accum);
Effect rhs_eff_accum;
CGContext rhs_cg_context(cg_context, rhs_eff_context, &rhs_eff_accum);
rhs_cg_context.flags |= NO_DANGLING_PTR;
rhs = Expression::make_random(rhs_cg_context, type, 0, true, false, tt);
cg_context.merge_param_context(rhs_cg_context, true);
}
ERROR_GUARD_AND_DEL2(NULL, fi, lhs);
// typecast, if needed.
rhs->check_and_set_cast(&lhs->get_type());
// TODO: fix `rhs' for eLShift and eRShift and ...
// Currently, the "fix" is handled in `FunctionInvocationBinary::Output'.
fi->param_value.push_back(lhs);
fi->param_value.push_back(rhs);
fi->ptr_cmp = true;
// bookkeeping for pointers
Bookkeeper::record_pointer_comparisons(lhs, rhs);
return fi;
}
/*
*
*/
void
FunctionInvocation::add_operand(const Expression* e)
{
param_value.push_back(e);
}
void
FunctionInvocation::get_called_funcs(std::vector<const FunctionInvocationUser*>& funcs) const
{
// find calls in parameters
for (size_t i=0; i<param_value.size(); i++) {
const Expression* value = param_value[i];
value->get_called_funcs(funcs);
}
if (invoke_type == eFuncCall) {
const FunctionInvocationUser* func_call = (const FunctionInvocationUser*)this;
funcs.push_back(func_call);
}
}
bool
FunctionInvocation::has_uncertain_call(void) const
{
// if there are more than two function calls in two separate parameters,
// we judge both calls as uncertain because the evaluation order can be
// either left-to-right or right-to-left
int has_func_param_cnt = 0;
size_t i;
for (i=0; i<param_value.size(); i++) {
if (param_value[i]->func_count() > 0) {
has_func_param_cnt++;
}
}
return has_func_param_cnt >= 2;
}
bool
FunctionInvocation::has_uncertain_call_recursive(void) const
{
size_t i;
for (i=0; i<param_value.size(); i++) {
const Expression* e = param_value[i];
if (e->term_type == eFunction) {
const ExpressionFuncall* ef = (const ExpressionFuncall*)e;
if (ef->has_uncertain_call_recursive()) {
return true;
}
}
}
return has_uncertain_call();
}
bool
FunctionInvocation::has_simple_params(void) const
{
size_t i;
for (i=0; i<param_value.size(); i++) {
const Expression* e = param_value[i];
if (e->term_type == eFunction) {
return false;
}
}
return true;
}
vector<intvec>
FunctionInvocation::permute_param_oders(void) const
{
vector<intvec> ret;
intvec ret_base; // the ordered sequence
vector<int> base;
size_t i, j;
// shortcut for 2 parameters
if (param_value.size() == 2) {
ret_base.push_back(0);
ret_base.push_back(1);
ret.push_back(ret_base);
ret_base.clear();
ret_base.push_back(1);
ret_base.push_back(0);
ret.push_back(ret_base);
return ret;
}
// get initial order, mark those paramters that invoke function call
for (i=0; i<param_value.size(); i++) {
if (param_value[i]->func_count() > 0) {
base.push_back(i);
}
ret_base.push_back(i);
}
// permute
vector<intvec> permuted = permute(base);
for (i=0; i<permuted.size(); i++) {
intvec new_seq = permuted[i];
intvec tmp = ret_base;
for (j=0; j<new_seq.size(); j++) {
// plug back the new sequence into initial ordered sequence
int orig_pos = base[j];
int new_pos = new_seq[j];
tmp[orig_pos] = new_pos;
}
ret.push_back(tmp);
}
return ret;
}
bool
FunctionInvocation::visit_unordered_params(vector<const Fact*>& inputs, CGContext& cg_context) const
{
vector<const Fact*> inputs_copy = inputs;
vector<const Fact*> tmp;
vector<intvec> orders = permute_param_oders();
size_t i, j;
assert(orders.size() > 0);
// visit function calls with all possible orders
for (i=0; i<orders.size(); i++) {
intvec& order = orders[i];
inputs = inputs_copy;
for (j=0; j<order.size(); j++) {
int param_id = order[j];
const Expression* value = param_value[param_id];
if (!value->visit_facts(inputs, cg_context)) {
return false;
}
}
if (i==0) {
tmp = inputs;
}
else {
merge_facts(tmp, inputs);
}
}
inputs = tmp;
return true;
}
CVQualifiers
FunctionInvocation::get_qualifiers(void) const
{
CVQualifiers qfer;
if (invoke_type == eFuncCall) {
const FunctionInvocationUser* func_call = dynamic_cast<const FunctionInvocationUser*>(this);
assert(func_call->get_func());
assert(func_call->get_func()->rv);
qfer = func_call->get_func()->rv->qfer;
}
// for binary and unary operations, they only yield integers right now (no pointer arithmatic
// supported yet!), we assume they return non-const non-volatile int
else {
qfer.add_qualifiers(false, false);
}
return qfer;
}
bool
FunctionInvocation::visit_facts(vector<const Fact*>& inputs, CGContext& cg_context) const
{
bool unordered = false; //has_uncertain_call();
bool ok = false;
bool is_func_call = (invoke_type == eFuncCall);
static int g = 0;
Effect running_eff_context(cg_context.get_effect_context());
if (!unordered) {
// unsigned int flags = ptr_cmp ? (cg_context.flags | NO_DANGLING_PTR) : cg_context.flags;
for (size_t i=0; i<param_value.size(); i++) {
Effect param_eff_accum;
int h = g++;
CGContext param_cg_context(cg_context, running_eff_context, ¶m_eff_accum);
// the parameters might be function calls
const Expression* value = param_value[i];
if (h == 236)
BREAK_NOP; // for debugging
if (!value->visit_facts(inputs, param_cg_context)) {
return false;
}
// Update the "running effect context": the context that we must use
// when we generate subsequent parameters within this invocation.
running_eff_context.add_effect(param_eff_accum);
// Update the total effect of this invocation, too.
cg_context.merge_param_context(param_cg_context, !is_func_call);
}
ok = true;
}
else {
ok = visit_unordered_params(inputs, cg_context);
}
if (ok && is_func_call) {
// make a copy of env
vector<const Fact*> inputs_copy = inputs;
const FunctionInvocationUser* func_call = dynamic_cast<const FunctionInvocationUser*>(this);
Effect effect_accum;
//CGContext new_context(func_call->func, cg_context.get_effect_context(), &effect_accum);
CGContext new_context(cg_context, func_call->func, cg_context.get_effect_context(), &effect_accum);
ok = func_call->revisit(inputs, new_context);
if (ok) {
assert(cg_context.curr_blk);
//cg_context.add_external_effect(*new_context.get_effect_accum());
cg_context.add_visible_effect(*new_context.get_effect_accum(), cg_context.curr_blk);
Effect& func_effect = func_call->func->feffect;
func_effect.add_external_effect(*new_context.get_effect_accum(), cg_context.call_chain);
}
}
return ok;
}
/*
* Build an "invocation" of a unary operation.
*/
FunctionInvocation *
FunctionInvocation::make_unary(CGContext &cg_context, eUnaryOps op,
Expression *operand)
{
DEPTH_GUARD_BY_TYPE_RETURN(dtFunctionInvocationUnary, NULL);
SafeOpFlags *flags = SafeOpFlags::make_random(sOpUnary);
ERROR_GUARD(NULL);
FunctionInvocation *fi = FunctionInvocationUnary::CreateFunctionInvocationUnary(cg_context, op, flags);
fi->param_value.push_back(operand);
return fi;
}
/*
* Build an "invocation" of a binary operation.
*/
FunctionInvocation *
FunctionInvocation::make_binary(CGContext &cg_context, eBinaryOps op,
Expression *lhs, Expression *rhs)
{
DEPTH_GUARD_BY_TYPE_RETURN(dtFunctionInvocationBinary, NULL);
SafeOpFlags *flags = SafeOpFlags::make_random(sOpBinary);
ERROR_GUARD(NULL);
FunctionInvocation *fi = FunctionInvocationBinary::CreateFunctionInvocationBinary(cg_context, op, flags);
fi->param_value.push_back(lhs);
fi->param_value.push_back(rhs);
return fi;
}
/*
*
*/
///////////////////////////////////////////////////////////////////////////////
FunctionInvocation::FunctionInvocation(eInvocationType e, const SafeOpFlags *flags)
: invoke_type(e),
failed(false),
ptr_cmp(false),
op_flags(flags)
{
// Nothing to do
}
/*
* copy constructor
*/
FunctionInvocation::FunctionInvocation(const FunctionInvocation &fi)
: invoke_type(fi.invoke_type),
failed(fi.failed),
ptr_cmp(fi.ptr_cmp)
{
std::vector<const Expression*>::const_iterator i;
for (i = fi.param_value.begin(); i != fi.param_value.end(); ++i) {
const Expression *expr = (*i)->clone();
param_value.push_back(expr);
}
//assert(fi.op_flags);
op_flags = fi.op_flags ? fi.op_flags->clone() : 0;
}
/*
*
*/
FunctionInvocation::~FunctionInvocation(void)
{
std::vector<const Expression*>::const_iterator i;
for (i = param_value.begin(); i != param_value.end(); ++i) {
delete (*i);
}
param_value.clear();
if (op_flags)
delete op_flags;
}
///////////////////////////////////////////////////////////////////////////////
/*
* Return true if `eFunc' defines and order for the evaluation of its
* arguments.
*/
bool
FunctionInvocation::IsOrderedStandardFunc(eBinaryOps eFunc)
{
return ((eFunc == eAnd) || (eFunc == eOr));
}
///////////////////////////////////////////////////////////////////////////////
// Local Variables:
// c-basic-offset: 4
// tab-width: 4
// End:
// End of file.
| 30.563609 | 113 | 0.704758 | [
"vector"
] |
a307eefee8773773c27e4c991537dbe395b6bfed | 15,581 | cpp | C++ | apps/robot-map-gui/gui/glWidget/CGLWidget.cpp | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | 4 | 2017-08-04T15:44:04.000Z | 2021-02-02T02:00:18.000Z | apps/robot-map-gui/gui/glWidget/CGLWidget.cpp | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | null | null | null | apps/robot-map-gui/gui/glWidget/CGLWidget.cpp | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | 2 | 2017-10-03T23:10:09.000Z | 2018-07-29T09:41:33.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+
*/
#include "CGLWidget.h"
#include "mrpt/maps/TMetricMapInitializer.h"
#include "mrpt/utils/CConfigFile.h"
#include "mrpt/utils/CFileGZOutputStream.h"
#include "mrpt/utils/CFileGZInputStream.h"
#include "mrpt/opengl/CPointCloud.h"
#include "mrpt/opengl/CTexturedPlane.h"
#include "mrpt/gui/CGlCanvasBase.h"
#include "mrpt/opengl/stock_objects.h"
#include "mrpt/math/geometry.h"
#include "CDocument.h"
#include "cmath"
#include <QMouseEvent>
#include <QApplication>
#include <QDebug>
// Include libraries in linking (needed for Windows)
#include <mrpt/config.h>
#if defined(_MSC_VER)
#pragma comment(lib, "opengl32.lib")
#endif
using namespace mrpt;
using namespace mrpt::opengl;
CGlWidget::CGlWidget(bool is2D, QWidget* parent)
: CQtGlCanvasBase(parent),
m_groundPlane(
mrpt::make_aligned_shared<CGridPlaneXY>(-200, 200, -200, 200, 0, 5)),
m_doc(nullptr),
m_miniMapSize(-1.0),
m_minimapPercentSize(0.25),
m_observationSize(10.),
m_observationColor(mrpt::utils::TColor::red),
m_selectedObsSize(15.0),
m_selectedColor(mrpt::utils::TColor::green),
m_isShowObs(false),
m_visiblePoints(mrpt::make_aligned_shared<CPointCloud>()),
m_selectedPointsCloud(mrpt::make_aligned_shared<CPointCloud>()),
m_currentObs(opengl::stock_objects::CornerXYZSimple()),
m_line(mrpt::make_aligned_shared<CSetOfLines>()),
m_is2D(is2D),
m_showRobot(false)
{
setClearColors(1.0, 1.0, 1.0);
m_visiblePoints->setColor(m_observationColor);
m_visiblePoints->setPointSize(m_observationSize);
m_selectedPointsCloud->setColor(m_selectedColor);
m_selectedPointsCloud->setPointSize(m_selectedObsSize);
if (m_is2D)
{
m_miniMapViewport = getOpenGLSceneRef()->createViewport("miniMap");
m_miniMapViewport->setBorderSize(2);
m_miniMapViewport->setViewportPosition(
0.01, 0.01, m_minimapPercentSize, m_minimapPercentSize);
m_miniMapViewport->setTransparent(false);
setAzimuthDegrees(-90.0f);
setElevationDegrees(90.0f);
CCamera& camMiniMap = m_miniMapViewport->getCamera();
updateCameraParams(camMiniMap);
camMiniMap.setOrthogonal();
}
updateCamerasParams();
m_groundPlane->setColor(0.4, 0.4, 0.4);
setVisibleGrid(true);
}
CGlWidget::~CGlWidget() {}
void CGlWidget::fillMap(const CSetOfObjects::Ptr& renderizableMap)
{
insertToMap(renderizableMap);
m_map = renderizableMap;
float xMin = 0;
float xMax = 0;
float yMin = 0;
float yMax = 0;
if (m_is2D)
{
if (m_map->size() == 1)
{
CRenderizable* ren = m_map->begin()->get();
CTexturedPlane* textured = dynamic_cast<CTexturedPlane*>(ren);
if (textured)
{
textured->getPlaneCorners(xMin, xMax, yMin, yMax);
}
else
{
CPointCloud* points = dynamic_cast<CPointCloud*>(ren);
if (points)
{
const std::vector<float>& arrayX = points->getArrayX();
const std::vector<float>& arrayY = points->getArrayY();
for (auto& itX : arrayX)
{
xMin = std::min(xMin, itX);
xMax = std::max(xMax, itX);
}
for (auto& itY : arrayY)
{
yMin = std::min(yMin, itY);
yMax = std::max(yMax, itY);
}
}
}
}
float xDist = xMax - xMin;
float yDist = yMax - yMin;
CCamera& camMiniMap = m_miniMapViewport->getCamera();
updateCameraParams(camMiniMap);
camMiniMap.setZoomDistance(std::max(xDist, yDist));
updateCamerasParams();
}
if (m_isShowObs)
setSelectedObservation(m_isShowObs);
else
update();
}
void CGlWidget::setSelected(const math::TPose3D& pose)
{
if (!m_map) return;
removeRobotDirection();
m_showRobot = true;
m_currentObs->setPose(pose);
m_map->insert(m_currentObs);
update();
}
void CGlWidget::setSelectedObservation(bool is)
{
m_isShowObs = is;
if (!m_doc || !m_map) return;
if (is)
{
m_map->insert(m_visiblePoints);
m_map->insert(m_selectedPointsCloud);
}
else
{
m_map->removeObject(m_visiblePoints);
m_map->removeObject(m_selectedPointsCloud);
m_selectedPointsCloud->clear();
removeRobotDirection();
}
update();
}
void CGlWidget::setLaserScan(CPlanarLaserScan::Ptr laserScan)
{
if (m_currentLaserScan) m_map->removeObject(m_currentLaserScan);
m_currentLaserScan = laserScan;
m_map->insert(m_currentLaserScan);
update();
}
void CGlWidget::setDocument(CDocument* doc)
{
m_doc = doc;
if (m_isShowObs)
{
m_map->removeObject(m_visiblePoints);
m_map->removeObject(m_selectedPointsCloud);
}
m_selectedPointsCloud->clear();
m_visiblePoints->clear();
for (auto iter = m_doc->simplemap().begin();
iter != m_doc->simplemap().end(); ++iter)
{
math::TPose3D pose = iter->first->getMeanVal();
m_visiblePoints->insertPoint(pose.x, pose.y, pose.z);
}
if (m_isShowObs) setSelectedObservation(m_isShowObs);
}
void CGlWidget::setZoom(float zoom)
{
CamaraParams params = cameraParams();
params.cameraZoomDistance = zoom;
setCameraParams(params);
updateCamerasParams();
update();
}
float CGlWidget::getZoom() const { return getZoomDistance(); }
void CGlWidget::setAzimuthDegrees(float ang)
{
CQtGlCanvasBase::setAzimuthDegrees(ang);
emit azimuthChanged(ang);
updateCamerasParams();
}
void CGlWidget::setElevationDegrees(float ang)
{
CQtGlCanvasBase::setElevationDegrees(ang);
emit elevationChanged(ang);
updateCamerasParams();
}
void CGlWidget::setBackgroundColor(float r, float g, float b, float a)
{
setClearColors(r, g, b, a);
update();
}
void CGlWidget::setGridColor(double r, double g, double b, double a)
{
m_groundPlane->setColor(r, g, b, a);
update();
}
void CGlWidget::setVisibleGrid(bool is)
{
if (is)
insertToMap(m_groundPlane);
else
removeFromMap(m_groundPlane);
}
bool CGlWidget::setBot(int value)
{
if (!m_map) return false;
math::TPose3D pose;
if (m_showRobot)
{
m_map->removeObject(m_currentObs);
pose = m_currentObs->getPose();
}
mrpt::opengl::CSetOfObjects::Ptr currentObs = m_currentObs;
switch (value)
{
case 0:
m_currentObs = opengl::stock_objects::CornerXYZSimple();
break;
case 1:
m_currentObs = opengl::stock_objects::CornerXYZ();
break;
case 2:
m_currentObs = opengl::stock_objects::RobotGiraff();
break;
case 3:
m_currentObs = opengl::stock_objects::RobotRhodon();
break;
case 4:
m_currentObs = opengl::stock_objects::RobotPioneer();
break;
case 5:
m_currentObs = opengl::stock_objects::BumblebeeCamera();
break;
default:
m_currentObs = opengl::stock_objects::CornerXYZSimple();
break;
}
if (m_showRobot)
{
m_currentObs->setPose(pose);
m_map->insert(m_currentObs);
return currentObs != m_currentObs;
}
return false;
}
bool CGlWidget::setObservationSize(double s)
{
if (m_observationSize != s)
{
m_observationSize = s;
m_visiblePoints->setPointSize(m_observationSize);
return true;
}
return false;
}
bool CGlWidget::setObservationColor(int type)
{
utils::TColorf color = typeToColor(type);
if (color.R != m_observationColor.R || color.B != m_observationColor.B ||
color.G != m_observationColor.G || color.A != m_observationColor.A)
{
m_observationColor = color;
m_visiblePoints->setColor(m_observationColor);
return true;
}
return false;
}
bool CGlWidget::setSelectedObservationSize(double s)
{
if (m_selectedObsSize != s)
{
m_selectedObsSize = s;
m_selectedPointsCloud->setPointSize(m_selectedObsSize);
return true;
}
return false;
}
bool CGlWidget::setSelectedObservationColor(int type)
{
utils::TColorf color = typeToColor(type);
if (color.R != m_selectedColor.R || color.B != m_selectedColor.B ||
color.G != m_selectedColor.G || color.A != m_selectedColor.A)
{
m_selectedColor = color;
m_selectedPointsCloud->setColor(m_selectedColor);
return true;
}
return false;
}
void CGlWidget::resizeGL(int width, int height)
{
CQtGlCanvasBase::resizeGL(width, height);
if (m_is2D)
{
GLint win_dims[4];
glGetIntegerv(GL_VIEWPORT, win_dims);
m_miniMapSize =
std::min(win_dims[2], win_dims[3]) * m_minimapPercentSize;
}
updateMinimapPos();
}
void CGlWidget::updateCamerasParams()
{
float zoom = getCameraZoomDistance();
CQtGlCanvasBase::updateCamerasParams();
if (m_is2D)
{
CCamera& camMiniMap = m_miniMapViewport->getCamera();
float zoomMiniMap = camMiniMap.getZoomDistance();
updateCameraParams(camMiniMap);
camMiniMap.setProjectiveModel(false);
camMiniMap.setZoomDistance(zoomMiniMap);
}
if (zoom != getZoomDistance()) emit zoomChanged(getZoomDistance());
}
void CGlWidget::insertToMap(const CRenderizable::Ptr& newObject)
{
CQtGlCanvasBase::insertToMap(newObject);
if (m_is2D)
{
assert(m_miniMapViewport);
m_miniMapViewport->insert(newObject);
}
}
void CGlWidget::removeFromMap(const CRenderizable::Ptr& newObject)
{
CQtGlCanvasBase::removeFromMap(newObject);
if (m_is2D)
{
assert(m_miniMapViewport);
m_miniMapViewport->removeObject(newObject);
}
}
void CGlWidget::mouseMoveEvent(QMouseEvent* event)
{
CQtGlCanvasBase::mouseMoveEvent(event);
std::pair<bool, math::TPoint3D> scenePos = sceneToWorld(event->pos());
if (scenePos.first)
emit mousePosChanged(scenePos.second.x, scenePos.second.y);
}
void CGlWidget::mousePressEvent(QMouseEvent* event)
{
CQtGlCanvasBase::mousePressEvent(event);
if (!m_isShowObs) return;
QPoint pos = event->pos();
bool isPressCtrl = event->modifiers() == Qt::ControlModifier;
QPoint otherPos(pos.x() + m_observationSize, pos.y() + m_observationSize);
auto scenePos = sceneToWorld(pos);
auto sceneOtherPos = sceneToWorld(otherPos);
if (scenePos.first && sceneOtherPos.first)
{
double xDistPow =
std::pow(sceneOtherPos.second.x - scenePos.second.x, 2);
double yDistPow =
std::pow(sceneOtherPos.second.y - scenePos.second.y, 2);
double maxDist = xDistPow + yDistPow;
bool updateScene = false;
if (isPressCtrl)
{
int i = searchSelectedPose(
scenePos.second.x, scenePos.second.y, maxDist);
if (i != -1)
{
auto point = removeFromSelected(i);
setVisiblePose(point.x, point.y, point.z);
updateScene = true;
}
}
else if (deselectAll())
update();
if (!updateScene)
{
int i = searchPose(scenePos.second.x, scenePos.second.y, maxDist);
if (i != -1)
{
removeFromVisible(i);
selectPose(
scenePos.second.x, scenePos.second.y, getSafeZPose());
updateScene = true;
}
}
if (updateScene)
{
update();
unpressMouseButtons();
}
}
}
utils::TColorf CGlWidget::typeToColor(int type) const
{
mrpt::utils::TColor color = mrpt::utils::TColor::red;
;
switch (type)
{
case 0:
color = mrpt::utils::TColor::red;
break;
case 1:
color = mrpt::utils::TColor::green;
break;
case 2:
color = mrpt::utils::TColor::blue;
break;
case 3:
color = mrpt::utils::TColor::white;
break;
case 4:
color = mrpt::utils::TColor::black;
break;
case 5:
color = mrpt::utils::TColor::gray;
break;
default:
break;
}
return mrpt::utils::TColorf(color);
}
std::pair<bool, math::TPoint3D> CGlWidget::sceneToWorld(const QPoint& pos) const
{
mrpt::math::TLine3D outRay;
mainViewport()->get3DRayForPixelCoord(pos.x(), pos.y(), outRay);
const mrpt::math::TPlane groundPlane(
mrpt::math::TPoint3D(0, 0, 0), mrpt::math::TPoint3D(1, 0, 0),
mrpt::math::TPoint3D(0, 1, 0));
// Intersection of the line with the plane:
mrpt::math::TObject3D inters;
mrpt::math::intersect(outRay, groundPlane, inters);
// Interpret the intersection as a point, if there is an intersection:
mrpt::math::TPoint3D intersPt;
bool converted = inters.getPoint(intersPt);
return std::make_pair(converted, intersPt);
}
int CGlWidget::searchPoseFromList(
float x, float y, double maxDist, const std::vector<float>& xs,
const std::vector<float>& ys) const
{
assert(xs.size() == ys.size());
std::map<double, int> minDistPos;
for (size_t i = 0; i < xs.size(); ++i)
{
double dist = std::pow(x - xs[i], 2) + std::pow(y - ys[i], 2);
if (dist < maxDist) minDistPos.emplace(dist, static_cast<int>(i));
}
if (minDistPos.empty()) return -1;
return minDistPos.begin()->second;
}
math::TPoint3D CGlWidget::removePoseFromPointsCloud(
CPointCloud::Ptr pointsCloud, int index) const
{
auto xs = pointsCloud->getArrayX();
auto ys = pointsCloud->getArrayY();
auto zs = pointsCloud->getArrayZ();
assert(xs.size() == ys.size() && xs.size() == zs.size());
assert(index < xs.size());
math::TPoint3D point;
auto itX = xs.begin() + index;
point.x = *itX;
xs.erase(itX);
auto itY = ys.begin() + index;
point.y = *itY;
ys.erase(itY);
auto itZ = zs.begin() + index;
point.z = *itZ;
zs.erase(itZ);
pointsCloud->setAllPoints(xs, ys, zs);
return point;
}
void CGlWidget::removeRobotDirection()
{
m_map->removeObject(m_currentObs);
if (m_currentLaserScan) m_map->removeObject(m_currentLaserScan);
m_showRobot = false;
}
void CGlWidget::updateMinimapPos()
{
if (!m_is2D) return;
GLint win_dims[4];
glGetIntegerv(GL_VIEWPORT, win_dims);
COpenGLViewport::Ptr miniMap = getOpenGLSceneRef()->getViewport("miniMap");
float w = m_miniMapSize / win_dims[2];
float h = m_miniMapSize / win_dims[3];
miniMap->setViewportPosition(0.01, 0.01, w, h);
}
int CGlWidget::searchSelectedPose(float x, float y, double maxDist)
{
auto xs = m_selectedPointsCloud->getArrayX();
auto ys = m_selectedPointsCloud->getArrayY();
return searchPoseFromList(x, y, maxDist, xs, ys);
}
int CGlWidget::searchPose(float x, float y, double maxDist)
{
auto xs = m_visiblePoints->getArrayX();
auto ys = m_visiblePoints->getArrayY();
return searchPoseFromList(x, y, maxDist, xs, ys);
}
math::TPoint3D CGlWidget::removeFromSelected(int index)
{
return removePoseFromPointsCloud(m_selectedPointsCloud, index);
}
void CGlWidget::selectPose(float x, float y, float z)
{
m_selectedPointsCloud->insertPoint(x, y, z);
math::TPose3D clickedPose(x, y, z, 0.0, 0.0, 0.0);
setSelected(clickedPose);
}
void CGlWidget::setVisiblePose(float x, float y, float z)
{
m_visiblePoints->insertPoint(x, y, z);
}
bool CGlWidget::deselectAll()
{
auto xs = m_selectedPointsCloud->getArrayX();
auto ys = m_selectedPointsCloud->getArrayY();
auto zs = m_selectedPointsCloud->getArrayZ();
assert(xs.size() == ys.size() && xs.size() == zs.size());
auto xv = m_visiblePoints->getArrayX();
auto yv = m_visiblePoints->getArrayY();
auto zv = m_visiblePoints->getArrayZ();
assert(xv.size() == yv.size() && xv.size() == zv.size());
for (size_t i = 0; i < xs.size(); ++i)
{
xv.push_back(xs[i]);
yv.push_back(ys[i]);
zv.push_back(zs[i]);
}
m_visiblePoints->setAllPoints(xv, yv, zv);
bool changedVectors = xs.size();
xs.clear();
ys.clear();
zs.clear();
m_selectedPointsCloud->setAllPoints(xs, ys, zs);
removeRobotDirection();
return changedVectors;
}
float CGlWidget::getSafeZPose() const
{
auto zs = m_visiblePoints->getArrayZ();
float z = 0.0;
if (!zs.empty())
z = zs[0];
else
{
zs = m_selectedPointsCloud->getArrayZ();
if (!zs.empty()) z = zs[0];
}
return z;
}
math::TPoint3D CGlWidget::removeFromVisible(int index)
{
return removePoseFromPointsCloud(m_visiblePoints, index);
}
| 23.500754 | 80 | 0.690135 | [
"geometry",
"vector"
] |
a3106687cbd1998379a6403c0fbe74d1706d9ccd | 4,045 | cpp | C++ | aslam_backend_python/src/OptimizerCallback.cpp | ethz-asl/aslam_optimizer | 8e9dd18f9f0d8af461e88e108a3beda2003daf11 | [
"BSD-3-Clause"
] | 33 | 2017-04-26T13:30:49.000Z | 2022-02-25T01:52:22.000Z | aslam_backend_python/src/OptimizerCallback.cpp | ethz-asl/aslam_optimizer | 8e9dd18f9f0d8af461e88e108a3beda2003daf11 | [
"BSD-3-Clause"
] | 15 | 2017-02-14T16:02:31.000Z | 2020-05-12T06:07:22.000Z | aslam_backend_python/src/OptimizerCallback.cpp | ethz-asl/aslam_optimizer | 8e9dd18f9f0d8af461e88e108a3beda2003daf11 | [
"BSD-3-Clause"
] | 8 | 2017-06-28T04:17:08.000Z | 2021-04-10T04:58:36.000Z | /*
* OptimizerCallback.cpp
*
* Created on: 24.08.2016
* Author: Ulrich Schwesinger
*/
#include <string>
#include <numpy_eigen/boost_python_headers.hpp>
#include <aslam/backend/OptimizerBase.hpp>
#include <aslam/backend/OptimizerCallback.hpp>
#include <aslam/backend/OptimizerCallbackManager.hpp>
#include <aslam/python/ExportOptimizerCallbackEvent.hpp>
using namespace boost::python;
using namespace aslam::python;
using namespace aslam::backend::callback;
std::type_index event2typeid(const boost::python::object& o)
{
boost::python::extract<std::type_index> ext(boost::python::getattr(o, "__typeId", boost::python::object()));
if(ext.check()) { return ext(); }
throw std::runtime_error("Invalid event type!");
}
void addCallbackWrapper(Registry& registry, const boost::python::object& event, const boost::python::object& callback)
{
if (!boost::python::getattr(callback, "__call__", boost::python::object())) {
throw std::runtime_error("Invalid callback object, has to be a callable!");
}
if (boost::python::getattr(event, "__getitem__", boost::python::object())) {
for (int i=0; i<len(event); ++i) {
registry.add( {event2typeid(event[i])} , [callback]() {
callback();
});
}
} else {
registry.add(event2typeid(event), [callback]() {
callback();
});
}
}
void exportOptimizerCallback()
{
class_<std::type_index>("type_info", no_init);
class_<Event>("__CallbackEvent")
.def_readonly("currentCost", &Event::currentCost)
.def_readonly("previousLowestCost", &Event::previousLowestCost)
;
exportEvent<event::OPTIMIZATION_INITIALIZED>("EVENT_OPTIMIZATION_INITIALIZED",
"Right after the the initial cost has been computed.");
exportEvent<event::ITERATION_START>("EVENT_ITERATION_START",
"At the start of an iteration before any work has been done, "
"same state as in PER_ITERATION_END in previous iteration");
exportEvent<event::ITERATION_END>("EVENT_ITERATION_END",
"At the end of an iteration after all work has been done, "
"same state as in PER_ITERATION_START in next iteration");
exportEvent<event::LINEAR_SYSTEM_SOLVED>("EVENT_LINEAR_SYSTEM_SOLVED",
"Right after the linear system was solved");
exportEvent<event::DESIGN_VARIABLES_UPDATED>("EVENT_DESIGN_VARIABLES_UPDATED",
"Right after the design variables (X) have been updated.");
exportEvent<event::RESIDUALS_UPDATED>("EVENT_RESIDUALS_UPDATED",
"After the raw squared error for each error term has been updated but "
"before the m-estimators are applied to compute the effective cost. "
"This is the right event to update m-estimators based on residuals.");
exportEvent<event::COST_UPDATED>("EVENT_COST_UPDATED",
"Right after the m-estimators are applied to compute the effective cost.");
class_<Registry>("CallbackRegistry")
.def("add", &addCallbackWrapper, "Adds a callback for a specific event or a list of events")
.def("clear", (void (Registry::*)(void))&Registry::clear, "Removes all callbacks")
.def("clear", detail::make_function_aux(
[](Registry& registry, const object& event)
{ registry.clear(event2typeid(event)); },
default_call_policies(), boost::mpl::vector<void, Registry&, const object&>()),
"Removes all callbacks for a specific event")
.def("numCallbacks", detail::make_function_aux(
[](const Registry& registry, const object& event)
{ return registry.numCallbacks(event2typeid(event)); },
default_call_policies(), boost::mpl::vector<std::size_t, const Registry&, const object&>()),
"Number of callbacks for a specific event")
;
}
| 43.967391 | 118 | 0.64178 | [
"object",
"vector"
] |
a31360d7f12993e8c11bced6809a6c5dd601a5bb | 24,145 | cpp | C++ | Deprecated/Sorts/src/AttackManager.cpp | sleyzerzon/soar | 74a6f32ba1be3a7b3ed4eac0b44b0f4b2e981f71 | [
"Unlicense"
] | 1 | 2016-04-01T04:02:28.000Z | 2016-04-01T04:02:28.000Z | Deprecated/Sorts/src/AttackManager.cpp | sleyzerzon/soar | 74a6f32ba1be3a7b3ed4eac0b44b0f4b2e981f71 | [
"Unlicense"
] | null | null | null | Deprecated/Sorts/src/AttackManager.cpp | sleyzerzon/soar | 74a6f32ba1be3a7b3ed4eac0b44b0f4b2e981f71 | [
"Unlicense"
] | null | null | null | /*
This file is part of Sorts, an interface between Soar and ORTS.
(c) 2006 James Irizarry, Sam Wintermute, and Joseph Xu
Sorts 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.
Sorts is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Sorts; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <sys/time.h>
#include "AttackManager.h"
#include "general.h"
#include "AttackManagerRegistry.h"
#include "Circle.h"
#include "Sorts.h"
#include "ScriptObj.H"
#define CLASS_TOKEN "ATKMAN"
#define DEBUG_OUTPUT true
#include "OutputDefinitions.h"
#define WAIT_RATIO 0.5
#define RESUME_RATIO 0.85
#define USE_CANVAS_ATTACK_MANAGER
#define NO_WAITING
/***
* Functions used by the old sorts agent. We're leaving them here for now
* in case they get used later.
*/
inline int min(int a, int b) {
if (a < b) {
return a;
}
return b;
}
inline int max(int a, int b) {
if (a > b) {
return a;
}
return b;
}
inline int minRadius(GameObj* gob) {
switch (*gob->sod.shape) {
case SHAPE_RECTANGLE:
return min((*gob->sod.x2-*gob->sod.x1), (*gob->sod.y2-*gob->sod.y1))/2;
case SHAPE_CIRCLE:
return *gob->sod.radius;
default:
ASSERT(false);
}
}
inline int maxRadius(GameObj* gob) {
switch (*gob->sod.shape) {
case SHAPE_RECTANGLE:
return max((*gob->sod.x2-*gob->sod.x1), (*gob->sod.y2-*gob->sod.y1))/2;
case SHAPE_CIRCLE:
return *gob->sod.radius;
default:
ASSERT(false);
return *gob->sod.radius;
}
}
Vec2d getClosePos(GameObj* src, GameObj* tgt) {
int srcRadius = maxRadius(src);
int tgtRadius = maxRadius(tgt);
Vec2d srcPos(gobX(src), gobY(src));
Vec2d tgtPos(gobX(tgt), gobY(tgt));
return tgtPos - Vec2d(tgtPos - srcPos, srcRadius + tgtRadius);
}
void positionsOnRectangle( int ax, int ay, int tx1, int ty1, int tx2, int ty2,
int offset, int distBetween,
list<Vec2d>& positions)
{
ASSERT(distBetween > 0);
cout << "positions on rectangle\n";
enum Side { LEFT, RIGHT, TOP, BOTTOM };
Side s[4];
int posX1 = tx1 - offset;
int posY1 = ty1 - offset;
int posX2 = tx2 + offset;
int posY2 = ty2 + offset;
int closeX = -1, closeY = -1;
if (ax < tx1) {
if (ay < ty1) {
// upper left corner
int diffx = tx1 - ax;
int diffy = ty1 - ay;
if (diffx < diffy) {
s[0] = TOP; s[1] = LEFT; s[2] = BOTTOM; s[3] = RIGHT;
closeX = tx1;
}
else {
s[0] = LEFT; s[1] = TOP; s[2] = RIGHT; s[3] = BOTTOM;
closeY = ty1;
}
}
else if (ay > ty2) {
// lower left corner
int diffx = tx1 - ax;
int diffy = ay - ty2;
if (diffx < diffy) {
s[0] = BOTTOM; s[1] = LEFT; s[2] = TOP; s[3] = RIGHT;
closeX = tx1;
}
else {
s[0] = LEFT; s[1] = BOTTOM; s[2] = RIGHT; s[3] = TOP;
closeY = ty2;
}
}
else {
// left side
s[0] = LEFT; s[1] = BOTTOM; s[2] = TOP; s[3] = RIGHT;
closeY = ay;
}
}
else if (ax > tx2) {
if (ay < ty1) {
// upper right corner
int diffx = ax - tx2;
int diffy = ty1 - ay;
if (diffx < diffy) {
s[0] = TOP; s[1] = RIGHT; s[2] = BOTTOM; s[3] = LEFT;
closeX = tx2;
}
else {
s[0] = RIGHT; s[1] = TOP; s[2] = LEFT; s[3] = BOTTOM;
closeY = ty1;
}
}
else if (ay > ty2) {
// lower right corner
int diffx = ax - tx2;
int diffy = ay - ty2;
if (diffx < diffy) {
s[0] = BOTTOM; s[1] = RIGHT; s[2] = TOP; s[3] = LEFT;
closeX = tx2;
}
else {
s[0] = RIGHT; s[1] = BOTTOM; s[2] = LEFT; s[3] = TOP;
closeY = ty2;
}
}
else {
// right side
s[0] = RIGHT; s[1] = TOP; s[2] = BOTTOM; s[3] = LEFT;
closeY = ay;
}
}
else if (ay < ty1) {
// top
s[0] = TOP; s[1] = RIGHT; s[2] = LEFT; s[3] = BOTTOM;
closeX = ax;
}
else {
// bottom
s[0] = BOTTOM; s[1] = LEFT; s[2] = RIGHT; s[3] = TOP;
closeX = ax;
}
int d;
for(int i = 0; i < 4; i++) {
switch(s[i]) {
case TOP:
ASSERT(tx1 <= closeX && closeX <= tx2);
positions.push_back(Vec2d(closeX, posY1));
for(d=distBetween; closeX-d>=tx1 || closeX+d<=tx2; d+=distBetween) {
if (closeX-d >= tx1) {
positions.push_back(Vec2d(closeX-d, posY1));
}
if (closeX+d <= tx2) {
positions.push_back(Vec2d(closeX+d, posY1));
}
}
closeY = ty1; // for next side
break;
case BOTTOM:
ASSERT(tx1 <= closeX && closeX <= tx2);
positions.push_back(Vec2d(closeX, posY2));
for(d=distBetween; closeX-d>=tx1 || closeX+d<=tx2; d+=distBetween) {
if (closeX-d >= tx1) {
positions.push_back(Vec2d(closeX-d, posY2));
}
if (closeX+d <= tx2) {
positions.push_back(Vec2d(closeX+d, posY2));
}
}
closeY = ty2;
break;
case LEFT:
ASSERT(ty1 <= closeY && closeY <= ty2);
positions.push_back(Vec2d(posX1, closeY));
for(d=distBetween; closeY-d>=ty1 || closeY+d<=ty2; d+=distBetween) {
if (closeY-d >= ty1) {
positions.push_back(Vec2d(posX1, closeY-d));
}
if (closeY+d <= ty2) {
positions.push_back(Vec2d(posX1, closeY+d));
}
}
closeX = tx1;
break;
case RIGHT:
ASSERT(ty1 <= closeY && closeY <= ty2);
positions.push_back(Vec2d(posX2, closeY));
for(d=distBetween; closeY-d>=ty1 || closeY+d<=ty2; d+=distBetween) {
if (closeY-d >= ty1) {
positions.push_back(Vec2d(posX2, closeY-d));
}
if (closeY+d <= ty2) {
positions.push_back(Vec2d(posX2, closeY+d));
}
}
closeX = tx2;
break;
default:
ASSERT(false);
}
}
cout << "end positions on rectangle\n";
}
/*****************************************************************
* AttackManager::AttackManager *
*****************************************************************/
AttackManager::AttackManager(const set<SoarGameObject*>& _targets) : targetSet(_targets)
{
reprioritizeCounter = 0;
numNewAttackers = 0;
for(set<SoarGameObject*>::iterator
i = targetSet.begin();
i != targetSet.end();
++i)
{
targets.insert(pair<SoarGameObject*, AttackTargetInfo>(*i, AttackTargetInfo(*i)));
idSet.insert((*i)->getID());
if((*i)->getGob()->bp_name() == "controlCenter") bases.push_back(*i);
}
reprioritize();
}
/*****************************************************************
* AttackManager::~AttackManager *
*****************************************************************/
AttackManager::~AttackManager() {
cout << "AttackManagerKilled" << endl;
int status;
if (targets.size() == 0) {
status = 1;
}
else {
status = 0;
}
for(list<AttackFSM*>::iterator
i = team.begin();
i != team.end();
++i)
{
#ifdef USE_CANVAS_ATTACK_MANAGER
//Sorts::canvas.unregisterGob((*i)->getGob());
Sorts::canvas.resetSGO((*i)->getSGO());
#endif
(*i)->disown(status);
}
}
/***
* AttackManager::registerFSM
* --------------------------
* Add a unit to the AttackManager
*/
void AttackManager::registerFSM(AttackFSM* fsm) {
ASSERT(numNewAttackers > 0);
numNewAttackers--;
team.push_back(fsm);
}
/***
* Method: unregisterFSM
* ---------------------
* Removes a unit from the AttackManager.
*/
void AttackManager::unregisterFSM(AttackFSM* fsm) {
ASSERT(find(team.begin(), team.end(), fsm) != team.end());
team.erase(find(team.begin(), team.end(), fsm));
if (fsm->getTarget() != NULL) {
unassignTarget(fsm);
}
#ifdef USE_CANVAS_ATTACK_MANAGER
// in addition to attack reassignments, this is called as a result
// of units being killed, in which case the gob is
// already removed from the canvas
if (Sorts::canvas.sgoRegistered(fsm->getSGO())) {
Sorts::canvas.resetSGO(fsm->getSGO());
}
#endif
if (team.size() + numNewAttackers == 0) {
msg << "team size is now 0, going away.." << endl;
Sorts::amr->removeManager(this);
delete this;
}
}
/***
* Method: assignTarget
* --------------------
* Given an attacking unit and a target unit, this method
* checks that the target being assigned does exist, adds the
* attacking unit to the set of units attacking the target object,
* and sets the attacking unit's target to be the target unit.
*/
void AttackManager::assignTarget(AttackFSM* fsm, SoarGameObject* target) {
ASSERT(targets.find(target) != targets.end());
targets[target].assignAttacker(fsm);
fsm->setTarget(target);
}
/***
* Method: unassignTarget
* ----------------------
* Removes an AttackFSM's (attacking finite state machine) target.
*/
void AttackManager::unassignTarget(AttackFSM* fsm) {
ASSERT(fsm->getTarget() != NULL);
ASSERT(targets.find(fsm->getTarget()) != targets.end());
targets[fsm->getTarget()].unassignAttacker(fsm);
fsm->setTarget(NULL);
}
/***
* Method: unassignAll
* -----------------
* Given a target, this frees all units that had been
* attacking it to do something else.
*/
void AttackManager::unassignAll(SoarGameObject* target) {
ASSERT(targets.find(target) != targets.end());
AttackTargetInfo& info = targets[target];
for(set<AttackFSM*>::const_iterator
i = info.attackers_begin();
i != info.attackers_end();
++i)
{
(*i)->setTarget(NULL);
(*i)->setReassign(true);
}
info.unassignAll();
}
/***
* Method: findTarget
* ------------------
* Given an attack unit, this method attacks nearby enemy
* units, making its target selection based on enemy
* health and distance.
*
* The segments commented out were used by the old sorts
* agent. Satured and unsaturated targetting should be
* reintroduced. If attacking formation is reintroduced,
* I think it will probably be in the MoveAttackFSM.
*/
bool AttackManager::findTarget(AttackFSM* fsm) {
msg << "FINDING A TARGET" << endl;
GameObj* gob = fsm->getGob();
/* vector<SoarGameObject*> saturated;
vector<SoarGameObject*> unsaturated;
for(vector<SoarGameObject*>::iterator
i = sortedTargets.begin();
i != sortedTargets.end();
++i)
{
if (targets[*i].isSaturated()) {
saturated.push_back(*i);
}
else {
unsaturated.push_back(*i);
}
}
*/
// try to hit immediately attackable things first
for(vector<SoarGameObject*>::iterator
i = sortedTargets.begin();
i != sortedTargets.end();
++i)
{
if (canHit(gob, (*i)->getGob())) {
assignTarget(fsm, *i);
#ifdef USE_CANVAS_ATTACK_MANAGER
// Sorts::canvas.trackDestination(fsm->getSGO(),
// (*i)->getX(), (*i)->getY());
#endif
msg << "NEARBY TARG" << endl;
return true;
}
}
return false;
/*
dbg << "no targets nearby..\n";
// now try to attack the "best" target
for(vector<SoarGameObject*>::iterator
i = sortedTargets.begin();
i != sortedTargets.end();
++i)
{
list<Vec2d> positions;
attackArcPos(fsm->getGob(), (*i)->getGob(), 0, positions);
for(list<Vec2d>::iterator
j = positions.begin();
j != positions.end();
++j)
{
if (fsm->move((int)(*j)(0), (int)(*j)(1), false) == 0) {
msg <<"Moving to Position: "<<(*j)(0)<<", "<<(*j)(1)<<endl;
assignTarget(fsm, *i);
#ifdef USE_CANVAS_ATTACK_MANAGER
// Sorts::canvas.trackDestination(fsm->getSGO(),
// (*i)->getX(), (*i)->getY());
#endif
dbg << "ARC TARG" << endl;
return true;
}
else {
msg << "ARC CHECK MOVE FAIL" << endl;
}
}
}
// finally, just run toward someone, preferrably unsaturated
// for(int checkSaturated = 1; checkSaturated >= 0; checkSaturated--) {
for(vector<SoarGameObject*>::iterator
i = sortedTargets.begin();
i != sortedTargets.end();
++i)
{
// if (checkSaturated == 0 || !targets[*i].isSaturated()) {
GameObj* tgob = (*i)->getGob();
Vec2d closePos = getClosePos(gob, tgob);
// force a pathfind, now, since the target must have had lots of
// failure points nearby, but should be reachable
msg << "Forcing a pathfind" << endl;
if (fsm->move((int)closePos(0), (int)closePos(1), true) == 0) {
assignTarget(fsm, *i);
#ifdef USE_CANVAS_ATTACK_MANAGER
// Sorts::canvas.trackDestination(fsm->getSGO(),
// (*i)->getX(), (*i)->getY());
#endif
msg << "LAST RESORT TARG" << endl;
return true;
}
// }
}
// }
// }
return false;*/
}
/***
* Method: direct
* --------------
* This method is called by each individual AttackFSM every turn,
* and it determines how these FSM's should behave. From this
* method, units are ordered to move, fire, or remain still. The
* return values inform the AttackFSM class about the state of the
* unit, and decisions on how to move are also based on these
* return values. Return values are:
* > 0 - Success
* = 0 - Still running
* < 0 - Failure
*/
int AttackManager::direct(AttackFSM* fsm) {
//Once per frame we should update our target list
if (reprioritizeCounter != Sorts::frame) {
dbg << "forced reprioritize!\n";
reprioritize();
reprioritizeCounter = Sorts::frame;
}
msg << "NUMTARGS: " << targets.size() << endl;
GameObj* gob = fsm->getGob();
SoarGameObject* sgob = Sorts::OrtsIO->getSoarGameObject(gob);
fsm->touch(); // tell the fsm its been updated, so it can mark time
if (updateTargetList() > 0) {
msg << "UPDATE TARGET LIST" << endl;
if (targets.size() == 0) {
Sorts::amr->removeManager(this);
delete this;
return 1;
}
reprioritize();
}
if (fsm->getTarget() == NULL) findTarget(fsm);
GameObj* goal = (*sortedTargets.begin())->getGob();
if (fsm->getTarget() == NULL){
fsm->move(*goal->sod.x, *goal->sod.y, false);
return 0;
}
GameObj* tgob = fsm->getTarget()->getGob();
AttackTargetInfo& info = targets[fsm->getTarget()];
if (!canHit(gob, tgob) || fsm->badAttack) {
fsm->move(*goal->sod.x, *goal->sod.y, false);
}
else if (!fsm->isFiring() ||
sgob->getLastAttacked() != fsm->getTarget()->getID())
{
fsm->attack(fsm->getTarget());
}
return 0;
}
/***
* Method: updateTargetList
* ------------------------
* Places the targets in the best order to attack them in.
*/
int AttackManager::updateTargetList() {
int numVanished = 0;
map<SoarGameObject*, AttackTargetInfo>::iterator i = targets.begin();
while (i != targets.end()) {
if (!Sorts::OrtsIO->isAlive(i->first->getID())) {
msg << "YYY Unit " << i->first->getID() << " is no longer alive or moved out of view" << endl;
unassignAll(i->first);
targetSet.erase(i->first);
map<SoarGameObject*, AttackTargetInfo>::iterator j = i++;
targets.erase(j);
++numVanished;
}
else {
++i;
}
}
return numVanished;
}
struct NewTargetCompare {
Vec2d myPos;
bool operator()(SoarGameObject* t1, SoarGameObject* t2) {
// first always prefer those that are armed and shooting over
// those that are not
ScriptObj* weapon1 = t1->getGob()->component("weapon");
ScriptObj* weapon2 = t2->getGob()->component("weapon");
if (weapon1 == NULL && weapon2 != NULL) {
return true;
}
if (weapon1 != NULL && weapon2 == NULL) {
return false;
}
Vec2d p1(*t1->getGob()->sod.x, *t1->getGob()->sod.y);
Vec2d p2(*t2->getGob()->sod.x, *t2->getGob()->sod.y);
double dist1 = (myPos - p1).magSq();
double dist2 = (myPos - p2).magSq();
if (weapon1 == NULL && weapon2 == NULL){
if(dist1 < dist2) return true;
return false;
}
int range1 = weapon1->get_int("max_ground_range");
int range2 = weapon2->get_int("max_ground_range");
if (dist1 < dist2 - range2) {
return true;
}
else if (dist2 < dist1 - range1) {
return false;
}
double rating1 = weaponDamageRate(t1->getGob()) * t2->getGob()->get_int("hp");
double rating2 = weaponDamageRate(t2->getGob()) * t1->getGob()->get_int("hp");
if (rating1 < rating2) {
return true;
}
else if (rating1 == rating2) { // break ties by distance
if (dist1 < dist2) {
return true;
}
else if (dist1 == dist2) { // lexicographically break ties
return (t1->getID() < t2->getID());
}
}
return false;
}
};
void AttackManager::reprioritize() {
NewTargetCompare comparator;
comparator.myPos = findCentroid();
dbg << "YYY reprioritizing\n";
sortedTargets.clear();
sortedTargets.insert(sortedTargets.end(), targetSet.begin(), targetSet.end());
sort(sortedTargets.begin(), sortedTargets.end(), comparator);
sort(bases.begin(), bases.end(), comparator);
}
void AttackManager::addNewAttackers(int num) {
// an action has been assigned to a group, but the FSMs have not been created
// make sure the manager is not detroyed until this many FSMs have been
// added-- fix the case where the last attacker is unassigned the same cycle
// new attackers are added
ASSERT(numNewAttackers == 0);
numNewAttackers = num;
}
// need to be called when we try to add attackers that are already part of this
// manager
void AttackManager::decNewAttackers() {
numNewAttackers--;
}
int AttackManager::size(){
return team.size();
}
/***
* Method: gather
* --------------
* Collects all attack units at a point.
*/
void AttackManager::gather(AttackFSM *fsm){
Vec2d gatherAt = Sorts::amr->mainCentroid();
msg << "er..." << endl;
fsm->move((sint4) gatherAt(0), (sint4) gatherAt(1), false);
msg << "GATHERING AT " << gatherAt(0) << ", " << gatherAt(1) << endl;
}
Vec2d AttackManager::findCentroid(){
double xsum = 0, ysum = 0;
for(list<AttackFSM*>::iterator
i = team.begin();
i != team.end();
i++)
{
xsum += *(*i)->getGob()->sod.x;
ysum += *(*i)->getGob()->sod.y;
}
return Vec2d(xsum / team.size(), ysum / team.size());
}
bool AttackManager:: attackLinePos(int range, list<Vec2d>& positions)
{
//First, see if the enemy is in a linear formation
double slope = getSlope();
//If it's not, then return
if(slope == (double) NULL){
dbg<< "SLOPE == NULL" <<endl;
return false;
}
//otherwise, set up a line across from the
//primary target
//First, get the midpoint of the line
Vec2d lineMidpoint = getLineMidpoint(slope, range);
positions.push_back(lineMidpoint);
//and add
for(int i = 1; i < 5; i++)
{
Vec2d temp = Vec2d(slope, 8*i);
positions.push_back(lineMidpoint + temp);
positions.push_back(lineMidpoint - temp);
}
return true;
}
Vec2d AttackManager::getLineMidpoint(double slope, int range){
SoarGameObject* first = sortedTargets[0];
Vec2d enemyPos = Vec2d(first->getX(), first->getY());
//Get the distance vector from the targetted attack unit
Vec2d dist = Vec2d(Vec2d(-slope, 1), range);
Vec2d loc1 = enemyPos + dist;
Vec2d loc2 = enemyPos - dist;
Vec2d centroid = findCentroid();
Vec2d fit1 = loc1 - centroid;
Vec2d fit2 = loc2 - centroid;
if(fit1.mag() < fit2.mag())
return loc1;
return loc2;
}
double AttackManager::getSlope(){
double ySum, xSum, xxSum, xySum, Sy, Sx,
slope, x, y, correlation;
ySum = xSum = xxSum = xySum = Sy = Sx = 0;
int count = targetSet.size();
//calculate the sum of the x's and the sum of the y's,
//which we'll use to find the slope and intercept
for(set<SoarGameObject*>::iterator i = targetSet.begin();
i != targetSet.end(); ++i)
{
x = (*i)->getX();
y = (*i)->getY();
ySum += y;
xSum += x;
xxSum += x*x;
xySum += x*y;
}
//This is the formula for calculating the slope of a best
//fit line for a set of points
slope = (ySum*xxSum - xSum*xySum)/(count*xxSum - xSum*xSum);
for(set<SoarGameObject*>::iterator i = targetSet.begin();
i != targetSet.end(); ++i)
{
x = (*i)->getX();
y = (*i)->getY();
Sy += (y - ySum/count);
Sx += (x - xSum/count);
}
correlation = slope*Sx/Sy;
if(correlation > 0.8)
return slope;
return (double) NULL;
}
void AttackManager::attackArcPos( GameObj* atk,
GameObj* tgt,
int layer,
list<Vec2d>& positions)
{
dbg << "getting arc positions\n";
dbg << "atk: " << atk << " tgt: " << tgt << endl;
int atkRadius = *atk->sod.radius;
Vec2d aPos(*atk->sod.x, *atk->sod.y);
Vec2d tPos(*tgt->sod.x, *tgt->sod.y);
int range;
if (*tgt->sod.zcat == GameObj::ON_LAND) {
range = atk->component("weapon")->get_int("max_ground_range")
+ atkRadius;
}
else {
range = atk->component("weapon")->get_int("max_air_range")
+ atkRadius;
}
range = (int)(range * 0.9); // for safety
range -= layer * atkRadius * 2;
list<Vec2d> atkPos;
/* The attackLinePos method was supposed to force
* our units into a line formation, but as it isn't
* working very well, and doesn't appear to be doing much,
* we're just not going to bother with this for now
*
if (attackLinePos(range, atkPos)){
dbg << "USING THE LINE FORMATION" << endl;
}
else*/
if (*tgt->sod.shape == SHAPE_RECTANGLE) {
int halfwidth = (*tgt->sod.x2 - *tgt->sod.x1) / 2;
int halfheight = (*tgt->sod.y2 - *tgt->sod.y1) / 2;
int minRadius = min(halfwidth, halfheight);
int maxRadius = max(halfwidth, halfheight);
dbg << "USING RADIUS " << minRadius << endl;
if (maxRadius - minRadius < range / 2) {
// treat this as a circle
Vec2d closestPos = tPos - Vec2d(tPos - aPos, range + minRadius);
positionsOnCircle(tPos, closestPos, *atk->sod.radius * 2, atkPos);
}
else {
// treat as a real rectangle
positionsOnRectangle
( *atk->sod.x,
*atk->sod.y,
*tgt->sod.x1,
*tgt->sod.y1,
*tgt->sod.x2,
*tgt->sod.y2,
range,
atkRadius * 2,
atkPos );
}
}
else {
int tgtRadius = *tgt->sod.radius;
Vec2d closestPos = tPos - Vec2d(tPos - aPos, range + tgtRadius);
positionsOnCircle(tPos, closestPos, *atk->sod.radius * 4, atkPos);
}
for(list<Vec2d>::iterator
i = atkPos.begin();
i != atkPos.end();
i++)
{
list<GameObj*> collisions;
Vec2d intPos = i->roundToward(tPos);
if (0 <= intPos(0) && intPos(0) < Sorts::OrtsIO->getMapXDim() &&
0 <= intPos(1) && intPos(1) < Sorts::OrtsIO->getMapYDim())
{
Circle c(intPos(0), intPos(1), atkRadius);
if (Sorts::spatialDB->hasObjectCollision((int)intPos(0),(int)intPos(1),atkRadius)
or
Sorts::spatialDB->hasTerrainCollision(c)) {
continue;
}
bool slotTaken = false;
for(list<AttackFSM*>::iterator
j = team.begin();
j != team.end();
j++)
{
if ((*j)->isMoving()) {
double d = (intPos - (*j)->getDestination()).magSq();
double r = *(*j)->getGob()->sod.radius + atkRadius;
if (d < r * r) {
slotTaken = true;
break;
}
}
}
if (!slotTaken) {
positions.push_back(intPos);
}
}
//positions.push_back(intPos);
}
}
| 27.098765 | 100 | 0.57192 | [
"object",
"shape",
"vector"
] |
a313ac5a8a73305e2f10f3ca936613f4328c8224 | 27,353 | cpp | C++ | src/thunderbots/software/geom/util.cpp | SupoWupo/Software | ae9af36d5ed20de9b8f1d4f232df0eb26e080dd4 | [
"MIT"
] | null | null | null | src/thunderbots/software/geom/util.cpp | SupoWupo/Software | ae9af36d5ed20de9b8f1d4f232df0eb26e080dd4 | [
"MIT"
] | null | null | null | src/thunderbots/software/geom/util.cpp | SupoWupo/Software | ae9af36d5ed20de9b8f1d4f232df0eb26e080dd4 | [
"MIT"
] | null | null | null | #include "geom/util.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <limits>
#include "geom/angle.h"
double proj_len(const Seg &first, const Vector &second)
{
return proj_len(first.toVector(), second - first.start);
}
double proj_len(const Vector &first, const Vector &second)
{
return first.dot(second) / first.len();
}
double dist(const Vector &first, const Vector &second)
{
return (first - second).len();
}
double dist(const Seg &first, const Seg &second)
{
if (intersects(first, second))
{
return 0.0;
}
return std::sqrt(
std::min(std::min(distsq(first, second.start), distsq(first, second.end)),
std::min(distsq(second, first.start), distsq(second, first.end))));
}
double dist(const Line &first, const Vector &second)
{
if (isDegenerate(first))
{
return dist(first.first, second);
}
return fabs((second - first.first).cross(first.second - first.first) /
(first.second - first.first).len());
}
double dist(const Vector &first, const Line &second)
{
return dist(second, first);
}
double dist(const Vector &first, const Seg &second)
{
return std::sqrt(distsq(first, second));
}
double dist(const Seg &first, const Vector &second)
{
return dist(second, first);
}
double distsq(const Vector &first, const Seg &second)
{
double seglensq = lensq(second);
Vector relsecond_s = first - second.start;
Vector relsecond_e = first - second.end;
Vector s_vec2 = second.toVector();
if (s_vec2.dot(relsecond_s) > 0 && second.reverse().toVector().dot(relsecond_e) > 0)
{
if (isDegenerate(second))
{
return relsecond_s.len();
}
double cross = relsecond_s.cross(s_vec2);
return std::fabs(cross * cross / seglensq);
}
double lensq_s = distsq(second.start, first), lensq_e = distsq(second.end, first);
return std::min(lensq_s, lensq_e);
}
double distsq(const Seg &first, const Vector &second)
{
return distsq(second, first);
}
double distsq(const Vector &first, const Vector &second)
{
return (first - second).lensq();
}
bool isDegenerate(const Seg &seg)
{
return distsq(seg.start, seg.end) < EPS2;
}
bool isDegenerate(const Line &line)
{
return distsq(line.first, line.second) < EPS2;
}
bool isDegenerate(const Ray &ray)
{
return distsq(ray.start, ray.dir) < EPS2;
}
double len(const Seg &seg)
{
return dist(seg.start, seg.end);
}
double lensq(const Seg &seg)
{
return distsq(seg.start, seg.end);
}
double lensq(const Line &line)
{
(void)line; // unused
return std::numeric_limits<double>::infinity();
}
bool contains(const Triangle &out, const Vector &in)
{
double angle = 0;
for (int i = 0, j = 2; i < 3; j = i++)
{
if ((in - out[i]).len() < EPS)
{
return true; // SPECIAL CASE
}
double a =
atan2((out[i] - in).cross(out[j] - in), (out[i] - in).dot(out[j] - in));
angle += a;
}
return std::fabs(angle) > 6;
}
bool contains(const Circle &out, const Vector &in)
{
return distsq(out.origin, in) <= out.radius * out.radius;
}
bool contains(const Circle &out, const Seg &in)
{
return dist(in, out.origin) < out.radius;
}
bool contains(const Seg &out, const Vector &in)
{
if (collinear(in, out.start, out.end))
{
// if collinear we only need to check one of the coordinates,
// arbitrarily choose x
return (in.x() <= out.start.x() && in.x() >= out.end.x()) ||
(in.x() <= out.end.x() && in.x() >= out.start.x());
}
return false;
}
bool contains(const Ray &out, const Vector &in)
{
if (collinear(in, out.start, out.dir))
{
return sign(in.x() - out.start.x()) == sign(out.dir.x() - out.start.x()) &&
sign(in.y() - out.start.y()) == sign(out.dir.y() - out.start.y());
}
return false;
}
bool contains(const Rect &out, const Vector &in)
{
return out.containsPoint(in);
}
bool intersects(const Triangle &first, const Circle &second)
{
return contains(first, second.origin) ||
dist(getSide(first, 0), second.origin) < second.radius ||
dist(getSide(first, 1), second.origin) < second.radius ||
dist(getSide(first, 2), second.origin) < second.radius;
}
bool intersects(const Circle &first, const Triangle &second)
{
return intersects(second, first);
}
bool intersects(const Circle &first, const Circle &second)
{
return (first.origin - second.origin).len() < (first.radius + second.radius);
}
bool intersects(const Ray &first, const Seg &second)
{
auto isect = lineIntersection(first.start, first.dir, second.start, second.end);
if (isect.has_value())
{
return contains(first, isect.value()) && contains(second, isect.value());
}
return collinear(first.start, first.dir, second.start);
}
bool intersects(const Seg &first, const Ray &second)
{
return intersects(second, first);
}
bool intersects(const Seg &first, const Circle &second)
{
// if the segment is inside the circle AND at least one of the points is
// outside the circle
return contains(second, first) &&
(distsq(first.start, second.origin) > second.radius * second.radius ||
distsq(first.end, second.origin) > second.radius * second.radius);
}
bool intersects(const Circle &first, const Seg &second)
{
return intersects(second, first);
}
bool intersects(const Seg &first, const Seg &second)
{
if (sign((first.start - first.end).cross(second.start - second.end)) == 0)
{
// find distance of two endpoints on segments furthest away from each
// other
double mx_len = std::sqrt(std::max(std::max((second.start - first.end).lensq(),
(second.end - first.end).lensq()),
std::max((second.start - first.start).lensq(),
(second.end - first.start).lensq())));
// if the segments cross then this distance should be less than
// the sum of the distances of the line segments
return mx_len <
(first.start - first.end).len() + (second.start - second.end).len() + EPS;
}
return sign((first.end - first.start).cross(second.start - first.start)) *
sign((first.end - first.start).cross(second.end - first.start)) <=
0 &&
sign((second.end - second.start).cross(first.start - second.start)) *
sign((second.end - second.start).cross(first.end - second.start)) <=
0;
}
template <size_t N>
Vector getVertex(const Poly<N> &poly, unsigned int i)
{
if (i > N)
throw std::out_of_range("poly does not have that many sides!!!");
else
return poly[i];
}
template <size_t N>
void setVertex(Poly<N> &poly, unsigned int i, const Vector &v)
{
if (i > N)
throw std::out_of_range("poly does not have that many sides!!!");
else
poly[i] = v;
}
template <size_t N>
Seg getSide(const Poly<N> &poly, unsigned int i)
{
return Seg(getVertex(poly, i), getVertex(poly, (i + 1) % N));
}
std::vector<std::pair<Vector, Angle>> angleSweepCirclesAll(
const Vector &src, const Vector &p1, const Vector &p2,
const std::vector<Point> &obstacles, const double &radius)
{
std::vector<std::pair<Vector, Angle>> ret;
const Angle offangle = (p1 - src).orientation();
if (collinear(src, p1, p2))
{
// return a result that contains the direction of the line and zero angle if not
// blocked by obstacles
Seg collinear_seg = Seg(src, p1);
for (Point p : obstacles)
{
if (intersects(collinear_seg, Circle(p, radius)))
{
// intersection with obstacle found, we're done here and we return nothing
return ret;
}
}
ret.push_back(std::make_pair(collinear_seg.toVector(), Angle::zero()));
return ret;
}
std::vector<std::pair<Angle, int>> events;
events.reserve(2 * obstacles.size() + 2);
events.push_back(std::make_pair(Angle::zero(), 1)); // p1 becomes angle 0
events.push_back(
std::make_pair(((p2 - src).orientation() - offangle).angleMod(), -1));
for (Vector i : obstacles)
{
Vector diff = i - src;
if (diff.len() < radius)
{
return ret;
}
const Angle cent = (diff.orientation() - offangle).angleMod();
const Angle span = Angle::asin(radius / diff.len());
const Angle range1 = cent - span;
const Angle range2 = cent + span;
if (range1 < -Angle::half() || range2 > Angle::half())
{
continue;
}
events.push_back(std::make_pair(range1, -1));
events.push_back(std::make_pair(range2, 1));
}
// do angle sweep for largest angle
std::sort(events.begin(), events.end());
Angle sum = Angle::zero();
Angle start = events[0].first;
int cnt = 0;
for (std::size_t i = 0; i + 1 < events.size(); ++i)
{
cnt += events[i].second;
assert(cnt <= 1);
if (cnt > 0)
{
sum += events[i + 1].first - events[i].first;
}
else
{
const Angle mid = start + sum / 2 + offangle;
const Vector ray = Vector::createFromAngle(mid) * 10.0;
const Vector inter = lineIntersection(src, src + ray, p1, p2).value();
ret.push_back(std::make_pair(inter, sum));
sum = Angle::zero();
start = events[i + 1].first;
}
}
return ret;
}
std::pair<Vector, Angle> angleSweepCircles(const Vector &src, const Vector &p1,
const Vector &p2,
const std::vector<Vector> &obstacles,
const double &radius)
{
// default value to return if nothing is valid
Vector bestshot = (p1 + p2) * 0.5;
const Angle offangle = (p1 - src).orientation();
if (collinear(src, p1, p2))
{
return std::make_pair(bestshot, Angle::zero());
}
std::vector<std::pair<Angle, int>> events;
events.reserve(2 * obstacles.size() + 2);
events.push_back(std::make_pair(Angle::zero(), 1)); // p1 becomes angle 0
events.push_back(
std::make_pair(((p2 - src).orientation() - offangle).angleMod(), -1));
for (Vector i : obstacles)
{
Vector diff = i - src;
if (diff.len() < radius)
{
return std::make_pair(bestshot, Angle::zero());
}
const Angle cent = (diff.orientation() - offangle).angleMod();
const Angle span = Angle::asin(radius / diff.len());
const Angle range1 = cent - span;
const Angle range2 = cent + span;
if (range1 < -Angle::half() || range2 > Angle::half())
{
continue;
}
events.push_back(std::make_pair(range1, -1));
events.push_back(std::make_pair(range2, 1));
}
// do angle sweep for largest angle
std::sort(events.begin(), events.end());
Angle best = Angle::zero();
Angle sum = Angle::zero();
Angle start = events[0].first;
int cnt = 0;
for (std::size_t i = 0; i + 1 < events.size(); ++i)
{
cnt += events[i].second;
assert(cnt <= 1);
if (cnt > 0)
{
sum += events[i + 1].first - events[i].first;
if (best < sum)
{
best = sum;
// shoot ray from point p
// intersect with line p1-p2
const Angle mid = start + sum / 2 + offangle;
const Vector ray = Vector::createFromAngle(mid) * 10.0;
const Vector inter = lineIntersection(src, src + ray, p1, p2).value();
bestshot = inter;
}
}
else
{
sum = Angle::zero();
start = events[i + 1].first;
}
}
return std::make_pair(bestshot, best);
}
std::vector<Vector> circleBoundaries(const Vector ¢re, double radius, int num_points)
{
Angle rotate_amount = Angle::full() / num_points;
std::vector<Vector> ans;
Vector bound(radius, 0.0);
for (int i = 0; i < num_points; i++)
{
Vector temp = centre + bound;
ans.push_back(temp);
bound = bound.rotate(rotate_amount);
}
return ans;
}
bool collinear(const Vector &a, const Vector &b, const Vector &c)
{
if ((a - b).lensq() < EPS2 || (b - c).lensq() < EPS2 || (a - c).lensq() < EPS2)
{
return true;
}
return std::fabs((b - a).cross(c - a)) < EPS;
}
Vector clipPoint(const Vector &p, const Vector &bound1, const Vector &bound2)
{
const double minx = std::min(bound1.x(), bound2.x());
const double miny = std::min(bound1.y(), bound2.y());
const double maxx = std::max(bound1.x(), bound2.x());
const double maxy = std::max(bound1.y(), bound2.y());
Vector ret = p;
if (p.x() < minx)
{
ret.set(minx, ret.y());
}
else if (p.x() > maxx)
{
ret.set(maxx, ret.y());
}
if (p.y() < miny)
{
ret.set(ret.x(), miny);
}
else if (p.y() > maxy)
{
ret.set(ret.x(), maxy);
}
return ret;
}
Vector clipPoint(const Vector &p, const Rect &r)
{
const double minx = r.swCorner().x();
const double miny = r.swCorner().y();
const double maxx = r.neCorner().x();
const double maxy = r.neCorner().y();
Vector ret = p;
if (p.x() < minx)
{
ret.set(minx, ret.y());
}
else if (p.x() > maxx)
{
ret.set(maxx, ret.y());
}
if (p.y() < miny)
{
ret.set(ret.x(), miny);
}
else if (p.y() > maxy)
{
ret.set(ret.x(), maxy);
}
return ret;
}
std::vector<Vector> lineCircleIntersect(const Vector ¢re, double radius,
const Vector &segA, const Vector &segB)
{
std::vector<Vector> ans;
// take care of 0 length segments too much error here
if ((segB - segA).lensq() < EPS)
{
return ans;
}
double lenseg = (segB - segA).dot(centre - segA) / (segB - segA).len();
Vector C = segA + lenseg * (segB - segA).norm();
// if C outside circle no intersections
if ((C - centre).lensq() > radius * radius + EPS)
{
return ans;
}
// if C on circle perimeter return the only intersection
if ((C - centre).lensq() < radius * radius + EPS &&
(C - centre).lensq() > radius * radius - EPS)
{
ans.push_back(C);
return ans;
}
// first possible intersection
double lensegb = radius * radius - (C - centre).lensq();
ans.push_back(C - lensegb * (segB - segA).norm());
ans.push_back(C + lensegb * (segB - segA).norm());
return ans;
}
std::vector<Vector> lineRectIntersect(const Rect &r, const Vector &segA,
const Vector &segB)
{
std::vector<Vector> ans;
for (unsigned int i = 0; i < 4; i++)
{
const Vector &a = r[i];
// to draw a line segment from point 3 to point 0
const Vector &b = r[(i + 1) % 4];
if (intersects(Seg(a, b), Seg(segA, segB)) &&
uniqueLineIntersects(a, b, segA, segB))
{
ans.push_back(lineIntersection(a, b, segA, segB).value());
}
}
return ans;
}
Vector vectorRectIntersect(const Rect &r, const Vector &vecA, const Vector &vecB)
{
std::vector<Vector> points = lineRectIntersect(r, vecA, (vecB - vecA) * 100 + vecA);
for (Vector i : points)
{
if (contains(Ray(vecA, vecB), i))
{
return i;
}
}
return Vector(1.0 / 0.0, 1.0 / 0.0); // no solution found, propagate infinity
}
Vector closestPointOnSeg(const Vector ¢re, const Vector &segA, const Vector &segB)
{
// if one of the end-points is extremely close to the centre point
// then return 0.0
if ((segB - centre).lensq() < EPS2)
{
return segB;
}
if ((segA - centre).lensq() < EPS2)
{
return segA;
}
// take care of 0 length segments
if ((segB - segA).lensq() < EPS2)
{
return segA;
}
// find point C
// which is the projection onto the line
double lenseg = (segB - segA).dot(centre - segA) / (segB - segA).len();
Vector C = segA + lenseg * (segB - segA).norm();
// check if C is in the line seg range
double AC = (segA - C).lensq();
double BC = (segB - C).lensq();
double AB = (segA - segB).lensq();
bool in_range = AC <= AB && BC <= AB;
// if so return C
if (in_range)
{
return C;
}
double lenA = (centre - segA).len();
double lenB = (centre - segB).len();
// otherwise return closest end of line-seg
if (lenA < lenB)
{
return segA;
}
return segB;
}
namespace
{
std::vector<Vector> lineseg_circle_intersect(const Vector ¢re, double radius,
const Vector &segA, const Vector &segB)
{
std::vector<Vector> ans;
std::vector<Vector> poss = lineCircleIntersect(centre, radius, segA, segB);
for (Vector i : poss)
{
bool x_ok = i.x() <= std::max(segA.x(), segB.x()) + EPS &&
i.x() >= std::min(segA.x(), segB.x()) - EPS;
bool y_ok = i.y() <= std::max(segA.y(), segB.y()) + EPS &&
i.y() >= std::min(segA.y(), segB.y()) - EPS;
if (x_ok && y_ok)
{
ans.push_back(i);
}
}
return ans;
}
} // namespace
bool uniqueLineIntersects(const Vector &a, const Vector &b, const Vector &c,
const Vector &d)
{
return std::abs((d - c).cross(b - a)) > EPS;
}
std::vector<Point> lineIntersection(const Seg &a, const Seg &b)
{
if (std::fabs((b.end - b.start).cross(a.end - a.start)) < EPS)
{
// parallel line segments, find if they're collinear and return the 2 points
// on the line they both lay on if they are collinear and intersecting
// shamelessly copypasted from
// https://stackoverflow.com/questions/22456517/algorithm-for-finding-the-segment-overlapping-two-collinear-segments
if (collinear(a.start, b.start, b.end) && collinear(a.end, b.start, b.end))
{
double slope = (a.end.y() - a.start.y()) / (a.end.x() - a.start.x());
bool isHorizontal = slope < EPS;
bool isDescending = slope < 0 && !isHorizontal;
double invertY = isDescending || isHorizontal ? -1 : 1;
Point min1 = Point(std::min(a.start.x(), a.end.x()),
std::min(a.start.y() * invertY, a.end.y() * invertY));
Point max1 = Point(std::max(a.start.x(), a.end.x()),
std::max(a.start.y() * invertY, a.end.y() * invertY));
Point min2 = Point(std::min(b.start.x(), b.end.x()),
std::min(b.start.y() * invertY, b.end.y() * invertY));
Point max2 = Point(std::max(b.start.x(), b.end.x()),
std::max(b.start.y() * invertY, b.end.y() * invertY));
Point minIntersection;
if (isDescending)
minIntersection = Point(std::max(min1.x(), min2.x()),
std::min(min1.y() * invertY, min2.y() * invertY));
else
minIntersection = Point(std::max(min1.x(), min2.x()),
std::max(min1.y() * invertY, min2.y() * invertY));
Point maxIntersection;
if (isDescending)
maxIntersection = Point(std::min(max1.x(), max2.x()),
std::max(max1.y() * invertY, max2.y() * invertY));
else
maxIntersection = Point(std::min(max1.x(), max2.x()),
std::min(max1.y() * invertY, max2.y() * invertY));
bool intersect =
minIntersection.x() <= maxIntersection.x() &&
((!isDescending && minIntersection.y() <= maxIntersection.y()) ||
(isDescending && minIntersection.y() >= maxIntersection.y()));
if (intersect)
{
return std::vector<Point>{minIntersection, maxIntersection};
}
else
return std::vector<Point>();
}
else
return std::vector<Point>();
}
return std::vector<Point>{a.start + (a.start - b.start).cross(b.end - b.start) /
(b.end - b.start).cross(a.end - a.start) *
(a.end - a.start)};
}
// shamelessly copy-pasted from RoboJackets
std::optional<Point> lineIntersection(const Vector &a, const Vector &b, const Vector &c,
const Vector &d)
{
Seg line1(a, b), line2(c, d);
double x1 = line1.start.x();
double y1 = line1.start.y();
double x2 = line1.end.x();
double y2 = line1.end.y();
double x3 = line2.start.x();
double y3 = line2.start.y();
double x4 = line2.end.x();
double y4 = line2.end.y();
double denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (denom == 0)
{
// log the parallel lines when we actually implement logging?
return std::nullopt;
}
double deta = x1 * y2 - y1 * x2;
double detb = x3 * y4 - y3 * x4;
Point intersection;
intersection.set((deta * (x3 - x4) - (x1 - x2) * detb) / denom,
(deta * (y3 - y4) - (y1 - y2) * detb) / denom);
return std::make_optional(intersection);
}
Vector reflect(const Vector &v, const Vector &n)
{
if (n.len() < EPS)
{
return v;
}
Vector normal = n.norm();
return v - 2 * v.dot(normal) * normal;
}
Vector reflect(const Vector &a, const Vector &b, const Vector &p)
{
// Make a as origin.
// Rotate by 90 degrees, does not matter which direction?
Vector n = (b - a).rotate(Angle::quarter());
return a + reflect(p - a, n);
}
Vector calcBlockCone(const Vector &a, const Vector &b, const double &radius)
{
if (a.len() < EPS || b.len() < EPS)
{
}
// unit vector and bisector
Vector au = a / a.len();
Vector c = au + b / b.len();
// use similar triangle
return c * (radius / std::fabs(au.cross(c)));
}
Vector calcBlockCone(const Vector &a, const Vector &b, const Vector &p,
const double &radius)
{
return p + calcBlockCone(a - p, b - p, radius);
}
Vector calcBlockOtherRay(const Vector &a, const Vector &c, const Vector &g)
{
return reflect(c - a, g - c); // this, and the next two instances, were
// changed from a - c since reflect() was
// fixed
}
Vector calcBlockConeDefender(const Vector &a, const Vector &b, const Vector &c,
const Vector &g, const double &r)
{
Vector R = reflect(c - a, g - c);
return calcBlockCone(R + c, b, c, r);
}
double offsetToLine(Vector x0, Vector x1, Vector p)
{
Vector n;
// get normal to line
n = (x1 - x0).perp().norm();
return n.dot(p - x0);
}
double offsetAlongLine(Vector x0, Vector x1, Vector p)
{
Vector n, v;
// get normal to line
n = x1 - x0;
n = n.norm();
v = p - x0;
return n.dot(v);
}
Vector segmentNearLine(Vector a0, Vector a1, Vector b0, Vector b1)
{
Vector v, n, p;
double dn, t;
v = a1 - a0;
n = (b1 - b0).norm();
n = n.perp();
dn = v.dot(n);
if (std::fabs(dn) < EPS)
{
return a0;
}
t = -(a0 - b0).dot(n) / dn;
if (t < 0)
{
t = 0;
}
if (t > 1)
{
t = 1;
}
p = a0 + v * t;
return p;
}
Vector intersection(Vector a1, Vector a2, Vector b1, Vector b2)
{
Vector a = a2 - a1;
Vector b1r = (b1 - a1).rotate(-a.orientation());
Vector b2r = (b2 - a1).rotate(-a.orientation());
Vector br = (b1r - b2r);
return Vector(b2r.x() - b2r.y() * (br.x() / br.y()), 0.0).rotate(a.orientation()) +
a1;
}
Angle vertexAngle(Vector a, Vector b, Vector c)
{
return ((a - b).orientation() - (c - b).orientation()).angleMod();
}
double closestPointTime(Point x1, Vector v1, Point x2, Vector v2)
{
Vector v = v1 - v2;
double sl = v.lensq();
double t;
if (sl < EPS)
{
return 0.0; // parallel tracks, any time is ok.
}
t = -v.dot(x1 - x2) / sl;
if (t < 0.0)
{
return 0.0; // nearest time was in the past, now is closest point from
// now on.
}
return t;
}
bool pointInFrontVector(Vector offset, Vector dir, Vector p)
{
// compare angle different
Angle a1 = dir.orientation();
Angle a2 = (p - offset).orientation();
Angle diff = (a1 - a2).angleMod();
return diff < Angle::quarter() && diff > -Angle::quarter();
}
std::pair<Point, Point> getCircleTangentPoints(const Point &start, const Circle &circle,
double buffer)
{
// If the point is already inside the circe arccos won't work so just return
// the perp points
if (contains(circle, start))
{
double perpDist =
std::sqrt(circle.radius * circle.radius - (circle.origin - start).lensq());
Point p1 = start + (circle.origin - start).perp().norm(perpDist + buffer);
Point p2 = start - (circle.origin - start).perp().norm(perpDist + buffer);
return std::make_pair(p1, p2);
}
else
{
double radiusAngle = std::acos(circle.radius / (start - circle.origin).len());
Point p1 = circle.origin + (start - circle.origin)
.rotate(Angle::ofRadians(radiusAngle))
.norm(circle.radius + buffer);
Point p2 = circle.origin + (start - circle.origin)
.rotate(-Angle::ofRadians(radiusAngle))
.norm(circle.radius + buffer);
return std::make_pair(p1, p2);
}
}
bool pointIsRightOfLine(const Seg &line, const Point &point)
{
return (line.end.x() - line.start.x()) * (point.y() - line.start.y()) -
(line.end.y() - line.start.y()) * (point.x() - line.start.x()) <
0.0;
}
Point getPointsMean(const std::vector<Point> &points)
{
Point average = Point(0, 0);
for (unsigned int i = 0; i < points.size(); i++)
{
average += points[i];
}
average /= static_cast<double>(points.size());
return average;
}
double getPointsVariance(const std::vector<Point> &points)
{
Point mean = getPointsMean(points);
double sum = 0.0;
for (unsigned int i = 0; i < points.size(); i++)
{
sum += (points[i] - mean).lensq();
}
sum /= static_cast<double>(points.size());
return sqrt(sum);
}
| 29.129925 | 124 | 0.542098 | [
"vector"
] |
a314b8fd1e9ce88b5311108602038079588e694f | 878 | hh | C++ | WhistleListener/whistlelistener.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | WhistleListener/whistlelistener.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | WhistleListener/whistlelistener.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <alsa/asoundlib.h>
#include <fftw3.h>
#include <string>
#include "../stats/movingaverage.hh"
#include "../util/windowfunctions.hh"
namespace bold
{
class WhistleListener
{
public:
WhistleListener();
WhistleListener(std::string deviceName, uint sampleRate, uint sampleCount, ushort slowSmoothingLength, ushort fastSmoothingLength);
~WhistleListener();
bool initialise();
bool step();
void setWindowFunction(WindowFunctionType type);
private:
const std::string d_deviceName;
uint d_sampleRate;
uint d_sampleCount;
std::vector<MovingAverage<float>> d_slowSmoothers;
std::vector<MovingAverage<float>> d_fastSmoothers;
std::vector<float> d_window;
WindowFunctionType d_windowType;
snd_pcm_t* d_pcm;
float* d_samples;
fftwf_complex* d_frequencies;
fftwf_plan d_fftwPlan;
};
} | 21.95 | 135 | 0.723235 | [
"vector"
] |
a31e8cc4d3abf2d33a3edcf3d803d6e59a31ff24 | 2,171 | cc | C++ | tests/tp/sampler.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | null | null | null | tests/tp/sampler.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | null | null | null | tests/tp/sampler.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | 1 | 2020-01-22T18:04:53.000Z | 2020-01-22T18:04:53.000Z | #include <nexus/test.hh>
#include <clean-core/vector.hh>
#include <texture-processor/image_view.hh>
#include <texture-processor/sampler.hh>
#include <typed-geometry/tg.hh>
TEST("sampler basics")
{
auto data = cc::vector<int>{1, 2, 3, //
4, 5, 6};
auto img = tp::image2_view<int>::from_data(cc::as_byte_span(data).data(), {3, 2}, {sizeof(int), 3 * sizeof(int)});
CHECK(img(0, 0) == 1);
CHECK(img(1, 0) == 2);
CHECK(img(2, 0) == 3);
CHECK(img(0, 1) == 4);
CHECK(img(1, 1) == 5);
CHECK(img(2, 1) == 6);
// sampler converts to float after lookup
auto sampler = tp::linear_clamped_px_sampler<float>(img);
CHECK(sampler({0, 0}) == 1);
CHECK(sampler({1, 0}) == 2);
CHECK(sampler({2, 0}) == 3);
CHECK(sampler({0, 1}) == 4);
CHECK(sampler({1, 1}) == 5);
CHECK(sampler({2, 1}) == 6);
CHECK(sampler({-10, 0}) == 1);
CHECK(sampler({10, 0}) == 3);
CHECK(sampler({-10, -10}) == 1);
CHECK(sampler({10, -10}) == 3);
CHECK(sampler({-10, 10}) == 4);
CHECK(sampler({10, 10}) == 6);
CHECK(sampler({0.25f, 0}) == 1.25f);
CHECK(sampler({0.5f, 0}) == 1.5f);
CHECK(sampler({0.5f, 1}) == 4.5f);
CHECK(sampler({0.5f, 0.5f}) == 3);
}
TEST("sampler tg")
{
auto data = cc::vector<tg::vec2>{{10, 5},
{20, 3}, //
{30, 8},
{10, 2}};
auto img = tp::image2_view<tg::vec2>::from_data(cc::as_byte_span(data).data(), {2, 2}, {sizeof(tg::vec2), 2 * sizeof(tg::vec2)});
CHECK(img(0, 0) == tg::vec2(10, 5));
CHECK(img(1, 0) == tg::vec2(20, 3));
CHECK(img(0, 1) == tg::vec2(30, 8));
CHECK(img(1, 1) == tg::vec2(10, 2));
auto sampler = tp::linear_clamped_px_sampler(img);
CHECK(sampler({0, 0}) == tg::vec2(10, 5));
CHECK(sampler({1, 0}) == tg::vec2(20, 3));
CHECK(sampler({0, 1}) == tg::vec2(30, 8));
CHECK(sampler({1, 1}) == tg::vec2(10, 2));
CHECK(sampler({0.5f, 0}) == tg::vec2(15, 4));
CHECK(sampler({0.5f, 1}) == tg::vec2(20, 5));
CHECK(sampler({0.5f, 0.5f}) == tg::vec2(17.5f, 4.5f));
}
| 29.739726 | 133 | 0.499309 | [
"geometry",
"vector"
] |
a321ed7522d03c3d2402466bee8f67f83c7b6f7e | 86,093 | cpp | C++ | DiskInfoDlg.cpp | sangkmt/CrystalDiskInfo | 453a5f343c594fb843bcc7d39df0574cbe9df212 | [
"MIT"
] | null | null | null | DiskInfoDlg.cpp | sangkmt/CrystalDiskInfo | 453a5f343c594fb843bcc7d39df0574cbe9df212 | [
"MIT"
] | null | null | null | DiskInfoDlg.cpp | sangkmt/CrystalDiskInfo | 453a5f343c594fb843bcc7d39df0574cbe9df212 | [
"MIT"
] | null | null | null | /*---------------------------------------------------------------------------*/
// Author : hiyohiyo
// Mail : hiyohiyo@crystalmark.info
// Web : https://crystalmark.info/
// License : The MIT License
/*---------------------------------------------------------------------------*/
#include "stdafx.h"
#include "DiskInfo.h"
#include "DiskInfoDlg.h"
#include "AtaSmart.h"
#include "UtilityFx.h"
#include "OsInfoFx.h"
#include <mmsystem.h>
#pragma comment(lib, "winmm.lib")
#include "locale.h"
#include <complex>
#include "digitalv.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Global
// Task Tray
UINT gRegMessageId = ::RegisterWindowMessage(_T("CrystalDiskInfo"));
UINT gRegIconId = ::RegisterWindowMessage(_T("CrystalDiskInfoIcon"));
UINT gTempIcon[CAtaSmart::MAX_DISK];
extern const GUID StrageGUID = { 0x53F56307, 0xB6BF, 0x11D0,
0x94,0xF2,0x00,0xA0,0xC9,0x1E,0xFB,0x8B };
CDiskInfoDlg::CDiskInfoDlg(CWnd* pParent /*=NULL*/, BOOL flagStartupExit)
: CMainDialogFx(CDiskInfoDlg::IDD, pParent)
{
DebugPrint(L"CDiskInfoDlg::CDiskInfoDlg - START");
m_Ini = ((CDiskInfoApp*)AfxGetApp())->m_Ini;
m_OffsetX = 0;
#ifdef SUISHO_SHIZUKU_SUPPORT
#ifdef KUREI_KEI_SUPPORT
m_DefaultTheme = L"KureiKei";
m_RecommendTheme = L"KureiKeiRecoding";
m_ThemeKeyName = L"ThemeKureiKei";
#else
m_DefaultTheme = L"Shizuku";
m_RecommendTheme = L"ShizukuIdol";
m_ThemeKeyName = L"ThemeShizuku";
#endif
#else
m_DefaultTheme = L"Default";
m_RecommendTheme = L"Default";
m_ThemeKeyName = L"Theme";
#endif
m_RandomThemeLabel = L"Random";
m_BackgroundName = L"Background";
m_hMenu = NULL;
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_hIconMini = AfxGetApp()->LoadIcon(IDI_MINI_ICON);
m_MainIconId = gRegIconId;
m_SmartDir = ((CDiskInfoApp*)AfxGetApp())->m_SmartDir;
// m_GadgetDir = ((CDiskInfoApp*)AfxGetApp())->m_GadgetDir;
m_ExeDir = ((CDiskInfoApp*)AfxGetApp())->m_ExeDir;
m_AlertMailPath = ((CDiskInfoApp*)AfxGetApp())->m_AlertMailPath;
m_OpusDecPath = ((CDiskInfoApp*)AfxGetApp())->m_OpusDecPath;
#ifdef SUISHO_SHIZUKU_SUPPORT
m_VoicePath = ((CDiskInfoApp*) AfxGetApp())->m_VoicePath;
#endif
TCHAR tempPath[MAX_PATH];
GetTempPath(MAX_PATH, tempPath);
m_TempFilePathOpus = tempPath;
m_TempFilePathOpus += _T("CrystalDiskInfo.opus");
m_TempFilePathWave = tempPath;
m_TempFilePathWave += _T("CrystalDiskInfo.wav");
m_bStartupExit = flagStartupExit;
m_AboutDlg = NULL;
m_SettingDlg = NULL;
m_HealthDlg = NULL;
m_OptionDlg = NULL;
// m_AlarmHistoryDlg = NULL;
// Set Default Locale for CStdioFile
_tsetlocale(LC_ALL, _T(""));
for(int i = 0; i < 300; i++)
{
m_hTempIcon[0][i] = NULL;
m_hTempIcon[1][i] = NULL;
}
CString cstr;
for (int i = 0; i < CAtaSmart::MAX_DISK; i++)
{
cstr.Format(L"TempIcon%d", i);
gTempIcon[i] = ::RegisterWindowMessage(cstr);
m_TempIconIndex[i] = gTempIcon[i];
}
m_bTrayMainIcon = FALSE;
for(int i = 0; i < CAtaSmart::MAX_DISK; i++)
{
m_PreTemp[i] = 0;
m_bTrayTemperatureIcon[i] = FALSE;
}
m_SelectDisk = 0;
m_DriveMenuPage = 0;
m_AutoRefreshStatus = 0;
m_WaitTimeStatus = 0;
m_AutoDetectionStatus = 0;
m_RawValues = 0;
m_NowDetectingUnitPowerOnHours = FALSE;
m_bInitializing = TRUE;
DebugPrint(L"CDiskInfoDlg::CDiskInfoDlg - CENTER");
m_ImageList.Create(16, 16, ILC_COLOR32|ILC_MASK, 3, 1);
m_ImageList.Add(AfxGetApp()->LoadIcon(IDI_GOOD));
m_ImageList.Add(AfxGetApp()->LoadIcon(IDI_GOOD_GREEN));
m_ImageList.Add(AfxGetApp()->LoadIcon(IDI_CAUTION));
m_ImageList.Add(AfxGetApp()->LoadIcon(IDI_BAD));
m_ImageList.Add(AfxGetApp()->LoadIcon(IDI_UNKNOWN));
m_bAdvancedDiskSearch = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("AdvancedDiskSearch"), 0, m_Ini);
m_bWorkaroundHD204UI = (BOOL)GetPrivateProfileInt(_T("Workaround"), _T("HD204UI"), 0, m_Ini);
m_bWorkaroundIE8MODE = (BOOL)GetPrivateProfileInt(_T("Workaround"), _T("IE8MODE"), 0, m_Ini);
m_bWorkaroundAdataSsd = (BOOL)GetPrivateProfileInt(_T("Workaround"), _T("AdataSsd"), 1, m_Ini);
m_bWorkaroundIgnoreC4 = (BOOL) GetPrivateProfileInt(_T("Workaround"), _T("IgnoreC4"), 1, m_Ini);
m_bEventLog = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("EventLog"), 0, m_Ini);
m_bAlertMail = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("AlertMail"), 0, m_Ini);
m_bAtaPassThroughSmart = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("AtaPassThroughSmart"), 1, m_Ini);
m_bAutoAamApm = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("AutoAamApm"), 0, m_Ini);
m_bDumpIdentifyDevice = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("DumpIdentifyDevice"), 1, m_Ini); // Default = Enabled
m_bDumpSmartReadData = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("DumpSmartReadData"), 1, m_Ini);
m_bDumpSmartReadThreshold = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("DumpSmartReadThreshold"), 1, m_Ini);
m_bResidentMinimize = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("ResidentMinimize"), 0, m_Ini);
m_bShowTemperatureIconOnly = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("ShowTemperatureIconOnly"), 0, m_Ini);
m_bAsciiView = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("AsciiView"), 0, m_Ini);
m_bSmartEnglish = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("SmartEnglish"), 0, m_Ini);
m_bAlertSound = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("AlertSound"), 1, m_Ini);
m_bHideNoSmartDisk = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("HideNoSmartDisk"), 0, m_Ini);
m_bGreenMode = (BOOL) GetPrivateProfileInt(_T("Setting"), _T("GreenMode"), 0, m_Ini);
m_bForceDisableDarkMode = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("ForceDisableDarkMode"), 0, m_Ini);
if((BOOL)GetPrivateProfileInt(_T("Workaround"), _T("ExecFailed"), 0, m_Ini))
{
m_bAtaPassThroughSmart = FALSE;
WritePrivateProfileString(_T("Setting"), _T("AtaPassThroughSmart"), _T("0"), m_Ini);
}
// Added 2013/04/12 - Workaround for Exec Failed
WritePrivateProfileString(_T("Workaround"), _T("ExecFailed"), _T("1"), m_Ini);
TCHAR str[256];
GetPrivateProfileString(_T("Setting"), _T("AlertSoundPath"), _T(""), str, 256, m_Ini);
m_AlertSoundPath = str;
m_bGadget = (BOOL)GetPrivateProfileInt(_T("Setting"), _T("Gadget"), 0, m_Ini);
m_AutoDetectionStatus = GetPrivateProfileInt(_T("Setting"), _T("AutoDetection"), 0, m_Ini);
if(m_AutoDetectionStatus < 0)
{
m_AutoDetectionStatus = 0;
}
m_RawValues = GetPrivateProfileInt(_T("Setting"), _T("RawValues"), 0, m_Ini);
if(m_RawValues < 0 || m_RawValues > 3)
{
m_RawValues = 0;
}
m_ZoomType = GetPrivateProfileInt(_T("Setting"), _T("ZoomType"), ZoomTypeAuto, m_Ini);
// Setting
SAVE_SMART_PERIOD = GetPrivateProfileInt(_T("Setting"), _T("SAVE_SMART_PERIOD"), 150, m_Ini);
ALARM_TEMPERATURE_PERIOD = GetPrivateProfileInt(_T("Setting"), _T("ALARM_TEMPERATURE_PERIOD"), 60 * 60, m_Ini);
if(m_bEventLog)
{
InstallEventSource();
}
else
{
UninstallEventSource();
}
if(m_bAtaPassThroughSmart)
{
m_Ata.SetAtaPassThroughSmart(TRUE);
}
else
{
m_Ata.SetAtaPassThroughSmart(FALSE);
}
m_Ata.CsmiType = GetPrivateProfileInt(_T("Setting"), _T("CsmiType"), m_Ata.CSMI_TYPE_ENABLE_AUTO, m_Ini);
// m_BrushDlg.CreateHatchBrush(HS_BDIAGONAL, RGB(0xF0, 0xF0, 0xF0));
// m_BrushDlg.CreatePatternBrush(&m_BitmapBk);
#ifdef SUISHO_SHIZUKU_SUPPORT
#ifdef KUREI_KEI_SUPPORT
m_BackgroundName = L"KureiKeiBackground";
#else
m_BackgroundName = L"ShizukuBackground";
#endif
#else
m_BackgroundName = L"Background";
#endif
#ifdef SUISHO_SHIZUKU_SUPPORT
OSVERSIONINFOEX osvi;
BOOL bosVersionInfoEx;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (!(bosVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi)))
{
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx((OSVERSIONINFO *)&osvi);
}
m_hVoice = LoadLibrary(m_VoicePath);
if (m_hVoice != NULL)
{
DebugPrint(L"m_hVoice != NULL");
}
else
{
DebugPrint(L"m_hVoice == NULL");
}
#endif
DebugPrint(L"CDiskInfoDlg::CDiskInfoDlg - END");
}
CDiskInfoDlg::~CDiskInfoDlg()
{
if(m_hMenu != NULL)
{
DestroyMenu(m_hMenu);
}
AlertSound(-1, AS_DEINIT);
DeleteShareInfo();
DeleteFile(m_TempFilePathOpus);
DeleteFile(m_TempFilePathWave);
#ifdef SUISHO_SHIZUKU_SUPPORT
if (m_hVoice)
{
FreeLibrary(m_hVoice);
}
#endif
}
void CDiskInfoDlg::OnCancel()
{
if(m_bResidentMinimize)
{
ShowWindow(SW_MINIMIZE);
}
else
{
ShowWindow(SW_HIDE);
}
if(! m_bResident)
{
SavePos();
KillGraphDlg();
if(m_hDevNotify)
{
UnregisterDeviceNotification(m_hDevNotify);
}
CMainDialogFx::OnCancel();
}
}
void CDiskInfoDlg::OnSaveText()
{
CString path;
SYSTEMTIME st;
GetLocalTime(&st);
path.Format(L"%s_%04d%02d%02d%02d%02d%02d", PRODUCT_NAME, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
CString filter = L"TEXT (*.txt)|*.txt||";
CFileDialog save(FALSE, L"txt", path, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_EXPLORER, filter);
if (save.DoModal() == IDOK)
{
SaveText(save.GetPathName());
}
}
void CDiskInfoDlg::OnSaveImage()
{
SaveImage();
}
void CDiskInfoDlg::OnExit()
{
SavePos();
ShowWindow(SW_HIDE);
RemoveTrayMainIcon();
for(int i = 0; i < m_Ata.vars.GetCount(); i++)
{
RemoveTemperatureIcon(i);
}
KillGraphDlg();
CMainDialogFx::OnCancel();
}
void CDiskInfoDlg::OnOK()
{
}
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam);
void CDiskInfoDlg::KillGraphDlg()
{
static HWND hWnd;
EnumWindows(EnumWindowsProc, (LPARAM)&m_GraphProcessId);
}
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
CArray<DWORD, DWORD> *id = (CArray<DWORD, DWORD>*)lParam;
TCHAR str[1024];
GetWindowText(hWnd, str, 1024);
if(str[0] == 0)
{
return TRUE;
}
CString cstr;
cstr = str;
if(cstr.Find(_T("CrystalDiskInfo - ")) == 0 && cstr.Find(_T(" - Powered by Flot")) > 0)
{
for(int i = 0; i < id->GetCount(); i++)
{
DWORD processId = 0;
::GetWindowThreadProcessId(hWnd, &processId);
if(processId == id->GetAt(i))
{
PostMessage(hWnd, WM_QUIT, NULL, NULL);
}
}
}
return TRUE;
}
void CDiskInfoDlg::DoDataExchange(CDataExchange* pDX)
{
CMainDialogFx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST, m_List);
DDX_Control(pDX, IDC_BUTTON_DISK0, m_ButtonDisk[0]);
DDX_Control(pDX, IDC_BUTTON_DISK1, m_ButtonDisk[1]);
DDX_Control(pDX, IDC_BUTTON_DISK2, m_ButtonDisk[2]);
DDX_Control(pDX, IDC_BUTTON_DISK3, m_ButtonDisk[3]);
DDX_Control(pDX, IDC_BUTTON_DISK4, m_ButtonDisk[4]);
DDX_Control(pDX, IDC_BUTTON_DISK5, m_ButtonDisk[5]);
DDX_Control(pDX, IDC_BUTTON_DISK6, m_ButtonDisk[6]);
DDX_Control(pDX, IDC_BUTTON_DISK7, m_ButtonDisk[7]);
DDX_Control(pDX, IDC_BUTTON_PRE_DISK, m_CtrlButtonPreDisk);
DDX_Control(pDX, IDC_BUTTON_NEXT_DISK, m_CtrlButtonNextDisk);
DDX_Control(pDX, IDC_LABEL_FIRMWARE, m_CtrlLabelFirmware);
DDX_Control(pDX, IDC_LABEL_SERIAL_NUMBER, m_CtrlLabelSerialNumber);
DDX_Control(pDX, IDC_LABEL_INTERFACE, m_CtrlLabelInterface);
DDX_Control(pDX, IDC_LABEL_TRANSFER_MODE, m_CtrlLabelTransferMode);
DDX_Control(pDX, IDC_LABEL_DRIVE_MAP, m_CtrlLabelDriveMap);
DDX_Control(pDX, IDC_LABEL_BUFFER_SIZE, m_CtrlLabelBufferSize);
DDX_Control(pDX, IDC_LABEL_NV_CACHE_SIZE, m_CtrlLabelNvCacheSize);
DDX_Control(pDX, IDC_LABEL_ROTATION_RATE, m_CtrlLabelRotationRate);
DDX_Control(pDX, IDC_LABEL_POWER_ON_COUNT, m_CtrlLabelPowerOnCount);
DDX_Control(pDX, IDC_LABEL_POWER_ON_HOURS, m_CtrlLabelPowerOnHours);
DDX_Control(pDX, IDC_LABEL_ATA_ATAPI, m_CtrlLabelAtaAtapi);
DDX_Control(pDX, IDC_LABEL_FEATURE, m_CtrlLabelFeature);
DDX_Control(pDX, IDC_LABEL_HEALTH_STATUS, m_CtrlLabelDiskStatus);
DDX_Control(pDX, IDC_LABEL_TEMPERATURE, m_CtrlLabelTemperature);
DDX_Control(pDX, IDC_VALUE_MODEL, m_CtrlModel);
DDX_Control(pDX, IDC_VALUE_FIRMWARE, m_CtrlFirmware);
DDX_Control(pDX, IDC_VALUE_SERIAL_NUMBER, m_CtrlSerialNumber);
DDX_Control(pDX, IDC_VALUE_INTERFACE, m_CtrlInterface);
DDX_Control(pDX, IDC_VALUE_TRANSFER_MODE, m_CtrlTransferMode);
DDX_Control(pDX, IDC_VALUE_DRIVE_MAP, m_CtrlDriveMap);
DDX_Control(pDX, IDC_VALUE_BUFFER_SIZE, m_CtrlBufferSize);
DDX_Control(pDX, IDC_VALUE_NV_CACHE_SIZE, m_CtrlNvCacheSize);
DDX_Control(pDX, IDC_VALUE_ROTATION_RATE, m_CtrlRotationRate);
DDX_Control(pDX, IDC_VALUE_POWER_ON_COUNT, m_CtrlPowerOnCount);
DDX_Control(pDX, IDC_VALUE_POWER_ON_HOURS, m_CtrlPowerOnHours);
DDX_Control(pDX, IDC_VALUE_ATA_ATAPI, m_CtrlAtaAtapi);
DDX_Control(pDX, IDC_VALUE_FEATURE, m_CtrlFeature);
DDX_Control(pDX, IDC_BUTTON_HEALTH_STATUS, m_CtrlDiskStatus);
DDX_Control(pDX, IDC_BUTTON_TEMPERATURE, m_CtrlTemperature);
DDX_Control(pDX, IDC_BUTTON_LIFE, m_CtrlLife);
DDX_Text(pDX, IDC_BUTTON_DISK0, m_LiDisk[0]);
DDX_Text(pDX, IDC_BUTTON_DISK1, m_LiDisk[1]);
DDX_Text(pDX, IDC_BUTTON_DISK2, m_LiDisk[2]);
DDX_Text(pDX, IDC_BUTTON_DISK3, m_LiDisk[3]);
DDX_Text(pDX, IDC_BUTTON_DISK4, m_LiDisk[4]);
DDX_Text(pDX, IDC_BUTTON_DISK5, m_LiDisk[5]);
DDX_Text(pDX, IDC_BUTTON_DISK6, m_LiDisk[6]);
DDX_Text(pDX, IDC_BUTTON_DISK7, m_LiDisk[7]);
DDX_Text(pDX, IDC_LABEL_FIRMWARE, m_LabelFirmware);
DDX_Text(pDX, IDC_LABEL_SERIAL_NUMBER, m_LabelSerialNumber);
DDX_Text(pDX, IDC_LABEL_INTERFACE, m_LabelInterface);
DDX_Text(pDX, IDC_LABEL_TRANSFER_MODE, m_LabelTransferMode);
DDX_Text(pDX, IDC_LABEL_DRIVE_MAP, m_LabelDriveMap);
DDX_Text(pDX, IDC_LABEL_BUFFER_SIZE, m_LabelBufferSize);
DDX_Text(pDX, IDC_LABEL_NV_CACHE_SIZE, m_LabelNvCacheSize);
DDX_Text(pDX, IDC_LABEL_ROTATION_RATE, m_LabelRotationRate);
DDX_Text(pDX, IDC_LABEL_POWER_ON_COUNT, m_LabelPowerOnCount);
DDX_Text(pDX, IDC_LABEL_POWER_ON_HOURS, m_LabelPowerOnHours);
DDX_Text(pDX, IDC_LABEL_ATA_ATAPI, m_LabelAtaAtapi);
DDX_Text(pDX, IDC_LABEL_FEATURE, m_LabelFeature);
DDX_Text(pDX, IDC_LABEL_HEALTH_STATUS, m_LabelDiskStatus);
DDX_Text(pDX, IDC_LABEL_TEMPERATURE, m_LabelTemperature);
DDX_Text(pDX, IDC_VALUE_MODEL, m_ModelCapacity);
DDX_Text(pDX, IDC_VALUE_FIRMWARE, m_Firmware);
DDX_Text(pDX, IDC_VALUE_SERIAL_NUMBER, m_SerialNumber);
DDX_Text(pDX, IDC_VALUE_INTERFACE, m_Interface);
DDX_Text(pDX, IDC_VALUE_TRANSFER_MODE, m_TransferMode);
DDX_Text(pDX, IDC_VALUE_DRIVE_MAP, m_DriveMap);
DDX_Text(pDX, IDC_VALUE_BUFFER_SIZE, m_BufferSize);
DDX_Text(pDX, IDC_VALUE_NV_CACHE_SIZE, m_NvCacheSize);
DDX_Text(pDX, IDC_VALUE_ROTATION_RATE, m_RotationRate);
DDX_Text(pDX, IDC_VALUE_POWER_ON_COUNT, m_PowerOnCount);
DDX_Text(pDX, IDC_VALUE_POWER_ON_HOURS, m_PowerOnHours);
DDX_Text(pDX, IDC_VALUE_ATA_ATAPI, m_AtaAtapi);
DDX_Text(pDX, IDC_VALUE_FEATURE, m_Feature);
DDX_Text(pDX, IDC_BUTTON_HEALTH_STATUS, m_DiskStatus);
DDX_Text(pDX, IDC_BUTTON_TEMPERATURE, m_Temperature);
DDX_Text(pDX, IDC_BUTTON_LIFE, m_Life);
DDX_Control(pDX, IDC_BUTTON_VOICE, m_CtrlVoice);
DDX_Control(pDX, IDC_BUTTON_VOICE_HIDE, m_CtrlVoiceHide);
DDX_Control(pDX, IDC_BUTTON_COPYRIGHT, m_CtrlCopyright);
}
BEGIN_MESSAGE_MAP(CDiskInfoDlg, CMainDialogFx)
//}}AFX_MSG_MAP
ON_WM_PAINT()
ON_WM_GETMINMAXINFO()
ON_WM_SIZE()
ON_WM_TIMER()
ON_COMMAND(ID_SAVE_TEXT, &CDiskInfoDlg::OnSaveText)
ON_COMMAND(ID_SAVE_IMAGE, &CDiskInfoDlg::OnSaveImage)
ON_COMMAND(ID_EXIT, &CDiskInfoDlg::OnExit)
ON_COMMAND(ID_ABOUT, &CDiskInfoDlg::OnAbout)
ON_COMMAND(ID_HIDE_SMART_INFO, &CDiskInfoDlg::OnHideSmartInfo)
ON_COMMAND(ID_HIDE_SERIAL_NUMBER, &CDiskInfoDlg::OnHideSerialNumber)
ON_COMMAND(ID_COPY, &CDiskInfoDlg::OnCopy)
ON_COMMAND(ID_CRYSTALDEWWORLD, &CDiskInfoDlg::OnCrystalDewWorld)
ON_COMMAND(ID_AMD_RC2T7, &CDiskInfoDlg::OnAmdRc2t7)
ON_COMMAND(ID_REFRESH, &CDiskInfoDlg::OnRefresh)
ON_COMMAND(ID_HELP_ABOUT_SMART, &CDiskInfoDlg::OnHelpAboutSmart)
ON_COMMAND(ID_AUTO_REFRESH_DISABLE, &CDiskInfoDlg::OnAutoRefreshDisable)
ON_COMMAND(ID_AUTO_REFRESH_01_MIN, &CDiskInfoDlg::OnAutoRefresh01Min)
ON_COMMAND(ID_AUTO_REFRESH_03_MIN, &CDiskInfoDlg::OnAutoRefresh03Min)
ON_COMMAND(ID_AUTO_REFRESH_05_MIN, &CDiskInfoDlg::OnAutoRefresh05Min)
ON_COMMAND(ID_AUTO_REFRESH_10_MIN, &CDiskInfoDlg::OnAutoRefresh10Min)
ON_COMMAND(ID_AUTO_REFRESH_30_MIN, &CDiskInfoDlg::OnAutoRefresh30Min)
ON_COMMAND(ID_AUTO_REFRESH_60_MIN, &CDiskInfoDlg::OnAutoRefresh60Min)
ON_COMMAND(ID_AUTO_REFRESH_120_MIN, &CDiskInfoDlg::OnAutoRefresh120Min)
ON_COMMAND(ID_AUTO_REFRESH_180_MIN, &CDiskInfoDlg::OnAutoRefresh180Min)
ON_COMMAND(ID_AUTO_REFRESH_360_MIN, &CDiskInfoDlg::OnAutoRefresh360Min)
ON_COMMAND(ID_AUTO_REFRESH_720_MIN, &CDiskInfoDlg::OnAutoRefresh720Min)
ON_COMMAND(ID_AUTO_REFRESH_1440_MIN, &CDiskInfoDlg::OnAutoRefresh1440Min)
ON_COMMAND(ID_OPEN_DISK_MANAGEMENT, &CDiskInfoDlg::OnOpenDiskManagement)
ON_COMMAND(ID_OPEN_DEVICE_MANAGER, &CDiskInfoDlg::OnOpenDeviceManager)
ON_COMMAND(ID_ADVANCED_DISK_SEARCH, &CDiskInfoDlg::OnAdvancedDiskSearch)
ON_COMMAND(ID_WORKAROUND_HD204UI, &CDiskInfoDlg::OnWorkaroundHD204UI)
ON_COMMAND(ID_WORKAROUND_IE8MODE, &CDiskInfoDlg::OnWorkaroundIE8MODE)
ON_COMMAND(ID_GREEN_MODE, &CDiskInfoDlg::OnGreenMode)
ON_COMMAND(ID_DISABLE_DARK_MODE, &CDiskInfoDlg::OnDisableDarkMode)
ON_COMMAND(ID_WORKAROUND_ADATA_SSD, &CDiskInfoDlg::OnWorkaroundAdataSsd)
ON_COMMAND(ID_WORKAROUND_IGNORE_C4, &CDiskInfoDlg::OnWorkaroundIgnoreC4)
ON_COMMAND(ID_RESIDENT, &CDiskInfoDlg::OnResident)
ON_MESSAGE(WM_POWERBROADCAST, &CDiskInfoDlg::OnPowerBroadcast)
ON_MESSAGE(WM_DEVICECHANGE, &CDiskInfoDlg::OnDeviceChange)
ON_MESSAGE(WM_QUERYENDSESSION, &CDiskInfoDlg::OnQueryEndSession)
// Task Tray
ON_REGISTERED_MESSAGE(gRegMessageId, OnRegMessage)
ON_REGISTERED_MESSAGE(wmTaskbarCreated, OnTaskbarCreated)
ON_REGISTERED_MESSAGE(gTempIcon[0], OnTempIcon0)
ON_REGISTERED_MESSAGE(gTempIcon[1], OnTempIcon1)
ON_REGISTERED_MESSAGE(gTempIcon[2], OnTempIcon2)
ON_REGISTERED_MESSAGE(gTempIcon[3], OnTempIcon3)
ON_REGISTERED_MESSAGE(gTempIcon[4], OnTempIcon4)
ON_REGISTERED_MESSAGE(gTempIcon[5], OnTempIcon5)
ON_REGISTERED_MESSAGE(gTempIcon[6], OnTempIcon6)
ON_REGISTERED_MESSAGE(gTempIcon[7], OnTempIcon7)
ON_REGISTERED_MESSAGE(gTempIcon[8], OnTempIcon8)
ON_REGISTERED_MESSAGE(gTempIcon[9], OnTempIcon9)
ON_REGISTERED_MESSAGE(gTempIcon[10], OnTempIcon10)
ON_REGISTERED_MESSAGE(gTempIcon[11], OnTempIcon11)
ON_REGISTERED_MESSAGE(gTempIcon[12], OnTempIcon12)
ON_REGISTERED_MESSAGE(gTempIcon[13], OnTempIcon13)
ON_REGISTERED_MESSAGE(gTempIcon[14], OnTempIcon14)
ON_REGISTERED_MESSAGE(gTempIcon[15], OnTempIcon15)
ON_REGISTERED_MESSAGE(gTempIcon[16], OnTempIcon16)
ON_REGISTERED_MESSAGE(gTempIcon[17], OnTempIcon17)
ON_REGISTERED_MESSAGE(gTempIcon[18], OnTempIcon18)
ON_REGISTERED_MESSAGE(gTempIcon[19], OnTempIcon19)
ON_REGISTERED_MESSAGE(gTempIcon[20], OnTempIcon20)
ON_REGISTERED_MESSAGE(gTempIcon[21], OnTempIcon21)
ON_REGISTERED_MESSAGE(gTempIcon[22], OnTempIcon22)
ON_REGISTERED_MESSAGE(gTempIcon[23], OnTempIcon23)
ON_REGISTERED_MESSAGE(gTempIcon[24], OnTempIcon24)
ON_REGISTERED_MESSAGE(gTempIcon[25], OnTempIcon25)
ON_REGISTERED_MESSAGE(gTempIcon[26], OnTempIcon26)
ON_REGISTERED_MESSAGE(gTempIcon[27], OnTempIcon27)
ON_REGISTERED_MESSAGE(gTempIcon[28], OnTempIcon28)
ON_REGISTERED_MESSAGE(gTempIcon[29], OnTempIcon29)
ON_REGISTERED_MESSAGE(gTempIcon[30], OnTempIcon30)
ON_REGISTERED_MESSAGE(gTempIcon[31], OnTempIcon31)
ON_REGISTERED_MESSAGE(gTempIcon[32], OnTempIcon32)
ON_REGISTERED_MESSAGE(gTempIcon[33], OnTempIcon33)
ON_REGISTERED_MESSAGE(gTempIcon[34], OnTempIcon34)
ON_REGISTERED_MESSAGE(gTempIcon[35], OnTempIcon35)
ON_REGISTERED_MESSAGE(gTempIcon[36], OnTempIcon36)
ON_REGISTERED_MESSAGE(gTempIcon[37], OnTempIcon37)
ON_REGISTERED_MESSAGE(gTempIcon[38], OnTempIcon38)
ON_REGISTERED_MESSAGE(gTempIcon[39], OnTempIcon39)
ON_REGISTERED_MESSAGE(gTempIcon[40], OnTempIcon40)
ON_REGISTERED_MESSAGE(gTempIcon[41], OnTempIcon41)
ON_REGISTERED_MESSAGE(gTempIcon[42], OnTempIcon42)
ON_REGISTERED_MESSAGE(gTempIcon[43], OnTempIcon43)
ON_REGISTERED_MESSAGE(gTempIcon[44], OnTempIcon44)
ON_REGISTERED_MESSAGE(gTempIcon[45], OnTempIcon45)
ON_REGISTERED_MESSAGE(gTempIcon[46], OnTempIcon46)
ON_REGISTERED_MESSAGE(gTempIcon[47], OnTempIcon47)
ON_REGISTERED_MESSAGE(gTempIcon[48], OnTempIcon48)
ON_REGISTERED_MESSAGE(gTempIcon[49], OnTempIcon49)
ON_REGISTERED_MESSAGE(gTempIcon[50], OnTempIcon50)
ON_REGISTERED_MESSAGE(gTempIcon[51], OnTempIcon51)
ON_REGISTERED_MESSAGE(gTempIcon[52], OnTempIcon52)
ON_REGISTERED_MESSAGE(gTempIcon[53], OnTempIcon53)
ON_REGISTERED_MESSAGE(gTempIcon[54], OnTempIcon54)
ON_REGISTERED_MESSAGE(gTempIcon[55], OnTempIcon55)
ON_REGISTERED_MESSAGE(gTempIcon[56], OnTempIcon56)
ON_REGISTERED_MESSAGE(gTempIcon[57], OnTempIcon57)
ON_REGISTERED_MESSAGE(gTempIcon[58], OnTempIcon58)
ON_REGISTERED_MESSAGE(gTempIcon[59], OnTempIcon59)
ON_REGISTERED_MESSAGE(gTempIcon[60], OnTempIcon60)
ON_REGISTERED_MESSAGE(gTempIcon[61], OnTempIcon61)
ON_REGISTERED_MESSAGE(gTempIcon[62], OnTempIcon62)
ON_REGISTERED_MESSAGE(gTempIcon[63], OnTempIcon63)
ON_REGISTERED_MESSAGE(gTempIcon[64], OnTempIcon64)
ON_REGISTERED_MESSAGE(gTempIcon[65], OnTempIcon65)
ON_REGISTERED_MESSAGE(gTempIcon[66], OnTempIcon66)
ON_REGISTERED_MESSAGE(gTempIcon[67], OnTempIcon67)
ON_REGISTERED_MESSAGE(gTempIcon[68], OnTempIcon68)
ON_REGISTERED_MESSAGE(gTempIcon[69], OnTempIcon69)
ON_REGISTERED_MESSAGE(gTempIcon[70], OnTempIcon70)
ON_REGISTERED_MESSAGE(gTempIcon[71], OnTempIcon71)
ON_REGISTERED_MESSAGE(gTempIcon[72], OnTempIcon72)
ON_REGISTERED_MESSAGE(gTempIcon[73], OnTempIcon73)
ON_REGISTERED_MESSAGE(gTempIcon[74], OnTempIcon74)
ON_REGISTERED_MESSAGE(gTempIcon[75], OnTempIcon75)
ON_REGISTERED_MESSAGE(gTempIcon[76], OnTempIcon76)
ON_REGISTERED_MESSAGE(gTempIcon[77], OnTempIcon77)
ON_REGISTERED_MESSAGE(gTempIcon[78], OnTempIcon78)
ON_REGISTERED_MESSAGE(gTempIcon[79], OnTempIcon79)
/*
ON_REGISTERED_MESSAGE(gTempIcon[80], OnTempIcon80)
ON_REGISTERED_MESSAGE(gTempIcon[81], OnTempIcon81)
ON_REGISTERED_MESSAGE(gTempIcon[82], OnTempIcon82)
ON_REGISTERED_MESSAGE(gTempIcon[83], OnTempIcon83)
ON_REGISTERED_MESSAGE(gTempIcon[84], OnTempIcon84)
ON_REGISTERED_MESSAGE(gTempIcon[85], OnTempIcon85)
ON_REGISTERED_MESSAGE(gTempIcon[86], OnTempIcon86)
ON_REGISTERED_MESSAGE(gTempIcon[87], OnTempIcon87)
ON_REGISTERED_MESSAGE(gTempIcon[88], OnTempIcon88)
ON_REGISTERED_MESSAGE(gTempIcon[89], OnTempIcon89)
ON_REGISTERED_MESSAGE(gTempIcon[90], OnTempIcon90)
ON_REGISTERED_MESSAGE(gTempIcon[91], OnTempIcon91)
ON_REGISTERED_MESSAGE(gTempIcon[92], OnTempIcon92)
ON_REGISTERED_MESSAGE(gTempIcon[93], OnTempIcon93)
ON_REGISTERED_MESSAGE(gTempIcon[94], OnTempIcon94)
ON_REGISTERED_MESSAGE(gTempIcon[95], OnTempIcon95)
ON_REGISTERED_MESSAGE(gTempIcon[96], OnTempIcon96)
ON_REGISTERED_MESSAGE(gTempIcon[97], OnTempIcon97)
ON_REGISTERED_MESSAGE(gTempIcon[98], OnTempIcon98)
ON_REGISTERED_MESSAGE(gTempIcon[99], OnTempIcon99)
ON_REGISTERED_MESSAGE(gTempIcon[100], OnTempIcon100)
ON_REGISTERED_MESSAGE(gTempIcon[101], OnTempIcon101)
ON_REGISTERED_MESSAGE(gTempIcon[102], OnTempIcon102)
ON_REGISTERED_MESSAGE(gTempIcon[103], OnTempIcon103)
ON_REGISTERED_MESSAGE(gTempIcon[104], OnTempIcon104)
ON_REGISTERED_MESSAGE(gTempIcon[105], OnTempIcon105)
ON_REGISTERED_MESSAGE(gTempIcon[106], OnTempIcon106)
ON_REGISTERED_MESSAGE(gTempIcon[107], OnTempIcon107)
ON_REGISTERED_MESSAGE(gTempIcon[108], OnTempIcon108)
ON_REGISTERED_MESSAGE(gTempIcon[109], OnTempIcon109)
ON_REGISTERED_MESSAGE(gTempIcon[110], OnTempIcon110)
ON_REGISTERED_MESSAGE(gTempIcon[111], OnTempIcon111)
ON_REGISTERED_MESSAGE(gTempIcon[112], OnTempIcon112)
ON_REGISTERED_MESSAGE(gTempIcon[113], OnTempIcon113)
ON_REGISTERED_MESSAGE(gTempIcon[114], OnTempIcon114)
ON_REGISTERED_MESSAGE(gTempIcon[115], OnTempIcon115)
ON_REGISTERED_MESSAGE(gTempIcon[116], OnTempIcon116)
ON_REGISTERED_MESSAGE(gTempIcon[117], OnTempIcon117)
ON_REGISTERED_MESSAGE(gTempIcon[118], OnTempIcon118)
ON_REGISTERED_MESSAGE(gTempIcon[119], OnTempIcon119)
ON_REGISTERED_MESSAGE(gTempIcon[120], OnTempIcon120)
ON_REGISTERED_MESSAGE(gTempIcon[121], OnTempIcon121)
ON_REGISTERED_MESSAGE(gTempIcon[122], OnTempIcon122)
ON_REGISTERED_MESSAGE(gTempIcon[123], OnTempIcon123)
ON_REGISTERED_MESSAGE(gTempIcon[124], OnTempIcon124)
ON_REGISTERED_MESSAGE(gTempIcon[125], OnTempIcon125)
ON_REGISTERED_MESSAGE(gTempIcon[126], OnTempIcon126)
ON_REGISTERED_MESSAGE(gTempIcon[127], OnTempIcon127)
*/
ON_COMMAND(ID_GRAPH, &CDiskInfoDlg::OnGraph)
ON_COMMAND(ID_HELP, &CDiskInfoDlg::OnHelp)
ON_COMMAND(ID_CUSTOMIZE, &CDiskInfoDlg::OnCustomize)
ON_COMMAND(ID_STARTUP, &CDiskInfoDlg::OnStartup)
ON_COMMAND(ID_WAIT_0_SEC, &CDiskInfoDlg::OnWait0Sec)
ON_COMMAND(ID_WAIT_5_SEC, &CDiskInfoDlg::OnWait5Sec)
ON_COMMAND(ID_WAIT_10_SEC, &CDiskInfoDlg::OnWait10Sec)
ON_COMMAND(ID_WAIT_15_SEC, &CDiskInfoDlg::OnWait15Sec)
ON_COMMAND(ID_WAIT_20_SEC, &CDiskInfoDlg::OnWait20Sec)
ON_COMMAND(ID_WAIT_30_SEC, &CDiskInfoDlg::OnWait30Sec)
ON_COMMAND(ID_WAIT_40_SEC, &CDiskInfoDlg::OnWait40Sec)
ON_COMMAND(ID_WAIT_50_SEC, &CDiskInfoDlg::OnWait50Sec)
ON_COMMAND(ID_WAIT_60_SEC, &CDiskInfoDlg::OnWait60Sec)
ON_COMMAND(ID_WAIT_90_SEC, &CDiskInfoDlg::OnWait90Sec)
ON_COMMAND(ID_WAIT_120_SEC, &CDiskInfoDlg::OnWait120Sec)
ON_COMMAND(ID_WAIT_150_SEC, &CDiskInfoDlg::OnWait150Sec)
ON_COMMAND(ID_WAIT_180_SEC, &CDiskInfoDlg::OnWait180Sec)
ON_COMMAND(ID_WAIT_210_SEC, &CDiskInfoDlg::OnWait210Sec)
ON_COMMAND(ID_WAIT_240_SEC, &CDiskInfoDlg::OnWait240Sec)
ON_COMMAND(ID_AUTO_DETECTION_05_SEC, &CDiskInfoDlg::OnAutoDetection05Sec)
ON_COMMAND(ID_AUTO_DETECTION_10_SEC, &CDiskInfoDlg::OnAutoDetection10Sec)
ON_COMMAND(ID_AUTO_DETECTION_20_SEC, &CDiskInfoDlg::OnAutoDetection20Sec)
ON_COMMAND(ID_AUTO_DETECTION_30_SEC, &CDiskInfoDlg::OnAutoDetection30Sec)
ON_COMMAND(ID_AUTO_DETECTION_DISABLE, &CDiskInfoDlg::OnAutoDetectionDisable)
ON_COMMAND(ID_EVENT_LOG, &CDiskInfoDlg::OnEventLog)
ON_COMMAND(ID_ATA_PASS_THROUGH_SMART, &CDiskInfoDlg::OnAtaPassThroughSmart)
ON_COMMAND(ID_GADGET_SUPPORT, &CDiskInfoDlg::OnGadgetSupport)
ON_COMMAND(ID_CELSIUS, &CDiskInfoDlg::OnCelsius)
ON_COMMAND(ID_FAHRENHEIT, &CDiskInfoDlg::OnFahrenheit)
ON_COMMAND(ID_AAM_APM, &CDiskInfoDlg::OnAamApm)
ON_COMMAND(ID_TEMPERATURE, &CDiskInfoDlg::OnTemperature)
ON_COMMAND(ID_AUTO_AAM_APM, &CDiskInfoDlg::OnAutoAamApm)
ON_COMMAND(ID_RESCAN, &CDiskInfoDlg::OnRescan)
ON_COMMAND(ID_USB_SAT, &CDiskInfoDlg::OnUsbSat)
ON_COMMAND(ID_USB_IODATA, &CDiskInfoDlg::OnUsbIodata)
ON_COMMAND(ID_USB_SUNPLUS, &CDiskInfoDlg::OnUsbSunplus)
ON_COMMAND(ID_USB_LOGITEC, &CDiskInfoDlg::OnUsbLogitec)
ON_COMMAND(ID_USB_PROLIFIC, &CDiskInfoDlg::OnUsbProlific)
ON_COMMAND(ID_USB_JMICRON, &CDiskInfoDlg::OnUsbJmicron)
ON_COMMAND(ID_USB_CYPRESS, &CDiskInfoDlg::OnUsbCypress)
ON_COMMAND(ID_USB_ASM1352R, &CDiskInfoDlg::OnUsbASM1352R)
ON_COMMAND(ID_USB_MEMORY, &CDiskInfoDlg::OnUsbMemory)
//ON_COMMAND(ID_USB_SAT16, &CDiskInfoDlg::OnUsbSat16)
ON_COMMAND(ID_USB_NVME_JMICRON, &CDiskInfoDlg::OnUsbNVMeJMicron)
ON_COMMAND(ID_USB_NVME_ASMEDIA, &CDiskInfoDlg::OnUsbNVMeASMedia)
ON_COMMAND(ID_USB_NVME_REALTEK, &CDiskInfoDlg::OnUsbNVMeRealtek)
ON_COMMAND(ID_MEGA_RAID, &CDiskInfoDlg::OnMegaRAID)
ON_COMMAND(ID_USB_ENABLE_ALL, &CDiskInfoDlg::OnUsbEnableAll)
ON_COMMAND(ID_USB_DISABLE_ALL, &CDiskInfoDlg::OnUsbDisableAll)
ON_COMMAND(ID_HEALTH_STATUS, &CDiskInfoDlg::OnHealthStatus)
ON_COMMAND(ID_SOUND_SETTINGS, &CDiskInfoDlg::OnSoundSetting)
ON_COMMAND(ID_DUMP_IDENTIFY_DEVICE, &CDiskInfoDlg::OnDumpIdentifyDevice)
ON_COMMAND(ID_DUMP_SMART_READ_DATA, &CDiskInfoDlg::OnDumpSmartReadData)
ON_COMMAND(ID_DUMP_SMART_READ_THRESHOLD, &CDiskInfoDlg::OnDumpSmartReadThreshold)
ON_COMMAND(ID_RESIDENT_HIDE, &CDiskInfoDlg::OnResidentHide)
ON_COMMAND(ID_RESIDENT_MINIMIZE, &CDiskInfoDlg::OnResidentMinimize)
ON_COMMAND(ID_ZOOM_100, &CDiskInfoDlg::OnZoom100)
ON_COMMAND(ID_ZOOM_125, &CDiskInfoDlg::OnZoom125)
ON_COMMAND(ID_ZOOM_150, &CDiskInfoDlg::OnZoom150)
ON_COMMAND(ID_ZOOM_200, &CDiskInfoDlg::OnZoom200)
ON_COMMAND(ID_ZOOM_250, &CDiskInfoDlg::OnZoom250)
ON_COMMAND(ID_ZOOM_300, &CDiskInfoDlg::OnZoom300)
ON_COMMAND(ID_ZOOM_AUTO, &CDiskInfoDlg::OnZoomAuto)
ON_COMMAND(ID_RAW_VALUES_16, &CDiskInfoDlg::OnRawValues16)
ON_COMMAND(ID_RAW_VALUES_10_ALL, &CDiskInfoDlg::OnRawValues10All)
ON_COMMAND(ID_RAW_VALUES_2BYTE, &CDiskInfoDlg::OnRawValues2byte)
ON_COMMAND(ID_RAW_VALUES_1BYTE, &CDiskInfoDlg::OnRawValues1byte)
ON_COMMAND(ID_ASCII_VIEW, &CDiskInfoDlg::OnAsciiView)
ON_COMMAND(ID_ALERT_MAIL, &CDiskInfoDlg::OnAlertMail)
ON_COMMAND(ID_MAIL_SETTINGS, &CDiskInfoDlg::OnMailSettings)
ON_COMMAND(ID_SMART_ENGLISH, &CDiskInfoDlg::OnSmartEnglish)
ON_COMMAND(ID_FONT_SETTING, &CDiskInfoDlg::OnFontSetting)
ON_COMMAND(ID_CSMI_DISABLE, &CDiskInfoDlg::OnCsmiDisable)
ON_COMMAND(ID_CSMI_ENABLE_AUTO, &CDiskInfoDlg::OnCsmiEnableAuto)
ON_COMMAND(ID_CSMI_ENABLE_RAID, &CDiskInfoDlg::OnCsmiEnableRaid)
ON_COMMAND(ID_CSMI_ENABLE_ALL, &CDiskInfoDlg::OnCsmiEnableAll)
// ON_COMMAND(ID_INSTALL_GADGET, &CDiskInfoDlg::OnInstallGadget)
// ON_COMMAND(ID_ALARM_HISTORY, &CDiskInfoDlg::OnAlarmHistory)
ON_COMMAND(ID_ALERT_SOUND, &CDiskInfoDlg::OnAlertSound)
ON_COMMAND(ID_HIDE_NO_SMART_DISK, &CDiskInfoDlg::OnHideNoSmartDisk)
ON_MESSAGE(MY_PLAY_ALERT_SOUND, OnPlayAlertSound)
ON_BN_CLICKED(IDC_BUTTON_DISK0, &CDiskInfoDlg::OnBnClickedButtonDisk0)
ON_BN_CLICKED(IDC_BUTTON_DISK1, &CDiskInfoDlg::OnBnClickedButtonDisk1)
ON_BN_CLICKED(IDC_BUTTON_DISK2, &CDiskInfoDlg::OnBnClickedButtonDisk2)
ON_BN_CLICKED(IDC_BUTTON_DISK3, &CDiskInfoDlg::OnBnClickedButtonDisk3)
ON_BN_CLICKED(IDC_BUTTON_DISK4, &CDiskInfoDlg::OnBnClickedButtonDisk4)
ON_BN_CLICKED(IDC_BUTTON_DISK5, &CDiskInfoDlg::OnBnClickedButtonDisk5)
ON_BN_CLICKED(IDC_BUTTON_DISK6, &CDiskInfoDlg::OnBnClickedButtonDisk6)
ON_BN_CLICKED(IDC_BUTTON_DISK7, &CDiskInfoDlg::OnBnClickedButtonDisk7)
ON_BN_CLICKED(IDC_BUTTON_PRE_DISK, &CDiskInfoDlg::OnBnClickedButtonPreDisk)
ON_BN_CLICKED(IDC_BUTTON_NEXT_DISK, &CDiskInfoDlg::OnBnClickedButtonNextDisk)
ON_BN_CLICKED(IDC_BUTTON_HEALTH_STATUS, &CDiskInfoDlg::OnBnClickedButtonHealthStatus)
ON_BN_CLICKED(IDC_BUTTON_TEMPERATURE, &CDiskInfoDlg::OnBnClickedButtonTemperature)
ON_BN_CLICKED(IDC_BUTTON_VOICE, &CDiskInfoDlg::OnBnClickedButtonVoice)
ON_BN_CLICKED(IDC_BUTTON_COPYRIGHT, &CDiskInfoDlg::OnBnClickedButtonCopyright)
ON_BN_CLICKED(IDC_BUTTON_LIFE, &CDiskInfoDlg::OnBnClickedButtonLife)
ON_WM_SHOWWINDOW()
ON_WM_NCCREATE()
END_MESSAGE_MAP()
LRESULT CDiskInfoDlg::OnPlayAlertSound(WPARAM wParam, LPARAM lParam)
{
static int id = 0;
static int idlist[21] = {1, 2, 3, 4, 5, 6, 7, 8, 601, 602, 603, 604, 605, 606, 607, 701, 702, 703, 704, 705, 707};
if(wParam == NULL)
{
id = idlist[rand() % 21];
}
else
{
id = (int)wParam;
}
TCHAR str[256];
GetPrivateProfileString(_T("Setting"), _T("AlertSoundPath"), _T(""), str, 256, m_Ini);
m_AlertSoundPath = str;
if (m_AlertSoundPath.Compare(_T("")) != 0)
{
id = 601;
}
AlertSound(id, AS_SET_SOUND_ID);
AlertSound(1000, AS_PLAY_SOUND);
return 0;
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CDiskInfoDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
// CPaintDC dc(this);
// dc.DrawState(CPoint(0, 0), CSize((int)(1000 * m_ZoomRatio), (int)(1000 * m_ZoomRatio)), m_BitmapBk, DST_BITMAP);
CMainDialogFx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CDiskInfoDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
BOOL CDiskInfoDlg::OnCommand(WPARAM wParam, LPARAM lParam)
{
if(WM_LANGUAGE_ID <= wParam && wParam < WM_LANGUAGE_ID + (UINT)m_MenuArrayLang.GetSize())
{
#ifdef _UNICODE
CMenu menu;
CMenu subMenu;
CMenu subMenuAN;
CMenu subMenuOZ;
menu.Attach(GetMenu()->GetSafeHmenu());
subMenu.Attach(menu.GetSubMenu(MENU_LANG_INDEX)->GetSafeHmenu());
subMenuAN.Attach(subMenu.GetSubMenu(0)->GetSafeHmenu());
subMenuOZ.Attach(subMenu.GetSubMenu(1)->GetSafeHmenu());
m_CurrentLang = m_MenuArrayLang.GetAt(wParam - WM_LANGUAGE_ID);
ChangeLang(m_MenuArrayLang.GetAt(wParam - WM_LANGUAGE_ID));
subMenuAN.CheckMenuRadioItem(WM_LANGUAGE_ID, WM_LANGUAGE_ID + (UINT)m_MenuArrayLang.GetSize(),
(UINT)wParam, MF_BYCOMMAND);
subMenuOZ.CheckMenuRadioItem(WM_LANGUAGE_ID, WM_LANGUAGE_ID + (UINT)m_MenuArrayLang.GetSize(),
(UINT)wParam, MF_BYCOMMAND);
subMenuOZ.Detach();
subMenuAN.Detach();
subMenu.Detach();
menu.Detach();
#else
CMenu menu;
CMenu subMenu;
menu.Attach(GetMenu()->GetSafeHmenu());
subMenu.Attach(menu.GetSubMenu(MENU_LANG_INDEX)->GetSafeHmenu());
m_CurrentLang = m_MenuArrayLang.GetAt(wParam - WM_LANGUAGE_ID);
ChangeLang(m_MenuArrayLang.GetAt(wParam - WM_LANGUAGE_ID));
subMenu.CheckMenuRadioItem(WM_LANGUAGE_ID, WM_LANGUAGE_ID + (UINT)m_MenuArrayLang.GetSize(),
(UINT)wParam, MF_BYCOMMAND);
subMenu.Detach();
menu.Detach();
#endif
}
// Task Tray Menu
else if(wParam == MY_EXIT)
{
SavePos();
RemoveTrayMainIcon();
for(int i = 0; i < m_Ata.vars.GetCount(); i++)
{
RemoveTemperatureIcon(i);
}
KillGraphDlg();
CMainDialogFx::OnCancel();
}
else if(wParam == MY_SHOW_MAIN_DIALOG && m_bResidentMinimize)
{
if(! IsIconic())
{
ShowWindowEx(SW_MINIMIZE);
}
else
{
ShowWindowEx(SW_RESTORE);
}
}
else if(wParam == MY_SHOW_MAIN_DIALOG)
{
if(IsWindowVisible())
{
ShowWindowEx(SW_HIDE);
}
else
{
ShowWindowEx(SW_RESTORE);
}
}
else if(wParam == MY_SHOW_TEMPERATURE_ICON_ONLY)
{
ShowTemperatureIconOnly();
}
else if(wParam == SHOW_GRAPH_BASE + CAtaSmart::MAX_DISK)
{
ShowGraphDlg(-1); // Using "GraphHideDisk" option
}
else if(SHOW_GRAPH_BASE <= wParam && wParam < SHOW_GRAPH_BASE + CAtaSmart::MAX_DISK)
{
ShowGraphDlg((int)wParam - SHOW_GRAPH_BASE);
}
else if(ALARM_SETTING_HEALTH_STATUS_BASE <= wParam && wParam <= ALARM_SETTING_HEALTH_STATUS_BASE + CAtaSmart::MAX_DISK + 1)
{
int i = (int)(wParam - ALARM_SETTING_HEALTH_STATUS_BASE);
if(i == CAtaSmart::MAX_DISK + 1) // Disable All
{
for(int j = 0; j < m_Ata.vars.GetCount(); j++)
{
m_Ata.vars[j].AlarmHealthStatus = FALSE;
WritePrivateProfileString(_T("AlarmHealthStatus"), m_Ata.vars[j].ModelSerial, _T("0"), m_Ini);
}
}
else if(i == CAtaSmart::MAX_DISK) // Enable All
{
for(int j = 0; j < m_Ata.vars.GetCount(); j++)
{
m_Ata.vars[j].AlarmHealthStatus = TRUE;
WritePrivateProfileString(_T("AlarmHealthStatus"), m_Ata.vars[j].ModelSerial, _T("1"), m_Ini);
}
}
else
{
CString alarm;
if(m_Ata.vars[i].AlarmHealthStatus)
{
m_Ata.vars[i].AlarmHealthStatus = FALSE;
alarm.Format(_T("%d"), FALSE);
}
else
{
m_Ata.vars[i].AlarmHealthStatus = TRUE;
alarm.Format(_T("%d"), TRUE);
}
WritePrivateProfileString(_T("AlarmHealthStatus"), m_Ata.vars[i].ModelSerial, alarm, m_Ini);
}
}
else if(ALARM_SETTING_TEMPERATURE_BASE <= wParam && wParam <= ALARM_SETTING_TEMPERATURE_BASE + (CAtaSmart::MAX_DISK + 1) * 100)
{
int i = (int)(wParam - ALARM_SETTING_TEMPERATURE_BASE) / 100;
int j = (int)(wParam - ALARM_SETTING_TEMPERATURE_BASE) % 100;
if(i == CAtaSmart::MAX_DISK)
{
for(int k = 0; k < m_Ata.vars.GetCount(); k++)
{
m_Ata.vars[k].AlarmTemperature = j;
CString temperature;
temperature.Format(_T("%d"), j);
WritePrivateProfileString(_T("AlarmTemperature"), m_Ata.vars[k].Model + m_Ata.vars[k].SerialNumber, temperature, m_Ini);
}
}
else
{
m_Ata.vars[i].AlarmTemperature = j;
CString temperature;
temperature.Format(_T("%d"), j);
WritePrivateProfileString(_T("AlarmTemperature"), m_Ata.vars[i].ModelSerial, temperature, m_Ini);
}
}
else if(TRAY_TEMPERATURE_ICON_BASE <= wParam && wParam <= TRAY_TEMPERATURE_ICON_BASE + CAtaSmart::MAX_DISK + 1)
{
int i = (int)(wParam - TRAY_TEMPERATURE_ICON_BASE);
if(i == CAtaSmart::MAX_DISK + 1) // Hide All
{
for(int j = 0; j < m_Ata.vars.GetCount(); j++)
{
if(m_bTrayTemperatureIcon[j])
{
if(RemoveTemperatureIcon(j))
{
CString cstr;
cstr.Format(_T("%d"), 0);
WritePrivateProfileString(_T("TemperatureIcon"), m_Ata.vars[j].ModelSerial, cstr, m_Ini);
}
}
}
if(m_bShowTemperatureIconOnly && ! IsTemperatureIconExist())
{
AddTrayMainIcon();
}
}
else if(i == CAtaSmart::MAX_DISK) // Show All
{
int max = gRegIconId;
for(int j = (int)m_Ata.vars.GetCount() -1; j >= 0; j--)
{
if(! m_bTrayTemperatureIcon[j])
{
if(AddTemperatureIcon(j))
{
CString cstr;
cstr.Format(_T("%d"), 1);
WritePrivateProfileString(_T("TemperatureIcon"), m_Ata.vars[j].ModelSerial, cstr, m_Ini);
max = TRAY_TEMPERATURE_ICON_BASE + j;
}
}
}
if(m_bShowTemperatureIconOnly && IsTemperatureIconExist())
{
if(RemoveTrayMainIcon())
{
m_MainIconId = max;
}
}
else
{
AddTrayMainIcon();
}
}
else
{
if(m_bTrayTemperatureIcon[i])
{
if(RemoveTemperatureIcon(i))
{
CString cstr;
cstr.Format(_T("%d"), 0);
WritePrivateProfileString(_T("TemperatureIcon"), m_Ata.vars[i].ModelSerial, cstr, m_Ini);
if(! IsTemperatureIconExist())
{
AddTrayMainIcon();
}
}
}
else if(AddTemperatureIcon(i))
{
CString cstr;
cstr.Format(_T("%d"), 1);
WritePrivateProfileString(_T("TemperatureIcon"), m_Ata.vars[i].ModelSerial, cstr, m_Ini);
if(m_bShowTemperatureIconOnly && IsTemperatureIconExist())
{
if(RemoveTrayMainIcon())
{
m_MainIconId = TRAY_TEMPERATURE_ICON_BASE + i;
}
}
}
}
}
else if(SELECT_DISK_BASE <= wParam && wParam < SELECT_DISK_BASE + CAtaSmart::MAX_DISK)
{
int i = (int)(wParam - SELECT_DISK_BASE);
m_DriveMenuPage = i / 8;
SelectDrive(i);
}
else if(AUTO_REFRESH_TARGET_BASE <= wParam && wParam <= AUTO_REFRESH_TARGET_BASE + CAtaSmart::MAX_DISK + 1)
{
int i = (int)(wParam - AUTO_REFRESH_TARGET_BASE);
// Target All Disk : AUTO_REFRESH_TARGET_BASE + CAtaSmart::MAX_DISK
// Unarget All Disk : AUTO_REFRESH_TARGET_BASE + CAtaSmart::MAX_DISK
CMenu *menu = GetMenu();
if(i == CAtaSmart::MAX_DISK) // Target All Disk
{
for(int j = 0; j < m_Ata.vars.GetCount(); j++)
{
m_bAutoRefreshTarget[j] = TRUE;
menu->CheckMenuItem(AUTO_REFRESH_TARGET_BASE + j, MF_CHECKED);
WritePrivateProfileString(_T("AutoRefreshTarget"), m_Ata.vars[j].ModelSerial, _T("1"), m_Ini);
}
}
else if(i == CAtaSmart::MAX_DISK + 1) // Unarget All Disk
{
for(int j = 0; j < m_Ata.vars.GetCount(); j++)
{
m_bAutoRefreshTarget[j] = FALSE;
menu->CheckMenuItem(AUTO_REFRESH_TARGET_BASE + j, MF_UNCHECKED);
WritePrivateProfileString(_T("AutoRefreshTarget"), m_Ata.vars[j].ModelSerial, _T("0"), m_Ini);
}
}
else
{
if(m_bAutoRefreshTarget[i])
{
m_bAutoRefreshTarget[i] = FALSE;
menu->CheckMenuItem(AUTO_REFRESH_TARGET_BASE + i, MF_UNCHECKED);
WritePrivateProfileString(_T("AutoRefreshTarget"), m_Ata.vars[i].ModelSerial, _T("0"), m_Ini);
}
else
{
m_bAutoRefreshTarget[i] = TRUE;
menu->CheckMenuItem(AUTO_REFRESH_TARGET_BASE + i, MF_CHECKED);
WritePrivateProfileString(_T("AutoRefreshTarget"), m_Ata.vars[i].ModelSerial, _T("1"), m_Ini);
}
}
SetMenu(menu);
DrawMenuBar();
}
else if(WM_THEME_ID <= wParam && wParam < WM_THEME_ID + (UINT)m_MenuArrayTheme.GetSize())
{
#ifndef SUISHO_SHIZUKU_SUPPORT
CMenu *menu = GetMenu();
if (menu->GetMenuState(ID_GREEN_MODE, MF_BYCOMMAND) & MFS_CHECKED)
{
m_bGreenMode = TRUE;
}
else
{
m_bGreenMode = FALSE;
}
#endif
CMainDialogFx::OnCommand(wParam, lParam);
#ifndef SUISHO_SHIZUKU_SUPPORT
if(m_CurrentTheme.Compare(_T("Simplicity")) == 0)
{
m_bGreenMode = TRUE;
}
#endif
UpdateListCtrl(m_SelectDisk);
return TRUE;
}
return CMainDialogFx::OnCommand(wParam, lParam);
}
void CDiskInfoDlg::UpdateDialogSize()
{
CDialogFx::UpdateDialogSize();
if (GetPrivateProfileInt(_T("Setting"), _T("HideSmartInfo"), 0, m_Ini))
{
m_SizeX = SIZE_X;
m_SizeY = SIZE_MIN_Y;
m_bHideSmartInfo = TRUE;
SetClientSize(m_SizeX, m_SizeY, m_ZoomRatio);
CMenu *menu = GetMenu();
menu->CheckMenuItem(ID_HIDE_SMART_INFO, MF_CHECKED);
SetMenu(menu);
DrawMenuBar();
}
else
{
m_SizeX = SIZE_SMART_X;
int y = GetPrivateProfileInt(_T("Setting"), _T("Height"), SIZE_SMART_Y, m_Ini);
if (y > 0)
{
m_SizeY = y;
}
if (m_SizeY < SIZE_MIN_Y)
{
m_SizeY = SIZE_MIN_Y;
}
else if (m_SizeY > SIZE_MAX_Y)
{
m_SizeY = SIZE_MAX_Y;
}
SetClientSize(m_SizeX, m_SizeY, m_ZoomRatio);
m_bHideSmartInfo = FALSE;
CMenu *menu = GetMenu();
menu->CheckMenuItem(ID_HIDE_SMART_INFO, MF_UNCHECKED);
SetMenu(menu);
DrawMenuBar();
}
UpdateBackground(TRUE, FALSE);
SetControlFont();
#ifdef SUISHO_SHIZUKU_SUPPORT
int positionX = 0;
if (m_CharacterPosition == 0)
{
m_OffsetX = OFFSET_X;
positionX = 0;
}
else
{
m_OffsetX = 0;
positionX = 1000 - OFFSET_X;
}
m_CtrlVoice.InitControl(positionX, 48, OFFSET_X, m_SizeY - 24 - 48, m_ZoomRatio, &m_BkDC, NULL, 0, BS_CENTER, OwnerDrawTransparent, FALSE, FALSE, FALSE);
m_CtrlVoiceHide.InitControl(positionX, 0, OFFSET_X, 48, m_ZoomRatio, &m_BkDC, NULL, 0, BS_CENTER, OwnerDrawTransparent, FALSE, FALSE, FALSE);
m_CtrlVoice.SetHandCursor();
if (m_CurrentLang.Find(L"Japanese") == 0)
{
/*
SYSTEMTIME systime;
GetLocalTime(&systime);
if ((systime.wYear == 2015 && systime.wMonth == 12 && systime.wDay <= 17)
|| (systime.wYear == 2015 && systime.wMonth == 12 && systime.wDay == 18 && systime.wHour < 20))
{
m_CtrlCopyright.InitControl(0, m_SizeY - 24, OFFSET_X, 24, m_ZoomRatio, IP(L"ShizukuAkibaMoe"), 1, SS_CENTER, CButtonCx::OwnerDrawImage);
}
else
{ }
*/
m_CtrlCopyright.InitControl((int)(positionX * m_ZoomRatio), (int)(m_SizeY * m_ZoomRatio) - (int)(24 * m_ZoomRatio), (int)(OFFSET_X * m_ZoomRatio), (int)(24 * m_ZoomRatio), 1.0, &m_BkDC, IP(PROJECT_COPYRIGHT), 1, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
}
else
{
m_CtrlCopyright.InitControl((int)(positionX * m_ZoomRatio), (int)(m_SizeY * m_ZoomRatio) - (int)(24 * m_ZoomRatio), (int)(OFFSET_X * m_ZoomRatio), (int)(24 * m_ZoomRatio), 1.0, &m_BkDC, IP(PROJECT_COPYRIGHT), 1, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
// m_CtrlCopyright.InitControl(positionX, m_SizeY - 24, OFFSET_X, 24, m_ZoomRatio, &m_BkDC, IP(PROJECT_COPYRIGHT), 1, BS_CENTER, OwnerDrawImage, FALSE, FALSE);
}
m_CtrlCopyright.SetHandCursor();
#else
m_CtrlVoice.ShowWindow(SW_HIDE);
m_CtrlVoiceHide.ShowWindow(SW_HIDE);
m_CtrlCopyright.ShowWindow(SW_HIDE);
#endif
int buttonDiskHeight = 48;
if(m_bHighContrast){ buttonDiskHeight = 56;}
for(int i = 0; i < 8; i++)
{
m_ButtonDisk[i].InitControl(84 * i + m_OffsetX, 0, 84, buttonDiskHeight, m_ZoomRatio, &m_BkDC, IP(L"noDisk"), 1, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
m_ButtonDisk[i].SetMargin(0, 0, 3, 0, m_ZoomRatio);
m_ButtonDisk[i].SetHandCursor(TRUE);
}
InitDriveList();
m_CtrlButtonPreDisk.SetHandCursor(TRUE);
m_CtrlButtonNextDisk.SetHandCursor(TRUE);
if (m_bHighContrast)
{
m_CtrlModel.InitControl(40 + m_OffsetX, 56, 592, 32, m_ZoomRatio, &m_BkDC, NULL, 0, ES_CENTER, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlButtonPreDisk.InitControl ( 8 + m_OffsetX, 60, 24, 24, m_ZoomRatio, &m_BkDC, IP(L"preDisk"), 2, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
m_CtrlButtonNextDisk.InitControl(640 + m_OffsetX, 60, 24, 24, m_ZoomRatio, &m_BkDC, IP(L"nextDisk"), 2, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
m_CtrlButtonPreDisk.SetWindowTextW(L"");
m_CtrlButtonNextDisk.SetWindowTextW(L"");
}
else
{
m_CtrlModel.InitControl(32 + m_OffsetX, 52, 608, 32, m_ZoomRatio, &m_BkDC, NULL, 0, ES_CENTER, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlButtonPreDisk.InitControl(8 + m_OffsetX, 56, 24, 24, m_ZoomRatio, &m_BkDC, IP(L"preDisk"), 2, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
m_CtrlButtonNextDisk.InitControl(640 + m_OffsetX, 56, 24, 24, m_ZoomRatio, &m_BkDC, IP(L"nextDisk"), 2, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
m_CtrlButtonPreDisk.SetWindowTextW(L"");
m_CtrlButtonNextDisk.SetWindowTextW(L"");
}
m_CtrlModel.Adjust();
CString className;
if (m_Ata.vars.GetCount())
{
className = GetDiskStatusClass(m_Ata.vars[m_SelectDisk].DiskStatus);
}
else
{
className = L"diskStatusUnknown";
}
int labelWidth = 128;
if (m_bHighContrast) { labelWidth = 124; }
#ifdef SUISHO_SHIZUKU_SUPPORT
m_CtrlLabelDiskStatus.InitControl(128 + m_OffsetX, 260, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelTemperature.InitControl(436 + m_OffsetX, 260, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelDiskStatus.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelTemperature.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlDiskStatus.InitControl (256 + m_OffsetX, 256, 180, 28, m_ZoomRatio, &m_BkDC, IP(className), 1, BS_CENTER, OwnerDrawImage, m_bHighContrast, FALSE, FALSE);
// m_CtrlDiskStatus.SetAlpha(IMAGE_ALPHA);
className.Replace(L"Green", L"");
if (m_Ata.vars.GetCount() && m_Ata.vars[m_SelectDisk].Life == 100)
{
className += L"100";
}
m_CtrlLife.InitControl (m_OffsetX, 88, 128, 192, m_ZoomRatio, &m_BkDC, IP(L"SD" + className), 1, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
m_CtrlLife.SetHandCursor(TRUE);
#else
m_CtrlLife.ShowWindow(SW_HIDE);
m_CtrlLabelDiskStatus.InitControl (8 + m_OffsetX, 88, 100, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_CENTER, OwnerDrawTransparent, FALSE, FALSE, FALSE);
m_CtrlLabelTemperature.InitControl (8 + m_OffsetX, 184, 100, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_CENTER, OwnerDrawTransparent, FALSE, FALSE, FALSE);
m_CtrlLabelDiskStatus.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelTemperature.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlDiskStatus.InitControl (8 + m_OffsetX, 112, 100, 60, m_ZoomRatio, &m_BkDC, IP(className), 1, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
m_CtrlDiskStatus.SetMargin(4, 0, 4, 0, m_ZoomRatio);
#endif
m_CtrlDiskStatus.SetHandCursor(TRUE);
if (m_Ata.vars.GetCount() && (m_Ata.vars[m_SelectDisk].IsSmartCorrect || m_Ata.vars[m_SelectDisk].DiskVendorId == m_Ata.SSD_VENDOR_NVME))
{
className = GetTemperatureClass(m_Ata.vars[m_SelectDisk].Temperature, m_Ata.vars[m_SelectDisk].AlarmTemperature);
}
else
{
className = _T("temperatureUnknown");
}
#ifdef SUISHO_SHIZUKU_SUPPORT
m_CtrlTemperature.InitControl (564 + m_OffsetX, 256, 100, 28, m_ZoomRatio, &m_BkDC, IP(className), 1, BS_CENTER, OwnerDrawImage, m_bHighContrast, FALSE, FALSE);
#else
m_CtrlTemperature.InitControl (8 + m_OffsetX, 208, 100, 40, m_ZoomRatio, &m_BkDC, IP(className), 1, BS_CENTER, OwnerDrawImage, m_bHighContrast, FALSE, FALSE);
#endif
m_CtrlDiskStatus.SetHandCursor(TRUE);
m_CtrlTemperature.SetHandCursor(TRUE);
m_CtrlLabelFirmware.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelSerialNumber.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelInterface.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelTransferMode.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelDriveMap.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelAtaAtapi.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelFeature.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelFirmware.InitControl(128 + m_OffsetX, 88, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelSerialNumber.InitControl(128 + m_OffsetX, 112, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelInterface.InitControl(128 + m_OffsetX, 136, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelTransferMode.InitControl(128 + m_OffsetX, 160, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelDriveMap.InitControl(128 + m_OffsetX, 184, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelAtaAtapi.InitControl(128 + m_OffsetX, 208, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelFeature.InitControl(128 + m_OffsetX, 232, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlFirmware.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlSerialNumber.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlInterface.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlTransferMode.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlDriveMap.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlAtaAtapi.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlFeature.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlFirmware.SetMargin(0, 2, 0, 0, m_ZoomRatio);
m_CtrlSerialNumber.SetMargin(0, 2, 0, 0, m_ZoomRatio);
m_CtrlInterface.SetMargin(0, 2, 0, 0, m_ZoomRatio);
m_CtrlTransferMode.SetMargin(0, 2, 0, 0, m_ZoomRatio);
m_CtrlDriveMap.SetMargin(0, 2, 0, 0, m_ZoomRatio);
m_CtrlAtaAtapi.SetMargin(0, 2, 0, 0, m_ZoomRatio);
m_CtrlFeature.SetMargin(0, 2, 0, 0, m_ZoomRatio);
m_CtrlFirmware.InitControl (256 + m_OffsetX, 88, 180, 20, m_ZoomRatio, &m_BkDC, NULL, 0, ES_LEFT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlSerialNumber.InitControl(256 + m_OffsetX, 112, 180, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_LEFT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlInterface.InitControl (256 + m_OffsetX, 136, 180, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_LEFT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlTransferMode.InitControl(256 + m_OffsetX, 160, 180, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_LEFT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlDriveMap.InitControl (256 + m_OffsetX, 184, 180, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_LEFT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlAtaAtapi.InitControl (256 + m_OffsetX, 208, 408, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_LEFT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlFeature.InitControl (256 + m_OffsetX, 232, 408, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_LEFT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlLabelBufferSize.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelNvCacheSize.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelRotationRate.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelPowerOnCount.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelPowerOnHours.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlLabelBufferSize.InitControl(436 + m_OffsetX, 88, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelNvCacheSize.InitControl(436 + m_OffsetX, 112, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelRotationRate.InitControl(436 + m_OffsetX, 136, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelPowerOnCount.InitControl(436 + m_OffsetX, 160, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlLabelPowerOnHours.InitControl(436 + m_OffsetX, 184, labelWidth, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawTransparent, m_bHighContrast, FALSE, FALSE);
m_CtrlBufferSize.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlNvCacheSize.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlRotationRate.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlPowerOnCount.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlPowerOnHours.SetGlassColor(m_Glass, m_GlassAlpha);
m_CtrlBufferSize.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlNvCacheSize.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlRotationRate.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlPowerOnCount.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlPowerOnHours.SetMargin(0, 0, 0, 4, m_ZoomRatio);
m_CtrlBufferSize.InitControl (564 + m_OffsetX, 88, 100, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlNvCacheSize.InitControl (564 + m_OffsetX, 112, 100, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlRotationRate.InitControl(564 + m_OffsetX, 136, 100, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlPowerOnCount.InitControl(564 + m_OffsetX, 160, 100, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlPowerOnHours.InitControl(564 + m_OffsetX, 184, 100, 20, m_ZoomRatio, &m_BkDC, NULL, 0, SS_RIGHT, OwnerDrawGlass, m_bHighContrast, FALSE, TRUE);
m_CtrlFirmware.SetDrawFrame(TRUE);
m_CtrlSerialNumber.SetDrawFrame(TRUE);
m_CtrlInterface.SetDrawFrame(TRUE);
m_CtrlTransferMode.SetDrawFrame(TRUE);
m_CtrlDriveMap.SetDrawFrame(TRUE);
m_CtrlAtaAtapi.SetDrawFrame(TRUE);
m_CtrlFeature.SetDrawFrame(TRUE);
m_CtrlBufferSize.SetDrawFrame(TRUE);
m_CtrlNvCacheSize.SetDrawFrame(TRUE);
m_CtrlRotationRate.SetDrawFrame(TRUE);
m_CtrlPowerOnCount.SetDrawFrame(TRUE);
m_CtrlPowerOnHours.SetDrawFrame(TRUE);
m_CtrlFirmware.Adjust();
m_CtrlSerialNumber.Adjust();
m_CtrlInterface.Adjust();
m_CtrlTransferMode.Adjust();
m_CtrlDriveMap.Adjust();
m_CtrlAtaAtapi.Adjust();
m_CtrlFeature.Adjust();
m_CtrlBufferSize.Adjust();
m_CtrlNvCacheSize.Adjust();
m_CtrlRotationRate.Adjust();
m_CtrlPowerOnCount.Adjust();
m_CtrlPowerOnHours.Adjust();
CRect rect;
GetClientRect(&rect);
m_List.SetTextColor1(m_ListText1);
m_List.SetTextColor2(m_ListText2);
m_List.SetTextSelected(m_ListTextSelected);
m_List.SetBkColor1(m_ListBk1);
m_List.SetBkColor2(m_ListBk2);
m_List.SetBkSelected(m_ListBkSelected);
m_List.SetLineColor1(m_ListLine1);
m_List.SetLineColor2(m_ListLine2);
m_List.SetGlassColor(m_Glass, m_GlassAlpha);
#ifdef SUISHO_SHIZUKU_SUPPORT
m_List.InitControl(8 + m_OffsetX, SIZE_Y, 672 - 16, (int)(rect.Height() / m_ZoomRatio - SIZE_Y - 8), 672 - 16, 1000 - SIZE_Y - 8, m_ZoomRatio, &m_BkDC, OwnerDrawGlass, m_bHighContrast, FALSE);
#else
m_List.InitControl(8 + m_OffsetX, SIZE_Y, 672 - 16, (int)(rect.Height() / m_ZoomRatio - SIZE_Y - 8), 672 - 16, 1000 - SIZE_Y - 8, m_ZoomRatio, &m_BkDC, SystemDraw, m_bHighContrast, FALSE);
#endif
RebuildListHeader(m_SelectDisk, TRUE);
UpdateListCtrl(m_SelectDisk);
Invalidate();
}
void CDiskInfoDlg::OnSize(UINT nType, int cx, int cy)
{
CMainDialogFx::OnSize(nType, cx, cy);
static BOOL flag = FALSE;
if(flag)
{
#ifdef SUISHO_SHIZUKU_SUPPORT
int positionX = 0;
if (m_CharacterPosition == 0)
{
positionX = 0;
}
else
{
positionX = 1000 - OFFSET_X;
}
m_List.MoveWindow((int)((8 + m_OffsetX) * m_ZoomRatio), (int)(SIZE_Y * m_ZoomRatio), (int)((672 - 16) * m_ZoomRatio), (int)(cy - ((SIZE_Y + 8) * m_ZoomRatio)));
m_CtrlVoice.MoveWindow((int)(positionX * m_ZoomRatio), (int)(48 * m_ZoomRatio), (int)(OFFSET_X * m_ZoomRatio), (int)(cy - ((24 + 48) * m_ZoomRatio)));
// m_CtrlCopyright.MoveWindow(0, (int)(cy - (24 * m_ZoomRatio)), (int)(m_OffsetX * m_ZoomRatio), (int)(24 * m_ZoomRatio));
m_CtrlCopyright.InitControl((int)(positionX * m_ZoomRatio), (int)(cy - (24 * m_ZoomRatio)), (int)(OFFSET_X * m_ZoomRatio), (int)(24 * m_ZoomRatio), 1.0, &m_BkDC, IP(PROJECT_COPYRIGHT), 1, BS_CENTER, OwnerDrawImage, FALSE, FALSE, FALSE);
#else
m_List.MoveWindow((int)((8 + m_OffsetX) * m_ZoomRatio), (int)(SIZE_Y * m_ZoomRatio), (int)((672 - 16) * m_ZoomRatio), (int)(cy - ((SIZE_Y + 8) * m_ZoomRatio)));
#endif
}
flag = TRUE;
if(m_bHideSmartInfo == FALSE && m_bInitializing == FALSE && m_bDpiChanging == FALSE && cy > 0)
{
CString cstr;
m_SizeY = (int)(cy / m_ZoomRatio);
cstr.Format(_T("%d"), m_SizeY);
WritePrivateProfileString(_T("Setting"), _T("Height"), cstr, m_Ini);
}
}
void CDiskInfoDlg::SetClientSize(int sizeX, int sizeY, double zoomRatio)
{
RECT rw, rc;
GetWindowRect(&rw);
GetClientRect(&rc);
if (rc.right != 0)
{
int ncaWidth = (rw.right - rw.left) - (rc.right - rc.left);
int ncaHeight = (rw.bottom - rw.top) - (rc.bottom - rc.top);
m_MinSizeX = (int)(sizeX * zoomRatio) + ncaWidth;
m_MaxSizeX = m_MinSizeX;
m_MinSizeY = (int)(SIZE_MIN_Y * m_ZoomRatio + ncaHeight);
m_MaxSizeY = (int)(SIZE_MAX_Y * m_ZoomRatio + ncaHeight);
SetWindowPos(NULL, 0, 0, (int)(sizeX * zoomRatio) + ncaWidth, (int)(sizeY * zoomRatio) + ncaHeight, SWP_NOMOVE | SWP_NOZORDER);
}
}
void CDiskInfoDlg::SavePos() const
{
WINDOWPLACEMENT place;
place.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(&place);
CString x, y;
x.Format(_T("%d"), place.rcNormalPosition.left);
y.Format(_T("%d"), place.rcNormalPosition.top);
WritePrivateProfileString(_T("Setting"), _T("X"), x, m_Ini);
WritePrivateProfileString(_T("Setting"), _T("Y"), y, m_Ini);
}
void CDiskInfoDlg::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
lpMMI->ptMinTrackSize.x = m_MinSizeX;
lpMMI->ptMinTrackSize.y = m_MinSizeY;
lpMMI->ptMaxTrackSize.x = m_MaxSizeX;
lpMMI->ptMaxTrackSize.y = m_MaxSizeY;
CMainDialogFx::OnGetMinMaxInfo(lpMMI);
}
void CDiskInfoDlg::AlarmHealthStatus(DWORD i, CString dir, CString disk)
{
TCHAR str[256];
CString cstr, alarm, name, title, id;
DWORD niifType = NIIF_INFO;
int pre = -1;
name.Format(_T("(%d) %s / %s / %s\r\n"), i + 1, m_Ata.vars[i].Model, m_Ata.vars[i].SerialNumber, m_Ata.vars[i].DriveMap);
title.Format(_T("(%d) %s / %s / %s"), i + 1, m_Ata.vars[i].Model, m_Ata.vars[i].SerialNumber, m_Ata.vars[i].DriveMap);
GetPrivateProfileString(disk, _T("HealthStatus"), _T("0"), str, 256, dir + _T("\\") + SMART_INI);
pre = _tstoi(str);
if(m_Ata.vars[i].DiskStatus == m_Ata.DISK_STATUS_UNKNOWN)
{
}
else if(m_Ata.vars[i].DiskStatus > (DWORD)pre && m_Ata.vars[i].DiskStatus != m_Ata.DISK_STATUS_GOOD)
{
cstr.Format(_T("%s: [%s] -> [%s]\r\n"), i18n(_T("Dialog"), _T("HEALTH_STATUS")),
GetDiskStatus(pre), GetDiskStatus(m_Ata.vars[i].DiskStatus));
alarm += cstr;
niifType = NIIF_WARNING;
AddEventLog(601, 2, name + cstr);
SendMail(601, title, cstr);
AddAlarmHistory(601, title, cstr);
AlertSound(601, AS_SET_SOUND_ID);
}
else if(m_Ata.vars[i].DiskStatus < (DWORD)pre)
{
cstr.Format(_T("%s: [%s] -> [%s]\r\n"), i18n(_T("Dialog"), _T("HEALTH_STATUS")),
GetDiskStatus(pre), GetDiskStatus(m_Ata.vars[i].DiskStatus));
alarm += cstr;
niifType = NIIF_INFO;
AddEventLog(701, 4, name + cstr);
SendMail(701, title, cstr);
AddAlarmHistory(701, title, cstr);
AlertSound(701, AS_SET_SOUND_ID);
}
GetPrivateProfileString(disk, _T("Life"), _T("-1"), str, 256, dir + _T("\\") + SMART_INI);
pre = _tstoi(str);
if(m_Ata.vars[i].Life == -1 || pre == -1)
{
}
else if(m_Ata.vars[i].Life < pre)
{
cstr.Format(_T("%s: [%d] -> [%d]\r\n"), i18n(_T("SmartSsd"), _T("FF")), pre, m_Ata.vars[i].Life);
alarm += cstr;
niifType = NIIF_WARNING;
AddEventLog(607, 2, name + cstr);
SendMail(607, title, cstr);
AddAlarmHistory(607, title, cstr);
AlertSound(607, AS_SET_SOUND_ID);
}
else if(m_Ata.vars[i].Life > pre)
{
cstr.Format(_T("%s: [%d] -> [%d]\r\n"), i18n(_T("SmartSsd"), _T("FF")), pre, m_Ata.vars[i].Life);
alarm += cstr;
niifType = NIIF_INFO;
AddEventLog(707, 4, name + cstr);
SendMail(707, title, cstr);
AddAlarmHistory(707, title, cstr);
AlertSound(707, AS_SET_SOUND_ID);
}
for(DWORD j = 0; j < m_Ata.vars[i].AttributeCount; j++)
{
if(( m_Ata.vars[i].Attribute[j].Id == 0x05 // Reallocated Sectors Count
|| (m_Ata.vars[i].Attribute[j].Id == 0xC4 && ! m_bWorkaroundIgnoreC4)// Reallocation Event Count
|| m_Ata.vars[i].Attribute[j].Id == 0xC5 // Current Pending Sector Count
|| m_Ata.vars[i].Attribute[j].Id == 0xC6 // Off-Line Scan Uncorrectable Sector Count
) && ! m_Ata.vars[i].IsSsd)
{
CString target;
DWORD eventId = 0;
if(m_Ata.vars[i].Attribute[j].Id == 0x05)
{
target = _T("ReallocatedSectorsCount");
eventId = 602;
}
else if(m_Ata.vars[i].Attribute[j].Id == 0xC4)
{
target = _T("ReallocationEventCount");
eventId = 603;
}
else if(m_Ata.vars[i].Attribute[j].Id == 0xC5)
{
target = _T("CurrentPendingSectorCount");
eventId = 604;
}
else if(m_Ata.vars[i].Attribute[j].Id == 0xC6)
{
target = _T("UncorrectableSectorCount");
eventId = 605;
}
GetPrivateProfileString(disk, target, _T("-1"), str, 256, dir + _T("\\") + SMART_INI);
pre = _tstoi(str);
id.Format(_T("%02X"), m_Ata.vars[i].Attribute[j].Id);
int rawValue = MAKEWORD(m_Ata.vars[i].Attribute[j].RawValue[0], m_Ata.vars[i].Attribute[j].RawValue[1]);
if(rawValue > pre && pre != -1)
{
cstr.Format(_T("%s: (%02X) %s [%d->%d]\r\n"), i18n(_T("Alarm"), _T("DEGRADATION")),
m_Ata.vars[i].Attribute[j].Id, i18n(_T("Smart"), id), pre, rawValue);
alarm += cstr;
niifType = NIIF_WARNING;
AddEventLog(eventId, 2, name + cstr);
SendMail(eventId, title, cstr);
AddAlarmHistory(eventId, title, cstr);
AlertSound(eventId, AS_SET_SOUND_ID);
}
else if(rawValue < pre && pre != -1)
{
cstr.Format(_T("%s: (%02X) %s [%d->%d]\r\n"), i18n(_T("Alarm"), _T("RECOVERY")),
m_Ata.vars[i].Attribute[j].Id, i18n(_T("Smart"), id), pre, rawValue);
alarm += cstr;
niifType = NIIF_INFO;
AddEventLog(eventId + 100, 4, name + cstr);
SendMail(eventId + 100, title, cstr);
AddAlarmHistory(eventId + 100, title, cstr);
AlertSound(eventId + 100, AS_SET_SOUND_ID);
}
}
static CTime preTime[CAtaSmart::MAX_DISK] = {0};
if(m_Ata.vars[i].AlarmTemperature > 0 && m_Ata.vars[i].Temperature >= m_Ata.vars[i].AlarmTemperature)
{
if(CTime::GetTickCount() - preTime[i] > ALARM_TEMPERATURE_PERIOD)
{
if(m_bFahrenheit)
{
cstr.Format(_T("%s: %d F\r\n"), i18n(_T("Alarm"), _T("ALARM_TEMPERATURE")), m_Ata.vars[i].Temperature * 9 / 5 + 32);
}
else
{
cstr.Format(_T("%s: %d C\r\n"), i18n(_T("Alarm"), _T("ALARM_TEMPERATURE")), m_Ata.vars[i].Temperature);
}
AddEventLog(606, 2, name + cstr);
SendMail(606, title, cstr);
AddAlarmHistory(606, title, cstr);
AlertSound(606, AS_SET_SOUND_ID);
niifType = NIIF_WARNING;
preTime[i] = CTime::GetTickCount();
}
}
}
if(! alarm.IsEmpty())
{
cstr.Format(_T("(%d) %s\n"), i + 1, m_Ata.vars[i].Model);
if(niifType == NIIF_WARNING)
{
ShowBalloon(m_MainIconId, niifType, i18n(_T("Alarm"), _T("ALARM_HEALTH_STATUS")), cstr + alarm);
}
else
{
ShowBalloon(m_MainIconId, niifType, i18n(_T("Alarm"), _T("INFO_HEALTH_STATUS")), cstr + alarm);
}
}
}
BOOL CDiskInfoDlg::AddEventLog(DWORD eventId, WORD eventType, CString message)
{
if(! m_bEventLog)
{
return FALSE;
}
return WriteEventLog(eventId, eventType, _T("CrystalDiskInfo"), message);
}
BOOL CDiskInfoDlg::SendMail(DWORD eventId, CString title, CString message)
{
if(! m_bAlertMail || m_AlertMailPath.IsEmpty())
{
return FALSE;
}
TCHAR computer[MAX_COMPUTERNAME_LENGTH + 1];
DWORD length = MAX_COMPUTERNAME_LENGTH + 1;
GetComputerName(computer, &length);
CString subject, body, option;
subject.Format(_T("[CDI] %s %s [%d]"), computer, title, eventId);
body.Format(_T("%s %s\r\n[%d] %s"), computer, title, eventId, message);
option.Format(_T("Subject=\"%s\" Body=\"%s\""), subject, body);
if((INT_PTR)(ShellExecute(NULL, NULL, m_AlertMailPath, option, NULL, SW_SHOW)) > 32)
{
return TRUE;
}
else
{
return FALSE;
}
}
BOOL CDiskInfoDlg::AddAlarmHistory(DWORD eventId, CString disk, CString message)
{
CString cstr;
cstr.Format(L"[Alarm] EventID=%d, Disk=%s, Message=%s", eventId, disk, message);
cstr.Replace(L"\n", L"");
DebugPrint(cstr);
return FALSE;
// 2012/5/26 -
/*
CTime time = CTime::GetTickCount();
CString line;
line.Format(_T("%s,%d,%s,%s"), time.Format(_T("%Y/%m/%d %H:%M:%S")), eventId, disk, message);
line.TrimRight();
line += _T("\n");
CStdioFile outFile;
if(outFile.Open(m_SmartDir + ALARM_HISTORY_CSV,
CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite | CFile::typeText))
{
outFile.SeekToEnd();
outFile.WriteString(line);
outFile.Close();
return TRUE;
}
return FALSE;
*/
}
int ExecAndWait(TCHAR *pszCmd, BOOL bNoWindow)
{
DWORD Code;
BOOL bSuccess;
STARTUPINFO si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
if (bNoWindow) {
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
}
bSuccess = CreateProcess(
NULL, // lpApplicationName
pszCmd, // lpCommandLine
NULL, // lpProcessAttributes
NULL, // lpThreadAttributes
FALSE, // bInheritHandle
0, // dwCreationFlag
NULL, // lpEnvironment
NULL, // lpCurrentDirectory
&si, // lpStartupInfo
&pi // lpProcessInformation
);
if (bSuccess != TRUE) return 0;
WaitForInputIdle(pi.hProcess, INFINITE);
WaitForSingleObject(pi.hProcess, INFINITE);
GetExitCodeProcess(pi.hProcess, &Code);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return Code;
}
BOOL CDiskInfoDlg::AlertSound(DWORD eventId, DWORD mode) const
{
if(mode != AS_SET_SOUND_ID && eventId != 1000 && ! m_bAlertSound)
{
return FALSE;
}
static DWORD soundId = 0;
if(mode == AS_SET_SOUND_ID)
{
if(eventId == 0 || soundId == 0 || soundId > eventId)
{
soundId = eventId;
}
return TRUE;
}
if(soundId == 0)
{
return TRUE;
}
if (600 <= soundId && soundId < 800 && IsFileExist(m_AlertSoundPath))
{
if (mode == AS_DEINIT)
{
return AlertSound(_T(""));
}
// mode == AS_PLAY_SOUND
// Play
if (AlertSound(m_AlertSoundPath) == FALSE)
{
return FALSE;
}
}
else
{
// mode == AS_PLAY_SOUND
HRSRC hrs;
// Choose OPUS resource
CString resource;
HMODULE hModule = nullptr;
#ifdef SUISHO_SHIZUKU_SUPPORT
// For Japanese
if (m_CurrentLang.Find(_T("Japanese")) == 0 || GetUserDefaultLCID() == 0x0411)
{
if (m_hVoice != nullptr)
{
hModule = m_hVoice;
}
else
{
return FALSE;
}
resource.Format(_T("CDI_VOICE_%03d"), soundId);
}
else
{
resource = _T("CDI_SOUND_001");
}
#else
resource = _T("CDI_SOUND_001");
#endif
hrs = FindResource(hModule, resource, _T("OPUS"));
// Resource to TempFile
if (hrs == nullptr)
{
return FALSE;
}
const HGLOBAL hOpus = LoadResource(hModule, hrs);
const LPBYTE lpOpus = static_cast<LPBYTE>(LockResource(hOpus));
DWORD dwWrite = 0;
const HANDLE hFile = CreateFile(m_TempFilePathOpus, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, nullptr);
if (hFile != INVALID_HANDLE_VALUE)
{
if (WriteFile(hFile, lpOpus, SizeofResource(hModule, hrs), &dwWrite, nullptr) == 0)
{
CloseHandle(hFile);
return FALSE;
}
CloseHandle(hFile);
}
// Play
if (AlertSound(m_TempFilePathOpus) == FALSE)
{
return FALSE;
}
}
soundId = 0;
return TRUE;
}
BOOL CDiskInfoDlg::AlertSound(const CString& alertSoundPath) const
{
static MCI_OPEN_PARMS mop = { 0 };
static MCI_PLAY_PARMS mpp = { 0 };
static MCI_GENERIC_PARMS mgp = { 0 };
MCIERROR error = 0;
if (mop.wDeviceID != 0)
{
// Stop and close
error = mciSendCommandW(mop.wDeviceID, MCI_STOP, MCI_WAIT, (DWORD_PTR)&mop);
error = mciSendCommandW(mop.wDeviceID, MCI_CLOSE, MCI_WAIT, (DWORD_PTR)&mop);
mop.wDeviceID = 0;
ZeroMemory(&mop, sizeof(MCI_PLAY_PARMS));
if (error)
{
return FALSE;
}
}
if (alertSoundPath.Right(5).MakeUpper().Compare(_T(".OPUS")) == 0)
{
// Convert Opus to WAV
CString option;
option.Format(_T("\"%s\" \"%s\" \"%s\""), m_OpusDecPath.GetString(), alertSoundPath.GetString(), m_TempFilePathWave.GetString());
ExecAndWait(const_cast<TCHAR*>(option.GetString()), TRUE);
return AlertSound(m_TempFilePathWave);
}
if (alertSoundPath.Compare(_T("")) == 0) {
// mode == AS_DEINIT
// Close
error = mciSendCommandW(mop.wDeviceID, MCI_CLOSE, 0, reinterpret_cast<DWORD_PTR>(&mop));
if (error)
{
return FALSE;
}
return TRUE;
}
// Open
mop.lpstrDeviceType = _T("MPEGVideo");
mop.lpstrElementName = alertSoundPath;
error = mciSendCommandW(NULL, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, reinterpret_cast<DWORD_PTR>(&mop));
if (error)
{
return FALSE;
}
// Set volume
int volume = GetPrivateProfileInt(_T("Setting"), _T("AlertSoundVolume"), 80, m_Ini);
if (volume < 0 || volume > 100) volume = 80;
MCI_DGV_SETAUDIO_PARMS parms = { 0 };
parms.dwItem = MCI_DGV_SETAUDIO_VOLUME;
parms.dwValue = volume * 10; // 0-1000
error = mciSendCommand(mop.wDeviceID, MCI_SETAUDIO, MCI_DGV_SETAUDIO_ITEM | MCI_DGV_SETAUDIO_VALUE, (DWORD_PTR)&parms);
// Seek
error = mciSendCommand(mop.wDeviceID, MCI_SEEK, MCI_SEEK_TO_START, reinterpret_cast<DWORD_PTR>(&mgp));
if (error)
{
return FALSE;
}
// Play
error = mciSendCommandW(mop.wDeviceID, MCI_PLAY, 0, reinterpret_cast<DWORD_PTR>(&mpp));
if (error)
{
return FALSE;
}
return TRUE;
}
void CDiskInfoDlg::AlarmOverheat()
{
CString cstr;
CString overheat;
CString diskStatus;
for(int i = 0; i < m_Ata.vars.GetCount(); i++)
{
if(m_Ata.vars[i].AlarmTemperature > 0 && m_Ata.vars[i].Temperature >= m_Ata.vars[i].AlarmTemperature)
{
diskStatus = GetDiskStatus(m_Ata.vars[i].DiskStatus);
if(m_bFahrenheit)
{
cstr.Format(_T("(%d) %s [%s] %d F\r\n"), i + 1, m_Ata.vars[i].Model, diskStatus, m_Ata.vars[i].Temperature * 9 / 5 + 32);
}
else
{
cstr.Format(_T("(%d) %s [%s] %d C\r\n"), i + 1, m_Ata.vars[i].Model, diskStatus, m_Ata.vars[i].Temperature);
}
overheat += cstr;
}
}
overheat.Trim();
if(! overheat.IsEmpty())
{
ShowBalloon(m_MainIconId, NIIF_WARNING, i18n(_T("Alarm"), _T("ALARM_TEMPERATURE")), overheat);
}
}
void CDiskInfoDlg::OnTimer(UINT_PTR nIDEvent)
{
if(nIDEvent == TIMER_SET_POWER_ON_UNIT)
{
KillTimer(TIMER_SET_POWER_ON_UNIT);
SetWindowTitle(_T(""));
m_NowDetectingUnitPowerOnHours = FALSE;
if(m_Ata.MeasuredTimeUnit())
{
for(int i = 0; i < m_Ata.vars.GetCount(); i++)
{
m_Ata.vars[i].MeasuredPowerOnHours = m_Ata.GetPowerOnHoursEx(i, m_Ata.vars[i].MeasuredTimeUnitType);
CString cstr;
cstr.Format(_T("%d"), m_Ata.vars[i].MeasuredTimeUnitType);
WritePrivateProfileString(_T("PowerOnUnit"), m_Ata.vars[i].ModelSerial, cstr, m_Ini);
SaveSmartInfo(i);
}
AlertSound(0, AS_PLAY_SOUND);
if(m_SelectDisk < (DWORD)m_Ata.vars.GetCount() && m_Ata.vars[m_SelectDisk].IsSmartCorrect && m_Ata.vars[m_SelectDisk].MeasuredPowerOnHours > 0)
{
CString IsMinutesT, title;
if(m_Ata.vars[m_SelectDisk].MeasuredTimeUnitType == CAtaSmart::POWER_ON_MINUTES && m_Ata.vars[m_SelectDisk].IsMaxtorMinute)
{
IsMinutesT = _T(" (?)");
}
else
{
IsMinutesT = _T("");
}
const int years = m_Ata.vars[m_SelectDisk].MeasuredPowerOnHours / (365 * 24);
const int days = (m_Ata.vars[m_SelectDisk].MeasuredPowerOnHours - 365 * 24 * years) / 24;
const int hours = m_Ata.vars[m_SelectDisk].MeasuredPowerOnHours % 24;
if (years > 0)
{
title.Format(_T("%d %s %d %s %d %s%s"),
years, i18n(_T("Dialog"), _T("POWER_ON_YEARS_UNIT")),
days, i18n(_T("Dialog"), _T("POWER_ON_DAYS_UNIT")),
hours, i18n(_T("Dialog"), _T("POWER_ON_HOURS_UNIT")),
IsMinutesT);
}
else
{
title.Format(_T("%d %s %d %s%s"),
days, i18n(_T("Dialog"), _T("POWER_ON_DAYS_UNIT")),
hours, i18n(_T("Dialog"), _T("POWER_ON_HOURS_UNIT")),
IsMinutesT);
}
m_CtrlPowerOnHours.SetToolTipText(title + L" ");
}
else
{
m_CtrlPowerOnHours.SetToolTipText(L"");
}
}
}
else if(nIDEvent == TIMER_AUTO_REFRESH)
{
Refresh(FALSE);
}
else if(nIDEvent == TIMER_FORCE_REFRESH)
{
KillTimer(TIMER_FORCE_REFRESH);
Refresh(FALSE);
AutoAamApmAdaption();
}
else if(nIDEvent == TIMER_AUTO_DETECT)
{
CWaitCursor wait;
BOOL flagChangeDisk = FALSE;
KillTimer(TIMER_AUTO_DETECT);
InitAta(TRUE, m_bAdvancedDiskSearch, &flagChangeDisk, m_bWorkaroundHD204UI, m_bWorkaroundAdataSsd);
if(flagChangeDisk)
{
// Update Menu and Dialog
m_SelectDisk = 0;
m_DriveMenuPage = 0;
ChangeLang(m_CurrentLang);
if(m_bResident)
{
for(int i = 0; i < CAtaSmart::MAX_DISK; i++)
{
RemoveTemperatureIcon(i);
}
CheckTrayTemperatureIcon();
}
if(m_SettingDlg != NULL)
{
::SendMessage(m_SettingDlg->m_hWnd, WM_CLOSE, 0, 0);
}
if(m_HealthDlg != NULL)
{
::SendMessage(m_HealthDlg->m_hWnd, WM_CLOSE, 0, 0);
}
}
else
{
Refresh(TRUE);
}
}
else if(nIDEvent == TIMER_UPDATE_TRAY_ICON)
{
KillTimer(TIMER_UPDATE_TRAY_ICON);
for(int i = 0; i < CAtaSmart::MAX_DISK; i++)
{
RemoveTemperatureIcon(i);
}
CheckTrayTemperatureIcon();
ShowWindow(SW_SHOW);
}
CMainDialogFx::OnTimer(nIDEvent);
}
LRESULT CDiskInfoDlg::OnPowerBroadcast(WPARAM wParam, LPARAM lParam)
{
switch(wParam)
{
case PBT_APMRESUMESUSPEND:
SetTimer(TIMER_FORCE_REFRESH, 5 * 1000, 0);
// MessageBox(_T("PBT_APMRESUMESUSPEND"));
break;
// case PBT_APMSUSPEND:
// MessageBox(_T("PBT_APMSUSPEND"));
// break;
default:
break;
}
return TRUE;
}
LRESULT CDiskInfoDlg::OnQueryEndSession(WPARAM wParam, LPARAM lParam)
{
return TRUE;
}
LRESULT CDiskInfoDlg::OnDeviceChange(WPARAM wParam, LPARAM lParam)
{
if(m_AutoDetectionStatus <= 0)
{
return FALSE;
}
//CString cstr;
switch(wParam)
{
case DBT_DEVICEARRIVAL:
{
//cstr.Format(_T("DBT_DEVICEARRIVAL: LPARAM=%08X\n"), lParam);
PDEV_BROADCAST_HDR pdbh = (PDEV_BROADCAST_HDR)lParam;
switch(pdbh->dbch_devicetype)
{
case DBT_DEVTYP_DEVICEINTERFACE:
{
//cstr += _T("DBT_DEVTYP_DEVICEINTERFACE");
PDEV_BROADCAST_DEVICEINTERFACE pdbd = (PDEV_BROADCAST_DEVICEINTERFACE)lParam;
if(pdbd->dbcc_classguid == StrageGUID)
{
// AfxMessageBox(pdbd->dbcc_name);
// Disabled 2008/11/20 (This feature will be enabled on future release...)
KillTimer(TIMER_AUTO_DETECT);
SetTimer(TIMER_AUTO_DETECT, m_AutoDetectionStatus * 1000, 0);
}
}
break;
case DBT_DEVTYP_HANDLE:
// cstr += _T("DBT_DEVTYP_HANDLE");
break;
case DBT_DEVTYP_OEM:
// cstr += _T("DBT_DEVTYP_OEM");
break;
case DBT_DEVTYP_PORT:
// cstr += _T("DBT_DEVTYP_PORT");
break;
case DBT_DEVTYP_VOLUME:
// cstr += _T("DBT_DEVTYP_VOLUME\n");
// PDEV_BROADCAST_VOLUME pdbv = (PDEV_BROADCAST_VOLUME)lParam;
// CString temp;
// temp.Format(_T("Flags=%d, UnitMask=%08X"), pdbv->dbcv_flags, pdbv->dbcv_unitmask);
// cstr += temp;
break;
}
// AfxMessageBox(cstr);
}
break;
case DBT_DEVICEREMOVECOMPLETE:
{
// cstr.Format(_T("DBT_DEVICEREMOVECOMPLETE: LPARAM=%08X\n"), lParam);
PDEV_BROADCAST_HDR pdbh = (PDEV_BROADCAST_HDR)lParam;
switch(pdbh->dbch_devicetype)
{
case DBT_DEVTYP_DEVICEINTERFACE:
{
// cstr += _T("DBT_DEVTYP_DEVICEINTERFACE");
PDEV_BROADCAST_DEVICEINTERFACE pdbd = (PDEV_BROADCAST_DEVICEINTERFACE)lParam;
if(pdbd->dbcc_classguid == StrageGUID)
{
// AfxMessageBox(pdbd->dbcc_name);
// Disabled 2008/11/20 (This feature will be enabled on future release...)
KillTimer(TIMER_AUTO_DETECT);
SetTimer(TIMER_AUTO_DETECT, m_AutoDetectionStatus * 1000, 0);
}
}
break;
case DBT_DEVTYP_HANDLE:
// cstr += _T("DBT_DEVTYP_HANDLE");
break;
case DBT_DEVTYP_OEM:
// cstr += _T("DBT_DEVTYP_OEM");
break;
case DBT_DEVTYP_PORT:
// cstr += _T("DBT_DEVTYP_PORT");
break;
case DBT_DEVTYP_VOLUME:
// cstr += _T("DBT_DEVTYP_VOLUME\n");
// PDEV_BROADCAST_VOLUME pdbv = (PDEV_BROADCAST_VOLUME)lParam;
// CString temp;
// temp.Format(_T("Flags=%d, UnitMask=%08X"), pdbv->dbcv_flags, pdbv->dbcv_unitmask);
// cstr += temp;
break;
}
// AfxMessageBox(cstr);
}
break;
default:
// cstr.Format(_T("WPARAM=%08X, LPARAM=%08X"), wParam, lParam);
// AfxMessageBox(cstr);
break;
}
return TRUE;
}
void CDiskInfoDlg::AutoAamApmAdaption()
{
if(! m_bAutoAamApm)
{
return ;
}
int status = 0;
int value = 0;
//DEBUG
DebugPrint(_T("AutoAamApmAdaption"));
// AAM
for(int i = 0; i < m_Ata.vars.GetCount(); i++)
{
if(! m_Ata.vars[i].IsAamSupported)
{
continue;
}
status = GetPrivateProfileInt(_T("AamStatus"), m_Ata.vars[i].ModelSerial, -1, m_Ini);
value = GetPrivateProfileInt(_T("AamValue"), m_Ata.vars[i].ModelSerial, -1, m_Ini);
if(status == 1 /* Enabled */ && value != -1)
{
m_Ata.EnableAam(i, value);
m_Ata.UpdateIdInfo(i);
DebugPrint(_T("m_Ata.EnableAam"));
}
else if(status == 0 /* Disabled */ )
{
m_Ata.DisableAam(i);
m_Ata.UpdateIdInfo(i);
DebugPrint(_T("m_Ata.DisableAam"));
}
}
// APM
for(int i = 0; i < m_Ata.vars.GetCount(); i++)
{
if(! m_Ata.vars[i].IsApmSupported)
{
continue;
}
status = GetPrivateProfileInt(_T("ApmStatus"), m_Ata.vars[i].ModelSerial, -1, m_Ini);
value = GetPrivateProfileInt(_T("ApmValue"), m_Ata.vars[i].ModelSerial, -1, m_Ini);
if(status == 1 /* Enabled */ && value != -1)
{
m_Ata.EnableApm(i, value);
m_Ata.UpdateIdInfo(i);
DebugPrint(_T("m_Ata.EnableApm"));
}
else if(status == 0 /* Disabled */ )
{
m_Ata.DisableApm(i);
m_Ata.UpdateIdInfo(i);
DebugPrint(_T("m_Ata.DisableApm"));
}
}
}
void CDiskInfoDlg::ReExecute()
{
// Added 2013/04/12 - Workaround for Exec Failed
WritePrivateProfileString(_T("Workaround"), _T("ExecFailed"), _T("0"), m_Ini);
ShowWindow(SW_HIDE);
RemoveTrayMainIcon();
for(int i = 0; i < m_Ata.vars.GetCount(); i++)
{
RemoveTemperatureIcon(i);
}
KillGraphDlg();
EndDialog(RE_EXEC);
}
DWORD CDiskInfoDlg::GetSelectDisk()
{
return m_SelectDisk;
}
void CDiskInfoDlg::OnBnClickedButtonDisk0(){SelectDrive(0 + m_DriveMenuPage * 8);}
void CDiskInfoDlg::OnBnClickedButtonDisk1(){SelectDrive(1 + m_DriveMenuPage * 8);}
void CDiskInfoDlg::OnBnClickedButtonDisk2(){SelectDrive(2 + m_DriveMenuPage * 8);}
void CDiskInfoDlg::OnBnClickedButtonDisk3(){SelectDrive(3 + m_DriveMenuPage * 8);}
void CDiskInfoDlg::OnBnClickedButtonDisk4(){SelectDrive(4 + m_DriveMenuPage * 8);}
void CDiskInfoDlg::OnBnClickedButtonDisk5(){SelectDrive(5 + m_DriveMenuPage * 8);}
void CDiskInfoDlg::OnBnClickedButtonDisk6(){SelectDrive(6 + m_DriveMenuPage * 8);}
void CDiskInfoDlg::OnBnClickedButtonDisk7(){SelectDrive(7 + m_DriveMenuPage * 8);}
void CDiskInfoDlg::SetControlFont()
{
#ifdef SUISHO_SHIZUKU_SUPPORT
BYTE textAlpha = TEXT_ALPHA;
// COLORREF textColor = RGB(77, 77, 77);
COLORREF textColor = m_LabelText;
#else
BYTE textAlpha = 255;
COLORREF textColor = m_LabelText;
#endif
m_List.SetFontEx(m_FontFace, 12, m_ZoomRatio, m_FontRatio, FW_NORMAL, m_FontRender);
for(int i = 0; i < 8; i++)
{
m_ButtonDisk[i].SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
}
if (m_bHighContrast)
{
m_CtrlModel.SetFontEx(m_FontFace, 20, 20, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
}
else
{
m_CtrlModel.SetFontEx(m_FontFace, 24, 24, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
}
m_CtrlButtonPreDisk.SetFontEx(m_FontFace, 24, 24, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlButtonNextDisk.SetFontEx(m_FontFace, 24, 24, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelFirmware.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio,m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelSerialNumber.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelInterface.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelTransferMode.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelDriveMap.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelBufferSize.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelNvCacheSize.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelRotationRate.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelPowerOnCount.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelPowerOnHours.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelAtaAtapi.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelFeature.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelDiskStatus.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlLabelTemperature.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlFirmware.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlSerialNumber.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlInterface.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlTransferMode.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlDriveMap.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlBufferSize.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlNvCacheSize.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlRotationRate.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlPowerOnCount.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlPowerOnHours.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlAtaAtapi.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
m_CtrlFeature.SetFontEx(m_FontFace, 12, 12, m_ZoomRatio, m_FontRatio, m_LabelText, FW_NORMAL, m_FontRender);
#ifdef SUISHO_SHIZUKU_SUPPORT
m_CtrlDiskStatus.SetFontEx(m_FontFace, 16, 16, m_ZoomRatio, m_FontRatio, m_ButtonText, FW_BOLD, m_FontRender);
m_CtrlTemperature.SetFontEx(m_FontFace, 18, 18, m_ZoomRatio, m_FontRatio, m_ButtonText, FW_BOLD, m_FontRender);
m_CtrlLife.SetFontEx(m_FontFace, 18, 18, m_ZoomRatio, m_FontRatio, m_ButtonText, FW_NORMAL, m_FontRender);
#else
m_CtrlDiskStatus.SetFontEx(m_FontFace, 18, 18, m_ZoomRatio, m_FontRatio, m_ButtonText, FW_BOLD, m_FontRender);
m_CtrlTemperature.SetFontEx(m_FontFace, 20, 20, m_ZoomRatio, m_FontRatio, m_ButtonText, FW_BOLD, m_FontRender);
#endif
}
void CDiskInfoDlg::OnBnClickedButtonPreDisk()
{
SelectDrive(m_SelectDisk - 1);
}
void CDiskInfoDlg::OnBnClickedButtonNextDisk()
{
SelectDrive(m_SelectDisk + 1);
}
void CDiskInfoDlg::OnBnClickedButtonHealthStatus()
{
CMenu *menu = GetMenu();
if(! (menu->GetMenuState(ID_HEALTH_STATUS, MF_BYCOMMAND) & MF_GRAYED))
{
m_HealthDlg = new CHealthDlg(this);
m_HealthDlg->Create(CHealthDlg::IDD, m_HealthDlg, ID_HEALTH_STATUS, this);
}
}
void CDiskInfoDlg::OnBnClickedButtonTemperature()
{
CMenu* menu = GetMenu();
if (!(menu->GetMenuState(ID_TEMPERATURE, MF_BYCOMMAND) & MF_GRAYED))
{
m_TemperatureDlg = new CTemperatureDlg(this);
m_TemperatureDlg->Create(CTemperatureDlg::IDD, m_TemperatureDlg, ID_TEMPERATURE, this);
}
}
void CDiskInfoDlg::OnBnClickedButtonVoice()
{
#ifdef SUISHO_SHIZUKU_SUPPORT
DWORD id;
if(GetTickCountFx() % 2)
{
id = 7;
}
else
{
id = 8;
}
AlertSound(id, AS_SET_SOUND_ID);
AlertSound(1000, AS_PLAY_SOUND);
#endif
}
void CDiskInfoDlg::OnBnClickedButtonCopyright()
{
#ifdef SUISHO_SHIZUKU_SUPPORT
/*
if (m_CurrentLang.Find(L"Japanese") == 0)
{
SYSTEMTIME systime;
GetLocalTime(&systime);
if ((systime.wYear == 2015 && systime.wMonth == 12 && systime.wDay <= 17)
|| (systime.wYear == 2015 && systime.wMonth == 12 && systime.wDay == 18 && systime.wHour < 20))
{
OpenUrl(L"http://akiba-pc.watch.impress.co.jp/docs/sp/20151207_733688.html");
}
}
*/
#ifdef KUREI_KEI_SUPPORT
CString url;
url.Format(L"http://pronama.jp/crystaldiskinfo_themes/?%s", m_CurrentTheme);
OpenUrl(url);
#else
UINT themeIndex = rand() % (UINT)m_MenuArrayTheme.GetSize();
SendMessage(WM_COMMAND, WM_THEME_ID + themeIndex);
#endif
#endif
}
void CDiskInfoDlg::OnBnClickedButtonLife()
{
#ifdef SUISHO_SHIZUKU_SUPPORT
DWORD id;
if (m_Ata.vars.GetCount() > 0)
{
switch(m_Ata.vars[m_SelectDisk].DiskStatus)
{
case CAtaSmart::DISK_STATUS_GOOD:
if(m_Ata.vars[m_SelectDisk].Life == 100)
{
id = 2;
}
else
{
id = 3;
}
break;
case CAtaSmart::DISK_STATUS_CAUTION:
id = 4;
break;
case CAtaSmart::DISK_STATUS_BAD:
id = 5;
break;
case CAtaSmart::DISK_STATUS_UNKNOWN:
default:
id = 6;
break;
}
}
else
{
id = 6;
}
AlertSound(id, AS_SET_SOUND_ID);
AlertSound(1000, AS_PLAY_SOUND);
#endif
}
void CDiskInfoDlg::SetLabel(CStaticFx& ctrl, CString& label, CString title)
{
ctrl.SetToolTipText(title);
label = title;
}
void CDiskInfoDlg::OnShowWindow(BOOL bShow, UINT nStatus)
{
CMainDialogFx::OnShowWindow(bShow, nStatus);
}
void CDiskInfoDlg::ShowWindowEx(int nCmdShow)
{
m_bShowWindow = TRUE;
ShowWindow(nCmdShow);
SetForegroundWindow();
}
BOOL CDiskInfoDlg::CheckThemeEdition(CString name)
{
#ifdef SUISHO_SHIZUKU_SUPPORT
#ifdef KUREI_KEI_SUPPORT
if (name.Find(L"KureiKei") == 0) { return TRUE; }
#else
if (name.Find(L"Shizuku") == 0) { return TRUE; }
#endif
#else
if (name.Find(L"Shizuku") != 0 && name.Find(L"KureiKei") != 0 && name.Find(L".") != 0) { return TRUE; }
#endif
return FALSE;
}
| 33.988551 | 262 | 0.737284 | [
"model"
] |
a3273eb3e9b4639d4718ab19b16ea5a29ac849e3 | 8,710 | hpp | C++ | src/tdi_utils.hpp | satish153/tdi | bcd09bdcc624de103e54531e618dd152e6a67387 | [
"Apache-2.0"
] | 15 | 2021-11-02T22:04:49.000Z | 2022-03-29T06:51:26.000Z | src/tdi_utils.hpp | satish153/tdi | bcd09bdcc624de103e54531e618dd152e6a67387 | [
"Apache-2.0"
] | 16 | 2021-10-15T17:14:55.000Z | 2022-02-25T01:24:35.000Z | src/tdi_utils.hpp | satish153/tdi | bcd09bdcc624de103e54531e618dd152e6a67387 | [
"Apache-2.0"
] | 6 | 2021-12-15T15:46:06.000Z | 2022-02-18T05:23:42.000Z | /*
* Copyright(c) 2021 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this software except as stipulated in the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _TDI_UTILS_HPP
#define _TDI_UTILS_HPP
#include <queue>
#include <mutex>
#include <future>
#include <thread>
#include <condition_variable>
#include <functional>
#include <cstring>
#include <target-sys/bf_sal/bf_sys_intf.h>
#define LOG_CRIT(...) LOG_COMMON(BF_LOG_CRIT, __VA_ARGS__)
#define LOG_ERROR(...) LOG_COMMON(BF_LOG_ERR, __VA_ARGS__)
#define LOG_WARN(...) LOG_COMMON(BF_LOG_WARN, __VA_ARGS__)
#define LOG_TRACE(...) LOG_COMMON(BF_LOG_INFO, __VA_ARGS__)
#define LOG_DBG(...) LOG_COMMON(BF_LOG_DBG, __VA_ARGS__)
#define LOG_COMMON(LOG_LEVEL, ...) \
do { \
if (bf_sys_log_is_log_enabled(BF_MOD_BFRT, LOG_LEVEL) == 1) { \
bf_sys_log_and_trace(BF_MOD_BFRT, LOG_LEVEL, __VA_ARGS__); \
} \
} while (0);
#define TDI_ASSERT bf_sys_assert
#define TDI_DBGCHK bf_sys_dbgchk
namespace tdi {
// This is a class to initialize a generalized thread pool with a specific
// number of worker threads given at time of creation of the thread pool.
// The thread pool uses a thread safe queue to manage the producer-consumer
// pipeline. This thread safe queue is just a wrapper on std::queue<T>.
// The queue is templatized over std::function<void()> and thus holds function
// objects. It is the job of the submitTask function to package the function F
// and the variadic arguments that are passed to it by the user into a
// std::function<void()> function object and enqueue it in the queue.
// Any producer can first create the thread pool and then use the submitTask
// function to submit tasks which will be enqueued in the queue. The worker
// thread/threads are waiting for any tasks to appear in the queue and pick
// them up as soon as the tasks are enqueued. During the destruction of the
// thread pool, the "shutdown_" flag is set which indicates to the worker
// threads that they need to stop processing the tasks in the queue and return.
// These worker threads are then subsequently joined.
// The implementation of this thread pool is inspired from the following.
// https://github.com/mtrebi/thread-pool
class TdiThreadPool {
private:
// Wrapper class over std::queue to make it thread safe
template <typename T>
class ThreadSafeQueue {
public:
ThreadSafeQueue(){};
void enqueue(T &t) {
std::lock_guard<std::mutex> lg(mtx_);
queue_.push(t);
}
bool dequeue(T *t) {
std::lock_guard<std::mutex> lg(mtx_);
if (queue_.empty()) {
return false;
}
*t = queue_.front();
queue_.pop();
return true;
}
bool empty() const {
std::lock_guard<std::mutex> lg(mtx_);
return queue_.empty();
}
size_t size() const {
std::lock_guard<std::mutex> lg(mtx_);
return queue_.size();
}
private:
std::queue<T> queue_;
// Lock to protect against concurrent accesses to std::queue
mutable std::mutex mtx_;
}; // ThreadSafeQueue
// Functor which will be executed by each worker thread
class WorkerThread {
public:
WorkerThread(const int &id, TdiThreadPool *thread_pool)
: id_(id), thread_pool_(thread_pool) {}
void operator()() {
// continue processing tasks from the queue until the thread pool is
// shutdown
while (!thread_pool_->shutdown_) {
bool is_dequeued = false;
std::function<void()> fn;
{
std::unique_lock<std::mutex> lock(thread_pool_->mtx_);
if (thread_pool_->queue_.empty()) {
// Wait until there is work to be performed
thread_pool_->cond_var_.wait(lock);
}
}
// Get a task from the queue
is_dequeued = thread_pool_->queue_.dequeue(&fn);
if (is_dequeued) {
// Perform the task
fn();
}
}
}
private:
const int id_{0};
TdiThreadPool *thread_pool_{nullptr};
}; // WorkerThread
std::vector<std::thread> threads_; // Vector to keep track of threads
bool shutdown_{false}; // Flag to shutdown the pool
ThreadSafeQueue<std::function<void()>> queue_;
// We use condition variable so that the worker threads can be signalled
// whenever there are tasks to be performed in the queue and thus they
// don't need to spin on the queue waiting for tasks to show up
std::mutex mtx_;
std::condition_variable cond_var_;
public:
TdiThreadPool(const size_t &num_threads = 1)
: threads_(std::vector<std::thread>(num_threads)) {
for (size_t i = 0; i < threads_.size(); i++) {
threads_[i] = std::thread(WorkerThread(i, this));
}
}
~TdiThreadPool() {
// Stop processing any more tasks
shutdown_ = true;
// Wake up all threads so that break from their respective while loops
// and return
cond_var_.notify_all();
for (size_t i = 0; i < threads_.size(); i++) {
if (threads_[i].joinable()) {
// Wait for the thread to finish
threads_[i].join();
}
}
}
size_t getQueueSize() { return queue_.size(); }
// This function is responsible for packaging the function 'F' and the
// variadic arguments 'args' that are passed to it into a generic
// function object 'std::function<void()>' and enqueue it in the queue.
// These packaged function objects will subsquently be processed by the
// worker threads
template <typename F, typename... Args>
auto submitTask(F &&f, Args &&... args) -> std::future<decltype(f(args...))> {
// Construct a function object
std::function<decltype(f(args...))()> fn_obj =
std::bind(std::forward<F>(f), std::forward<Args>(args)...);
// Make a packaged task. We need a task object so that we retrieve the
// result once the worker thread has finished execution
auto task_ptr =
std::make_shared<std::packaged_task<decltype(f(args...))()>>(fn_obj);
// Construct a generic void function
std::function<void()> fn_wrapper = [task_ptr]() { (*task_ptr)(); };
// Enqueue the generic void function
queue_.enqueue(fn_wrapper);
// Wake up any one thread waiting
cond_var_.notify_one();
// Return the future for the packaged_task shared state
return task_ptr->get_future();
}
// Delete the copy constructor and the assignment operator
TdiThreadPool(const TdiThreadPool &) = delete;
TdiThreadPool(TdiThreadPool &&) = delete;
TdiThreadPool &operator=(const TdiThreadPool &) = delete;
TdiThreadPool &operator=(TdiThreadPool &&) = delete;
}; // TdiThreadPool
class TdiEndiannessHandler {
public:
TdiEndiannessHandler() = delete;
static void toHostOrder(const size_t &size,
const uint8_t *value_ptr,
uint64_t *out_data) {
uint64_t local_value = 0;
uint8_t *dst = reinterpret_cast<uint8_t *>(&local_value);
if (size > 8) {
LOG_ERROR(
"ERROR: %s:%d Trying to convert a network order byte stream of more "
"than 8 bytes (%zu) into 64 bit data",
__func__,
__LINE__,
size);
TDI_DBGCHK(0);
return;
}
local_value = 0;
// Before memcpy, move the dst pointer offset deep enough
dst += (8 - size);
std::memcpy(dst, value_ptr, size);
local_value = be64toh(local_value);
*out_data = local_value;
}
static void toNetworkOrder(const size_t &size,
const uint64_t &in_data,
uint8_t *value_ptr) {
if (size > 8) {
LOG_ERROR(
"ERROR: %s:%d Trying to convert a 64 bit data into a network order "
"byte stream of more than 8 bytes (%zu)",
__func__,
__LINE__,
size);
TDI_DBGCHK(0);
return;
}
auto local_val = in_data;
local_val = htobe64(local_val);
uint8_t *src = reinterpret_cast<uint8_t *>(&local_val);
// Before memcpy, move the src pointer offset deep enough
src += (8 - size);
std::memcpy(value_ptr, src, size);
}
};
} // namespace tdi
#endif // _TDI_UTILS_HPP
| 33.891051 | 80 | 0.646728 | [
"object",
"vector"
] |
a3292bd97f5fef701a82672e7990d2a4b9d0b972 | 1,317 | cpp | C++ | peg/ccc/2000/stage-1/golf.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | peg/ccc/2000/stage-1/golf.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | peg/ccc/2000/stage-1/golf.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
constexpr unsigned int max_strokes {6000};
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
unsigned int min_strokes(unsigned int to_hole,
const vector<unsigned int>& distances)
{
vector<unsigned int> strokes(to_hole + 1, max_strokes);
strokes[0] = 0;
for (unsigned int i {0}; i < to_hole; ++i)
{
for (auto distance : distances)
{
if (i + distance <= to_hole)
{
strokes[i + distance] = min(strokes[i + distance],
strokes[i] + 1);
}
}
}
return strokes[to_hole];
}
int main()
{
use_io_optimizations();
unsigned int to_hole;
cin >> to_hole;
unsigned int clubs;
cin >> clubs;
vector<unsigned int> distances(clubs);
for (auto& distance : distances)
{
cin >> distance;
}
unsigned int strokes_to_hole {min_strokes(to_hole, distances)};
if (strokes_to_hole == max_strokes)
{
cout << "Roberta acknowledges defeat.";
}
else
{
cout << "Roberta wins in " << strokes_to_hole << " strokes.";
}
cout << '\n';
return 0;
}
| 18.814286 | 69 | 0.555049 | [
"vector"
] |
a32a426aae02c705433a2ed72d250e743fd79266 | 6,238 | cpp | C++ | teleop_and_haptics/sss/Source/MySliceGLWidget.cpp | atp42/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | 3 | 2017-02-02T13:27:45.000Z | 2018-06-17T11:52:13.000Z | teleop_and_haptics/sss/Source/MySliceGLWidget.cpp | salisbury-robotics/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | null | null | null | teleop_and_haptics/sss/Source/MySliceGLWidget.cpp | salisbury-robotics/jks-ros-pkg | 367fc00f2a9699f33d05c7957d319a80337f1ed4 | [
"FTL"
] | null | null | null | #include "MySliceGLWidget.h"
#include <QtGui>
#include <algorithm>
#include <cmath>
using namespace std;
// --------------------------------------------------------------------------
MySliceGLWidget::MySliceGLWidget(const QGLFormat &format, QWidget *parent,
const QGLWidget *shareWidget, Qt::WindowFlags f)
: QGLWidget(format, parent, shareWidget, f)
{
m_initialized = false;
m_minRange = 0;
m_maxRange = 0xff;
m_zoom = 1.f;
m_centerX = 0.f;
m_centerY = 0.f;
}
// --------------------------------------------------------------------------
GLuint MySliceGLWidget::allocateTexture()
{
GLuint texture;
// create a 2D texture for storing the image
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
return texture;
}
// --------------------------------------------------------------------------
void MySliceGLWidget::initializeGL()
{
// allocate a single texture first
m_imageTextures.push_back(allocateTexture());
m_imageValid.push_back(false);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
unsigned char data[256];
for (int i = 0; i < 256; ++i) data[i] = i;
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, 8, 32, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
m_initialized = true;
}
// --------------------------------------------------------------------------
void MySliceGLWidget::paintGL()
{
glClearColor(.2f, .2f, .2f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// enable blending so that images can be overlayed
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// iterate through and paint our list of images in order
glEnable(GL_TEXTURE_2D);
for (int i = 0; i < m_imageTextures.size(); ++i)
{
// don't draw invalid images
if (m_imageValid[i] == false) continue;
glBindTexture(GL_TEXTURE_2D, m_imageTextures[i]);
// bind the optional shader before draw
bindShader(i);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glScalef(m_zoom, m_zoom, m_zoom);
glTranslatef(m_centerX, m_centerY, 0.f);
glColor3f(1.f, 1.f, 1.f);
glBegin(GL_QUADS);
glTexCoord2f(0.f, 1.f); glVertex2f(-1.f, -1.f);
glTexCoord2f(1.f, 1.f); glVertex2f( 1.f, -1.f);
glTexCoord2f(1.f, 0.f); glVertex2f( 1.f, 1.f);
glTexCoord2f(0.f, 0.f); glVertex2f(-1.f, 1.f);
glEnd();
// unbind the optional shader after draw
releaseShader(i);
}
}
// --------------------------------------------------------------------------
void MySliceGLWidget::resizeGL(int width, int height)
{
glViewport(0, 0, GLsizei(width), GLsizei(height));
double aspectw = float(width) / float(height);
double aspecth = float(height) / float(width);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (aspectw > aspecth)
glOrtho(-aspectw, aspectw, -1.0, 1.0, -1.0, 1.0);
else
glOrtho(-1.0, 1.0, -aspecth, aspecth, -1.0, 1.0);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// --------------------------------------------------------------------------
void MySliceGLWidget::mousePressEvent(QMouseEvent *event)
{
m_mouseX = event->x();
m_mouseY = event->y();
event->accept();
}
void MySliceGLWidget::mouseMoveEvent(QMouseEvent *event)
{
int dx = event->x() - m_mouseX;
int dy = event->y() - m_mouseY;
// update translation
float size = min(width(), height());
m_centerX += dx * 2.f / size / m_zoom;
m_centerY -= dy * 2.f / size / m_zoom;
updateGL();
// update stored mouse position
m_mouseX = event->x();
m_mouseY = event->y();
event->accept();
}
void MySliceGLWidget::wheelEvent(QWheelEvent *event)
{
float dz = float(event->delta()) / 2880.f;
m_zoom = m_zoom * exp(dz);
m_zoom = min(max(0.25f, m_zoom), 25.f);
updateGL();
}
// --------------------------------------------------------------------------
void MySliceGLWidget::updateImage(int width, int height, GLenum format,
GLenum type, const void *data, int index)
{
if (!m_initialized || data == 0) return;
// remember the input data type's range to compute window in [0,1] range
if (index == 0)
{
switch (type) {
case GL_BYTE: m_minRange = -0x80; m_maxRange = 0x7f; break;
case GL_UNSIGNED_BYTE: m_minRange = 0; m_maxRange = 0xff; break;
case GL_SHORT: m_minRange = -0x8000; m_maxRange = 0x7fff; break;
case GL_UNSIGNED_SHORT: m_minRange = 0; m_maxRange = 0xffff; break;
}
}
// update the texture and re-render the image
makeCurrent();
// if the index is beyond what we have, allocate more images
while (index >= m_imageTextures.size()) {
m_imageTextures.push_back(allocateTexture());
m_imageValid.push_back(false);
}
// store the updated image data
glPushAttrib(GL_PIXEL_MODE_BIT);
if (type == GL_BYTE || type == GL_SHORT) {
glPixelTransferf(GL_RED_SCALE, 0.5f);
glPixelTransferf(GL_RED_BIAS, 0.5f);
}
glBindTexture(GL_TEXTURE_2D, m_imageTextures[index]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, width, height, 0,
format, type, data);
glPopAttrib();
m_imageValid[index] = true;
updateGL();
}
// --------------------------------------------------------------------------
void MySliceGLWidget::invalidateImage(int index)
{
// if the index is beyond what we have, allocate more images
while (index >= m_imageValid.size())
m_imageValid.push_back(false);
m_imageValid[index] = false;
}
// --------------------------------------------------------------------------
| 28.614679 | 86 | 0.558192 | [
"render"
] |
a32d01c1fbed25052cb1c63cbc04cde9f4c66da7 | 4,011 | hpp | C++ | external/source/exploits/CVE-2017-13861/liboffsetfinder64/insn.hpp | OsmanDere/metasploit-framework | b7a014a5d22d3b57157e301d4af57e3a31ad03a9 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 26,932 | 2015-01-01T00:04:51.000Z | 2022-03-31T22:51:38.000Z | external/source/exploits/CVE-2017-13861/liboffsetfinder64/insn.hpp | Kilo-411/metasploit-framework | aaf27d7fa51390895dea63c58cb3b76e959d36f8 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 11,048 | 2015-01-01T00:05:44.000Z | 2022-03-31T21:49:52.000Z | external/source/exploits/CVE-2017-13861/liboffsetfinder64/insn.hpp | Kilo-411/metasploit-framework | aaf27d7fa51390895dea63c58cb3b76e959d36f8 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 12,593 | 2015-01-01T01:01:20.000Z | 2022-03-31T22:13:32.000Z | //
// insn.hpp
// liboffsetfinder64
//
// Created by tihmstar on 09.03.18.
// Copyright © 2018 tihmstar. All rights reserved.
//
#ifndef insn_hpp
#define insn_hpp
#include "common.h"
#include <vector>
namespace tihmstar{
namespace patchfinder64{
class insn{
public:
enum segtype{
kText_only,
kData_only,
kText_and_Data
};
private:
std::pair <loc_t,int> _p;
std::vector<text_t> _segments;
segtype _segtype;
public:
insn(segment_t segments, loc_t p = 0, segtype segType = kText_only);
insn(const insn &cpy, loc_t p=0);
insn &operator++();
insn &operator--();
insn operator+(int i);
insn operator-(int i);
insn &operator+=(int i);
insn &operator-=(int i);
insn &operator=(loc_t p);
public: //helpers
uint64_t pc();
uint32_t value();
uint64_t doublevalue();
public: //static type determinition
static uint64_t deref(segment_t segments, loc_t p);
static bool is_adrp(uint32_t i);
static bool is_adr(uint32_t i);
static bool is_add(uint32_t i);
static bool is_bl(uint32_t i);
static bool is_cbz(uint32_t i);
static bool is_ret(uint32_t i);
static bool is_tbnz(uint32_t i);
static bool is_br(uint32_t i);
static bool is_ldr(uint32_t i);
static bool is_cbnz(uint32_t i);
static bool is_movk(uint32_t i);
static bool is_orr(uint32_t i);
static bool is_and(uint32_t i);
static bool is_tbz(uint32_t i);
static bool is_ldxr(uint32_t i);
static bool is_ldrb(uint32_t i);
static bool is_str(uint32_t i);
static bool is_stp(uint32_t i);
static bool is_movz(uint32_t i);
static bool is_bcond(uint32_t i);
static bool is_b(uint32_t i);
static bool is_nop(uint32_t i);
public: //type
enum type{
unknown,
adrp,
adr,
bl,
cbz,
ret,
tbnz,
add,
br,
ldr,
cbnz,
movk,
orr,
tbz,
ldxr,
ldrb,
str,
stp,
movz,
bcond,
b,
nop,
and_
};
enum subtype{
st_general,
st_register,
st_immediate,
st_literal
};
enum supertype{
sut_general,
sut_branch_imm
};
enum cond{
NE = 000,
EG = 000,
CS = 001,
CC = 001,
MI = 010,
PL = 010,
VS = 011,
VC = 011,
HI = 100,
LS = 100,
GE = 101,
LT = 101,
GT = 110,
LE = 110,
AL = 111
};
type type();
subtype subtype();
supertype supertype();
int64_t imm();
uint8_t rd();
uint8_t rn();
uint8_t rt();
uint8_t other();
public: //cast operators
operator void*();
operator loc_t();
operator enum type();
};
loc_t find_literal_ref(segment_t segemts, loc_t pos, int ignoreTimes = 0);
loc_t find_rel_branch_source(insn bdst, bool searchUp, int ignoreTimes=0, int limit = 0);
};
};
#endif /* insn_hpp */
| 27.854167 | 97 | 0.433059 | [
"vector"
] |
cd12bd346187064419f4b9b86e4d39d11eb93f3a | 581 | hpp | C++ | maistra/vendor/com_github_alibaba_hessian2_codec/hessian2/basic_codec/map_codec.hpp | Maistra/proxy | 96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f | [
"Apache-2.0"
] | 23 | 2020-12-24T08:10:24.000Z | 2021-12-27T04:52:59.000Z | hessian2/basic_codec/map_codec.hpp | wbpcode/hessian2-codec | dd8e05487a27b367b90ce81f4e6e6f62d693a212 | [
"Apache-2.0"
] | 15 | 2020-12-28T08:25:19.000Z | 2021-12-27T04:03:14.000Z | maistra/vendor/com_github_alibaba_hessian2_codec/hessian2/basic_codec/map_codec.hpp | Maistra/proxy | 96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f | [
"Apache-2.0"
] | 7 | 2019-07-04T14:23:54.000Z | 2020-04-27T08:52:51.000Z | #pragma once
#include "hessian2/codec.hpp"
#include "hessian2/object.hpp"
#include "hessian2/basic_codec/object_codec.hpp"
#include "hessian2/basic_codec/number_codec.hpp"
#include "hessian2/basic_codec/string_codec.hpp"
#include "hessian2/basic_codec/type_ref_codec.hpp"
namespace Hessian2 {
template <>
std::unique_ptr<TypedMapObject> Decoder::decode();
template <>
std::unique_ptr<UntypedMapObject> Decoder::decode();
template <>
bool Encoder::encode(const TypedMapObject& value);
template <>
bool Encoder::encode(const UntypedMapObject& value);
} // namespace Hessian2
| 23.24 | 52 | 0.783133 | [
"object"
] |
cd135578d9491be0a285014088a1865bf614e9aa | 14,909 | hpp | C++ | src/mlpack/methods/lsh/lsh_search_impl.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/lsh/lsh_search_impl.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/lsh/lsh_search_impl.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file lsh_search_impl.hpp
* @author Parikshit Ram
*
* Implementation of the LSHSearch class.
*/
#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_LSH_SEARCH_IMPL_HPP
#define __MLPACK_METHODS_NEIGHBOR_SEARCH_LSH_SEARCH_IMPL_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace neighbor {
// Construct the object.
template<typename SortPolicy>
LSHSearch<SortPolicy>::
LSHSearch(const arma::mat& referenceSet,
const arma::mat& querySet,
const size_t numProj,
const size_t numTables,
const double hashWidthIn,
const size_t secondHashSize,
const size_t bucketSize) :
referenceSet(referenceSet),
querySet(querySet),
numProj(numProj),
numTables(numTables),
hashWidth(hashWidthIn),
secondHashSize(secondHashSize),
bucketSize(bucketSize),
distanceEvaluations(0)
{
if (hashWidth == 0.0) // The user has not provided any value.
{
// Compute a heuristic hash width from the data.
for (size_t i = 0; i < 25; i++)
{
size_t p1 = (size_t) math::RandInt(referenceSet.n_cols);
size_t p2 = (size_t) math::RandInt(referenceSet.n_cols);
hashWidth += std::sqrt(metric::EuclideanDistance::Evaluate(
referenceSet.unsafe_col(p1), referenceSet.unsafe_col(p2)));
}
hashWidth /= 25;
}
Log::Info << "Hash width chosen as: " << hashWidth << std::endl;
BuildHash();
}
template<typename SortPolicy>
LSHSearch<SortPolicy>::
LSHSearch(const arma::mat& referenceSet,
const size_t numProj,
const size_t numTables,
const double hashWidthIn,
const size_t secondHashSize,
const size_t bucketSize) :
referenceSet(referenceSet),
querySet(referenceSet),
numProj(numProj),
numTables(numTables),
hashWidth(hashWidthIn),
secondHashSize(secondHashSize),
bucketSize(bucketSize),
distanceEvaluations(0)
{
if (hashWidth == 0.0) // The user has not provided any value.
{
// Compute a heuristic hash width from the data.
for (size_t i = 0; i < 25; i++)
{
size_t p1 = (size_t) math::RandInt(referenceSet.n_cols);
size_t p2 = (size_t) math::RandInt(referenceSet.n_cols);
hashWidth += std::sqrt(metric::EuclideanDistance::Evaluate(
referenceSet.unsafe_col(p1), referenceSet.unsafe_col(p2)));
}
hashWidth /= 25;
}
Log::Info << "Hash width chosen as: " << hashWidth << std::endl;
BuildHash();
}
template<typename SortPolicy>
void LSHSearch<SortPolicy>::InsertNeighbor(arma::mat& distances,
arma::Mat<size_t>& neighbors,
const size_t queryIndex,
const size_t pos,
const size_t neighbor,
const double distance)
{
// We only memmove() if there is actually a need to shift something.
if (pos < (distances.n_rows - 1))
{
const size_t len = (distances.n_rows - 1) - pos;
memmove(distances.colptr(queryIndex) + (pos + 1),
distances.colptr(queryIndex) + pos,
sizeof(double) * len);
memmove(neighbors.colptr(queryIndex) + (pos + 1),
neighbors.colptr(queryIndex) + pos,
sizeof(size_t) * len);
}
// Now put the new information in the right index.
distances(pos, queryIndex) = distance;
neighbors(pos, queryIndex) = neighbor;
}
template<typename SortPolicy>
inline force_inline
double LSHSearch<SortPolicy>::BaseCase(arma::mat& distances,
arma::Mat<size_t>& neighbors,
const size_t queryIndex,
const size_t referenceIndex)
{
// If the datasets are the same, then this search is only using one dataset
// and we should not return identical points.
if ((&querySet == &referenceSet) && (queryIndex == referenceIndex))
return 0.0;
const double distance = metric::EuclideanDistance::Evaluate(
querySet.unsafe_col(queryIndex), referenceSet.unsafe_col(referenceIndex));
// If this distance is better than any of the current candidates, the
// SortDistance() function will give us the position to insert it into.
arma::vec queryDist = distances.unsafe_col(queryIndex);
arma::Col<size_t> queryIndices = neighbors.unsafe_col(queryIndex);
size_t insertPosition = SortPolicy::SortDistance(queryDist, queryIndices,
distance);
// SortDistance() returns (size_t() - 1) if we shouldn't add it.
if (insertPosition != (size_t() - 1))
InsertNeighbor(distances, neighbors, queryIndex, insertPosition,
referenceIndex, distance);
return distance;
}
template<typename SortPolicy>
void LSHSearch<SortPolicy>::
ReturnIndicesFromTable(const size_t queryIndex,
arma::uvec& referenceIndices,
size_t numTablesToSearch)
{
// Decide on the number of tables to look into.
if (numTablesToSearch == 0) // If no user input is given, search all.
numTablesToSearch = numTables;
// Sanity check to make sure that the existing number of tables is not
// exceeded.
if (numTablesToSearch > numTables)
numTablesToSearch = numTables;
// Hash the query in each of the 'numTablesToSearch' hash tables using the
// 'numProj' projections for each table. This gives us 'numTablesToSearch'
// keys for the query where each key is a 'numProj' dimensional integer
// vector.
// Compute the projection of the query in each table.
arma::mat allProjInTables(numProj, numTablesToSearch);
for (size_t i = 0; i < numTablesToSearch; i++)
{
allProjInTables.unsafe_col(i) = projections[i].t() *
querySet.unsafe_col(queryIndex);
}
allProjInTables += offsets.cols(0, numTablesToSearch - 1);
allProjInTables /= hashWidth;
// Compute the hash value of each key of the query into a bucket of the
// 'secondHashTable' using the 'secondHashWeights'.
arma::rowvec hashVec = secondHashWeights.t() * arma::floor(allProjInTables);
for (size_t i = 0; i < hashVec.n_elem; i++)
hashVec[i] = (double) ((size_t) hashVec[i] % secondHashSize);
Log::Assert(hashVec.n_elem == numTablesToSearch);
// For all the buckets that the query is hashed into, sequentially
// collect the indices in those buckets.
arma::Col<size_t> refPointsConsidered;
refPointsConsidered.zeros(referenceSet.n_cols);
for (size_t i = 0; i < hashVec.n_elem; i++) // For all tables.
{
size_t hashInd = (size_t) hashVec[i];
if (bucketContentSize[hashInd] > 0)
{
// Pick the indices in the bucket corresponding to 'hashInd'.
size_t tableRow = bucketRowInHashTable[hashInd];
assert(tableRow < secondHashSize);
assert(tableRow < secondHashTable.n_rows);
for (size_t j = 0; j < bucketContentSize[hashInd]; j++)
refPointsConsidered[secondHashTable(tableRow, j)]++;
}
}
referenceIndices = arma::find(refPointsConsidered > 0);
}
template<typename SortPolicy>
void LSHSearch<SortPolicy>::
Search(const size_t k,
arma::Mat<size_t>& resultingNeighbors,
arma::mat& distances,
const size_t numTablesToSearch)
{
// Set the size of the neighbor and distance matrices.
resultingNeighbors.set_size(k, querySet.n_cols);
distances.set_size(k, querySet.n_cols);
distances.fill(SortPolicy::WorstDistance());
resultingNeighbors.fill(referenceSet.n_cols);
size_t avgIndicesReturned = 0;
Timer::Start("computing_neighbors");
// Go through every query point sequentially.
for (size_t i = 0; i < querySet.n_cols; i++)
{
// Hash every query into every hash table and eventually into the
// 'secondHashTable' to obtain the neighbor candidates.
arma::uvec refIndices;
ReturnIndicesFromTable(i, refIndices, numTablesToSearch);
// An informative book-keeping for the number of neighbor candidates
// returned on average.
avgIndicesReturned += refIndices.n_elem;
// Sequentially go through all the candidates and save the best 'k'
// candidates.
for (size_t j = 0; j < refIndices.n_elem; j++)
BaseCase(distances, resultingNeighbors, i, (size_t) refIndices[j]);
}
Timer::Stop("computing_neighbors");
distanceEvaluations += avgIndicesReturned;
avgIndicesReturned /= querySet.n_cols;
Log::Info << avgIndicesReturned << " distinct indices returned on average." <<
std::endl;
}
template<typename SortPolicy>
void LSHSearch<SortPolicy>::BuildHash()
{
// The first level hash for a single table outputs a 'numProj'-dimensional
// integer key for each point in the set -- (key, pointID)
// The key creation details are presented below
//
// The second level hash is performed by hashing the key to
// an integer in the range [0, 'secondHashSize').
//
// This is done by creating a weight vector 'secondHashWeights' of
// length 'numProj' with each entry an integer randomly chosen
// between [0, 'secondHashSize').
//
// Then the bucket for any key and its corresponding point is
// given by <key, 'secondHashWeights'> % 'secondHashSize'
// and the corresponding point ID is put into that bucket.
// Step I: Prepare the second level hash.
// Obtain the weights for the second hash.
secondHashWeights = arma::floor(arma::randu(numProj) *
(double) secondHashSize);
// The 'secondHashTable' is initially an empty matrix of size
// ('secondHashSize' x 'bucketSize'). But by only filling the buckets
// as points land in them allows us to shrink the size of the
// 'secondHashTable' at the end of the hashing.
// Fill the second hash table n = referenceSet.n_cols. This is because no
// point has index 'n' so the presence of this in the bucket denotes that
// there are no more points in this bucket.
secondHashTable.set_size(secondHashSize, bucketSize);
secondHashTable.fill(referenceSet.n_cols);
// Keep track of the size of each bucket in the hash. At the end of hashing
// most buckets will be empty.
bucketContentSize.zeros(secondHashSize);
// Instead of putting the points in the row corresponding to the bucket, we
// chose the next empty row and keep track of the row in which the bucket
// lies. This allows us to stack together and slice out the empty buckets at
// the end of the hashing.
bucketRowInHashTable.set_size(secondHashSize);
bucketRowInHashTable.fill(secondHashSize);
// Keep track of number of non-empty rows in the 'secondHashTable'.
size_t numRowsInTable = 0;
// Step II: The offsets for all projections in all tables.
// Since the 'offsets' are in [0, hashWidth], we obtain the 'offsets'
// as randu(numProj, numTables) * hashWidth.
offsets.randu(numProj, numTables);
offsets *= hashWidth;
// Step III: Create each hash table in the first level hash one by one and
// putting them directly into the 'secondHashTable' for memory efficiency.
for (size_t i = 0; i < numTables; i++)
{
// Step IV: Obtain the 'numProj' projections for each table.
// For L2 metric, 2-stable distributions are used, and
// the normal Z ~ N(0, 1) is a 2-stable distribution.
arma::mat projMat;
projMat.randn(referenceSet.n_rows, numProj);
// Save the projection matrix for querying.
projections.push_back(projMat);
// Step V: create the 'numProj'-dimensional key for each point in each
// table.
// The following code performs the task of hashing each point to a
// 'numProj'-dimensional integer key. Hence you get a ('numProj' x
// 'referenceSet.n_cols') key matrix.
//
// For a single table, let the 'numProj' projections be denoted by 'proj_i'
// and the corresponding offset be 'offset_i'. Then the key of a single
// point is obtained as:
// key = { floor( (<proj_i, point> + offset_i) / 'hashWidth' ) forall i }
arma::mat offsetMat = arma::repmat(offsets.unsafe_col(i), 1,
referenceSet.n_cols);
arma::mat hashMat = projMat.t() * referenceSet;
hashMat += offsetMat;
hashMat /= hashWidth;
// Step VI: Putting the points in the 'secondHashTable' by hashing the key.
// Now we hash every key, point ID to its corresponding bucket.
arma::rowvec secondHashVec = secondHashWeights.t()
* arma::floor(hashMat);
// This gives us the bucket for the corresponding point ID.
for (size_t j = 0; j < secondHashVec.n_elem; j++)
secondHashVec[j] = (double)((size_t) secondHashVec[j] % secondHashSize);
Log::Assert(secondHashVec.n_elem == referenceSet.n_cols);
// Insert the point in the corresponding row to its bucket in the
// 'secondHashTable'.
for (size_t j = 0; j < secondHashVec.n_elem; j++)
{
// This is the bucket number.
size_t hashInd = (size_t) secondHashVec[j];
// The point ID is 'j'.
// If this is currently an empty bucket, start a new row keep track of
// which row corresponds to the bucket.
if (bucketContentSize[hashInd] == 0)
{
// Start a new row for hash.
bucketRowInHashTable[hashInd] = numRowsInTable;
secondHashTable(numRowsInTable, 0) = j;
numRowsInTable++;
}
else
{
// If bucket is already present in the 'secondHashTable', find the
// corresponding row and insert the point ID in this row unless the
// bucket is full, in which case, do nothing.
if (bucketContentSize[hashInd] < bucketSize)
secondHashTable(bucketRowInHashTable[hashInd],
bucketContentSize[hashInd]) = j;
}
// Increment the count of the points in this bucket.
if (bucketContentSize[hashInd] < bucketSize)
bucketContentSize[hashInd]++;
} // Loop over all points in the reference set.
} // Loop over tables.
// Step VII: Condensing the 'secondHashTable'.
size_t maxBucketSize = 0;
for (size_t i = 0; i < bucketContentSize.n_elem; i++)
if (bucketContentSize[i] > maxBucketSize)
maxBucketSize = bucketContentSize[i];
Log::Info << "Final hash table size: (" << numRowsInTable << " x "
<< maxBucketSize << ")" << std::endl;
secondHashTable.resize(numRowsInTable, maxBucketSize);
}
template<typename SortPolicy>
std::string LSHSearch<SortPolicy>::ToString() const
{
std::ostringstream convert;
convert << "LSHSearch [" << this << "]" << std::endl;
convert << " Reference Set: " << referenceSet.n_rows << "x" ;
convert << referenceSet.n_cols << std::endl;
if (&referenceSet != &querySet)
convert << " QuerySet: " << querySet.n_rows << "x" << querySet.n_cols
<< std::endl;
convert << " Number of Projections: " << numProj << std::endl;
convert << " Number of Tables: " << numTables << std::endl;
convert << " Hash Width: " << hashWidth << std::endl;
return convert.str();
}
}; // namespace neighbor
}; // namespace mlpack
#endif
| 35.838942 | 80 | 0.669394 | [
"object",
"vector"
] |
cd170d47bbc64cf0ac3c2e1aca569145e4a8cc00 | 3,114 | cpp | C++ | examples/google-code-jam/trecio/ParentingPartnering.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/trecio/ParentingPartnering.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/trecio/ParentingPartnering.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct period {
int from;
int to;
char who;
int duration() const {
return to - from;
}
bool operator<(const period& other) {
return from < other.from;
}
};
bool by_duration_descending(const period& left, const period& right) {
return left.duration() > right.duration();
}
int get_time(const vector<period>&p, char who) {
int t = 0;
for (unsigned i = 0; i < p.size(); i += 1) {
if (p[i].who == who) {
t += p[i].duration();
}
}
return t;
}
void dump(const vector<period>&p, char who) {
cerr << who << ":";
for (int i = 0; i < p.size(); i += 1){
if (p[i].who == who) {
cerr << "(" << p[i].from << ", " << p[i].to << ": " << p[i].duration() << ")\t";
}
}
cerr << endl;
}
int main() {
int T;
cin >> T;
for (int t = 1; t <= T; t += 1) {
int ac, aj;
cin >> ac >> aj;
vector<period> p;
p.resize(ac + aj);
for (int i = 0; i < ac + aj; i += 1) {
cin >> p[i].from >> p[i].to;
}
for (int i = 0; i < ac; i += 1) {
p[i].who = 'J';
}
for (int i = ac; i < ac + aj; i += 1){
p[i].who = 'C';
}
sort(p.begin(), p.end());
dump(p, 'C');
dump(p, 'J');
int c_t = 720 - get_time(p, 'C');
int j_t = 720 - get_time(p, 'J');
cerr << "Capacity: C = " << c_t << " J = " << j_t << endl;
vector<period> to_take;
for (unsigned i = 1; i < p.size(); i += 1) {
period pp;
pp.to = p[i].from;
pp.from = p[i - 1].to;
pp.who = p[i].who == p[i - 1].who
? p[i].who
: '?';
to_take.push_back(pp);
}
period pp;
pp.from = p[p.size() - 1].to;
pp.to = p[0].from + 1440;
pp.who = p[0].who == p[p.size() - 1].who
? p[0].who
: '?';
to_take.push_back(pp);
sort(to_take.begin(), to_take.end(), by_duration_descending);
for (int i = to_take.size() - 1; i >= 0; i -= 1) {
switch (to_take[i].who)
{
case 'C':
if (to_take[i].duration() < c_t) {
p.push_back(to_take[i]);
c_t -= to_take[i].duration();
to_take.erase(to_take.begin() + i);
cerr << "C: (" << to_take[i].from << ", " << to_take[i].to << ": " << to_take[i].duration() << ")" << endl;
}
break;
case 'J':
if (to_take[i].duration() < j_t) {
p.push_back(to_take[i]);
j_t -= to_take[i].duration();
to_take.erase(to_take.begin() + i);
cerr << "J: (" << to_take[i].from << ", " << to_take[i].to << ": " << to_take[i].duration() << ")" << endl;
}
break;
}
}
cerr << "Capacity: C = " << c_t << " J = " << j_t << endl;
int result = 0;
for (unsigned i = 0; i < to_take.size(); i += 1) {
if (to_take[i].who == '?') {
result += 1;
cerr << "Switch between " << to_take[i].from << " and " << to_take[i].to << endl;
}
else {
result += 2;
cerr << "Switch between " << to_take[i].from << " and " << to_take[i].to << " and back" << endl;
}
}
cout << "Case #" << t << ": " << result << endl;
cerr << "Case #" << t << ": " << result << endl;
}
return 0;
} | 23.953846 | 113 | 0.468208 | [
"vector"
] |
cd1de70480f20393cb7e8ccf4e50040ae1d9ef43 | 1,114 | cpp | C++ | src/crypto/test/base64.cpp | Jerryxia32/CCF | 2514a92ff96ca22aff37994d211ace2e1c918097 | [
"Apache-2.0"
] | null | null | null | src/crypto/test/base64.cpp | Jerryxia32/CCF | 2514a92ff96ca22aff37994d211ace2e1c918097 | [
"Apache-2.0"
] | 23 | 2021-11-08T07:23:47.000Z | 2022-01-17T18:49:33.000Z | src/crypto/test/base64.cpp | Jerryxia32/CCF | 2514a92ff96ca22aff37994d211ace2e1c918097 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "crypto/base64.h"
#include <chrono>
#include <doctest/doctest.h>
#include <string>
using namespace std;
using namespace crypto;
TEST_CASE("base64")
{
for (size_t length = 1; length < 20; ++length)
{
std::vector<uint8_t> raw(length);
std::generate(raw.begin(), raw.end(), rand);
const auto encoded = b64_from_raw(raw.data(), raw.size());
const auto decoded = raw_from_b64(encoded);
REQUIRE(decoded == raw);
}
}
TEST_CASE("base64url")
{
for (size_t length = 1; length < 20; ++length)
{
std::vector<uint8_t> raw(length);
std::generate(raw.begin(), raw.end(), rand);
auto encoded = b64_from_raw(raw.data(), raw.size());
std::replace(encoded.begin(), encoded.end(), '+', '-');
std::replace(encoded.begin(), encoded.end(), '/', '_');
encoded.erase(
std::find(encoded.begin(), encoded.end(), '='), encoded.end());
const auto decoded = raw_from_b64url(encoded);
REQUIRE(decoded == raw);
}
}
| 26.52381 | 69 | 0.651706 | [
"vector"
] |
cd1e314080b9e4a6785f90209b999d3f0490af27 | 7,283 | hpp | C++ | 3rdparty/g2o/g2o/solvers/pcg/linear_solver_pcg.hpp | Refstop/VSLAM_Example | 060b9419f79f035d1c9ebfa75ad46e2e9a53e992 | [
"MIT"
] | null | null | null | 3rdparty/g2o/g2o/solvers/pcg/linear_solver_pcg.hpp | Refstop/VSLAM_Example | 060b9419f79f035d1c9ebfa75ad46e2e9a53e992 | [
"MIT"
] | null | null | null | 3rdparty/g2o/g2o/solvers/pcg/linear_solver_pcg.hpp | Refstop/VSLAM_Example | 060b9419f79f035d1c9ebfa75ad46e2e9a53e992 | [
"MIT"
] | null | null | null | // g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// helpers for doing fixed or variable size operations on the matrices
namespace internal {
#ifdef _MSC_VER
// MSVC does not like the template specialization, seems like MSVC applies type
// conversion which results in calling a fixed size method (segment<int>) on the
// dynamically sized matrices
template <typename MatrixType>
void pcg_axy(const MatrixType& A, const VectorX& x, int xoff, VectorX& y,
int yoff) {
y.segment(yoff, A.rows()) = A * x.segment(xoff, A.cols());
}
#else
template <typename MatrixType>
inline void pcg_axy(const MatrixType& A, const VectorX& x, int xoff, VectorX& y,
int yoff) {
y.segment<MatrixType::RowsAtCompileTime>(yoff) =
A * x.segment<MatrixType::ColsAtCompileTime>(xoff);
}
template <>
inline void pcg_axy(const MatrixX& A, const VectorX& x, int xoff, VectorX& y,
int yoff) {
y.segment(yoff, A.rows()) = A * x.segment(xoff, A.cols());
}
#endif
template <typename MatrixType>
inline void pcg_axpy(const MatrixType& A, const VectorX& x, int xoff,
VectorX& y, int yoff) {
y.segment<MatrixType::RowsAtCompileTime>(yoff) +=
A * x.segment<MatrixType::ColsAtCompileTime>(xoff);
}
template <>
inline void pcg_axpy(const MatrixX& A, const VectorX& x, int xoff, VectorX& y,
int yoff) {
y.segment(yoff, A.rows()) += A * x.segment(xoff, A.cols());
}
template <typename MatrixType>
inline void pcg_atxpy(const MatrixType& A, const VectorX& x, int xoff,
VectorX& y, int yoff) {
y.segment<MatrixType::ColsAtCompileTime>(yoff) +=
A.transpose() * x.segment<MatrixType::RowsAtCompileTime>(xoff);
}
template <>
inline void pcg_atxpy(const MatrixX& A, const VectorX& x, int xoff, VectorX& y,
int yoff) {
y.segment(yoff, A.cols()) += A.transpose() * x.segment(xoff, A.rows());
}
} // namespace internal
// helpers end
template <typename MatrixType>
bool LinearSolverPCG<MatrixType>::solve(const SparseBlockMatrix<MatrixType>& A,
number_t* x, number_t* b) {
const bool indexRequired = _indices.size() == 0;
_diag.clear();
_J.clear();
// put the block matrix once in a linear structure, makes mult faster
int colIdx = 0;
for (size_t i = 0; i < A.blockCols().size(); ++i) {
const typename SparseBlockMatrix<MatrixType>::IntBlockMap& col =
A.blockCols()[i];
if (col.size() > 0) {
typename SparseBlockMatrix<MatrixType>::IntBlockMap::const_iterator it;
for (it = col.begin(); it != col.end(); ++it) {
if (it->first == (int)i) { // only the upper triangular block is needed
_diag.push_back(it->second);
_J.push_back(it->second->inverse());
break;
}
if (indexRequired) {
_indices.push_back(std::make_pair(
it->first > 0 ? A.rowBlockIndices()[it->first - 1] : 0, colIdx));
_sparseMat.push_back(it->second);
}
}
}
colIdx = A.colBlockIndices()[i];
}
int n = A.rows();
assert(n > 0 && "Hessian has 0 rows/cols");
Eigen::Map<VectorX> xvec(x, A.cols());
const Eigen::Map<VectorX> bvec(b, n);
xvec.setZero();
VectorX r, d, q, s;
d.setZero(n);
q.setZero(n);
s.setZero(n);
r = bvec;
multDiag(A.colBlockIndices(), _J, r, d);
number_t dn = r.dot(d);
number_t d0 = _tolerance * dn;
if (_absoluteTolerance) {
if (_residual > 0.0 && _residual > d0) d0 = _residual;
}
int maxIter = _maxIter < 0 ? A.rows() : _maxIter;
int iteration;
for (iteration = 0; iteration < maxIter; ++iteration) {
if (_verbose)
std::cerr << "residual[" << iteration << "]: " << dn << std::endl;
if (dn <= d0) break; // done
mult(A.colBlockIndices(), d, q);
number_t a = dn / d.dot(q);
xvec += a * d;
// TODO: reset residual here every 50 iterations
r -= a * q;
multDiag(A.colBlockIndices(), _J, r, s);
number_t dold = dn;
dn = r.dot(s);
number_t ba = dn / dold;
d = s + ba * d;
}
// std::cerr << "residual[" << iteration << "]: " << dn << std::endl;
_residual = 0.5 * dn;
G2OBatchStatistics* globalStats = G2OBatchStatistics::globalStats();
if (globalStats) {
globalStats->iterationsLinearSolver = iteration;
}
return true;
}
template <typename MatrixType>
void LinearSolverPCG<MatrixType>::multDiag(
const std::vector<int>& colBlockIndices, MatrixVector& A,
const VectorX& src, VectorX& dest) {
int row = 0;
for (size_t i = 0; i < A.size(); ++i) {
internal::pcg_axy(A[i], src, row, dest, row);
row = colBlockIndices[i];
}
}
template <typename MatrixType>
void LinearSolverPCG<MatrixType>::multDiag(
const std::vector<int>& colBlockIndices, MatrixPtrVector& A,
const VectorX& src, VectorX& dest) {
int row = 0;
for (size_t i = 0; i < A.size(); ++i) {
internal::pcg_axy(*A[i], src, row, dest, row);
row = colBlockIndices[i];
}
}
template <typename MatrixType>
void LinearSolverPCG<MatrixType>::mult(const std::vector<int>& colBlockIndices,
const VectorX& src, VectorX& dest) {
// first multiply with the diagonal
multDiag(colBlockIndices, _diag, src, dest);
// now multiply with the upper triangular block
for (size_t i = 0; i < _sparseMat.size(); ++i) {
const int& srcOffset = _indices[i].second;
const int& destOffsetT = srcOffset;
const int& destOffset = _indices[i].first;
const int& srcOffsetT = destOffset;
const typename SparseBlockMatrix<MatrixType>::SparseMatrixBlock* a =
_sparseMat[i];
// destVec += *a * srcVec (according to the sub-vector parts)
internal::pcg_axpy(*a, src, srcOffset, dest, destOffset);
// destVec += *a.transpose() * srcVec (according to the sub-vector parts)
internal::pcg_atxpy(*a, src, srcOffsetT, dest, destOffsetT);
}
}
| 35.70098 | 80 | 0.654401 | [
"vector"
] |
cd247c76b216c5687f69a1da55e9b7c02f820d8d | 30,732 | cpp | C++ | exportNF/release/windows/obj/src/openfl/display/CanvasRenderer.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/src/openfl/display/CanvasRenderer.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/src/openfl/display/CanvasRenderer.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | // Generated by Haxe 4.2.1+bf9ff69
#include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_lime_app_IModule
#include <lime/app/IModule.h>
#endif
#ifndef INCLUDED_lime_ui_Window
#include <lime/ui/Window.h>
#endif
#ifndef INCLUDED_openfl_display_Bitmap
#include <openfl/display/Bitmap.h>
#endif
#ifndef INCLUDED_openfl_display_BitmapData
#include <openfl/display/BitmapData.h>
#endif
#ifndef INCLUDED_openfl_display_CanvasRenderer
#include <openfl/display/CanvasRenderer.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObject
#include <openfl/display/DisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectContainer
#include <openfl/display/DisplayObjectContainer.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectRenderer
#include <openfl/display/DisplayObjectRenderer.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_display_ITileContainer
#include <openfl/display/ITileContainer.h>
#endif
#ifndef INCLUDED_openfl_display_InteractiveObject
#include <openfl/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_openfl_display_SimpleButton
#include <openfl/display/SimpleButton.h>
#endif
#ifndef INCLUDED_openfl_display_Stage
#include <openfl/display/Stage.h>
#endif
#ifndef INCLUDED_openfl_display_Tilemap
#include <openfl/display/Tilemap.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasBitmap
#include <openfl/display/_internal/CanvasBitmap.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasBitmapData
#include <openfl/display/_internal/CanvasBitmapData.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasDisplayObject
#include <openfl/display/_internal/CanvasDisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasDisplayObjectContainer
#include <openfl/display/_internal/CanvasDisplayObjectContainer.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasSimpleButton
#include <openfl/display/_internal/CanvasSimpleButton.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasTextField
#include <openfl/display/_internal/CanvasTextField.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasTilemap
#include <openfl/display/_internal/CanvasTilemap.h>
#endif
#ifndef INCLUDED_openfl_display__internal_CanvasVideo
#include <openfl/display/_internal/CanvasVideo.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_geom_Matrix
#include <openfl/geom/Matrix.h>
#endif
#ifndef INCLUDED_openfl_geom_Rectangle
#include <openfl/geom/Rectangle.h>
#endif
#ifndef INCLUDED_openfl_media_Video
#include <openfl/media/Video.h>
#endif
#ifndef INCLUDED_openfl_text_TextField
#include <openfl/text/TextField.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_dcbf857ab860ed73_35_new,"openfl.display.CanvasRenderer","new",0xb7099f97,"openfl.display.CanvasRenderer.new","openfl/display/CanvasRenderer.hx",35,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_71_applySmoothing,"openfl.display.CanvasRenderer","applySmoothing",0xf98f304f,"openfl.display.CanvasRenderer.applySmoothing","openfl/display/CanvasRenderer.hx",71,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_80_setTransform,"openfl.display.CanvasRenderer","setTransform",0x3b7aff53,"openfl.display.CanvasRenderer.setTransform","openfl/display/CanvasRenderer.hx",80,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_104___clear,"openfl.display.CanvasRenderer","__clear",0x050d0124,"openfl.display.CanvasRenderer.__clear","openfl/display/CanvasRenderer.hx",104,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_129___popMask,"openfl.display.CanvasRenderer","__popMask",0xbaf74a74,"openfl.display.CanvasRenderer.__popMask","openfl/display/CanvasRenderer.hx",129,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_133___popMaskObject,"openfl.display.CanvasRenderer","__popMaskObject",0x24188c53,"openfl.display.CanvasRenderer.__popMaskObject","openfl/display/CanvasRenderer.hx",133,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_147___popMaskRect,"openfl.display.CanvasRenderer","__popMaskRect",0xaa600db8,"openfl.display.CanvasRenderer.__popMaskRect","openfl/display/CanvasRenderer.hx",147,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_151___pushMask,"openfl.display.CanvasRenderer","__pushMask",0x88887caf,"openfl.display.CanvasRenderer.__pushMask","openfl/display/CanvasRenderer.hx",151,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_164___pushMaskObject,"openfl.display.CanvasRenderer","__pushMaskObject",0xbb0d9cce,"openfl.display.CanvasRenderer.__pushMaskObject","openfl/display/CanvasRenderer.hx",164,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_177___pushMaskRect,"openfl.display.CanvasRenderer","__pushMaskRect",0x16167973,"openfl.display.CanvasRenderer.__pushMaskRect","openfl/display/CanvasRenderer.hx",177,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_189___render,"openfl.display.CanvasRenderer","__render",0x63d57fdf,"openfl.display.CanvasRenderer.__render","openfl/display/CanvasRenderer.hx",189,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_193___renderDrawable,"openfl.display.CanvasRenderer","__renderDrawable",0x87e19e9d,"openfl.display.CanvasRenderer.__renderDrawable","openfl/display/CanvasRenderer.hx",193,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_219___renderDrawableMask,"openfl.display.CanvasRenderer","__renderDrawableMask",0x75211e29,"openfl.display.CanvasRenderer.__renderDrawableMask","openfl/display/CanvasRenderer.hx",219,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_245___setBlendMode,"openfl.display.CanvasRenderer","__setBlendMode",0xc677459b,"openfl.display.CanvasRenderer.__setBlendMode","openfl/display/CanvasRenderer.hx",245,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_256___setBlendModeContext,"openfl.display.CanvasRenderer","__setBlendModeContext",0x277f3194,"openfl.display.CanvasRenderer.__setBlendModeContext","openfl/display/CanvasRenderer.hx",256,0x2676f477)
HX_LOCAL_STACK_FRAME(_hx_pos_dcbf857ab860ed73_35_boot,"openfl.display.CanvasRenderer","boot",0x697b051b,"openfl.display.CanvasRenderer.boot","openfl/display/CanvasRenderer.hx",35,0x2676f477)
namespace openfl{
namespace display{
void CanvasRenderer_obj::__construct( ::Dynamic context){
HX_GC_STACKFRAME(&_hx_pos_dcbf857ab860ed73_35_new)
HXLINE( 46) this->pixelRatio = ((Float)1);
HXLINE( 54) super::__construct();
HXLINE( 56) this->context = context;
HXLINE( 58) this->_hx___tempMatrix = ::openfl::geom::Matrix_obj::__alloc( HX_CTX ,null(),null(),null(),null(),null(),null());
HXLINE( 61) this->_hx___type = HX_("canvas",d8,54,42,b8);
}
Dynamic CanvasRenderer_obj::__CreateEmpty() { return new CanvasRenderer_obj; }
void *CanvasRenderer_obj::_hx_vtable = 0;
Dynamic CanvasRenderer_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< CanvasRenderer_obj > _hx_result = new CanvasRenderer_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool CanvasRenderer_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x16827685) {
if (inClassId<=(int)0x0c89e854) {
return inClassId==(int)0x00000001 || inClassId==(int)0x0c89e854;
} else {
return inClassId==(int)0x16827685;
}
} else {
return inClassId==(int)0x49529132;
}
}
void CanvasRenderer_obj::applySmoothing( ::Dynamic context,bool value){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_71_applySmoothing)
HXDLIN( 71) context->__SetField(HX_("imageSmoothingEnabled",e8,4e,0e,94),value,::hx::paccDynamic);
}
HX_DEFINE_DYNAMIC_FUNC2(CanvasRenderer_obj,applySmoothing,(void))
void CanvasRenderer_obj::setTransform( ::openfl::geom::Matrix transform, ::Dynamic context){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_80_setTransform)
HXLINE( 81) if (::hx::IsNull( context )) {
HXLINE( 83) context = this->context;
}
else {
HXLINE( 85) bool _hx_tmp;
HXDLIN( 85) if (::hx::IsEq( this->context,context )) {
HXLINE( 85) _hx_tmp = ::hx::IsNotNull( this->_hx___worldTransform );
}
else {
HXLINE( 85) _hx_tmp = false;
}
HXDLIN( 85) if (_hx_tmp) {
HXLINE( 87) this->_hx___tempMatrix->copyFrom(transform);
HXLINE( 88) this->_hx___tempMatrix->concat(this->_hx___worldTransform);
HXLINE( 89) transform = this->_hx___tempMatrix;
}
}
HXLINE( 92) if (this->_hx___roundPixels) {
HXLINE( 94) ::Dynamic context1 = ::Dynamic(context->__Field(HX_("setTransform",6a,ed,e2,69),::hx::paccDynamic));
HXDLIN( 94) Float transform1 = transform->a;
HXDLIN( 94) Float transform2 = transform->b;
HXDLIN( 94) Float transform3 = transform->c;
HXDLIN( 94) Float transform4 = transform->d;
HXDLIN( 94) int _hx_tmp = ::Std_obj::_hx_int(transform->tx);
HXDLIN( 94) context1(transform1,transform2,transform3,transform4,_hx_tmp,::Std_obj::_hx_int(transform->ty));
}
else {
HXLINE( 98) context->__Field(HX_("setTransform",6a,ed,e2,69),::hx::paccDynamic)(transform->a,transform->b,transform->c,transform->d,transform->tx,transform->ty);
}
}
HX_DEFINE_DYNAMIC_FUNC2(CanvasRenderer_obj,setTransform,(void))
void CanvasRenderer_obj::_hx___clear(){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_104___clear)
HXDLIN( 104) if (::hx::IsNotNull( this->_hx___stage )) {
HXLINE( 106) ::Dynamic cacheBlendMode = this->_hx___blendMode;
HXLINE( 107) this->_hx___blendMode = null();
HXLINE( 108) this->_hx___setBlendMode(10);
HXLINE( 110) this->context->__Field(HX_("setTransform",6a,ed,e2,69),::hx::paccDynamic)(1,0,0,1,0,0);
HXLINE( 111) this->context->__SetField(HX_("globalAlpha",fb,fe,d4,f9),1,::hx::paccDynamic);
HXLINE( 113) bool _hx_tmp;
HXDLIN( 113) if (!(this->_hx___stage->_hx___transparent)) {
HXLINE( 113) _hx_tmp = this->_hx___stage->_hx___clearBeforeRender;
}
else {
HXLINE( 113) _hx_tmp = false;
}
HXDLIN( 113) if (_hx_tmp) {
HXLINE( 115) this->context->__SetField(HX_("fillStyle",ae,cb,c4,52),this->_hx___stage->_hx___colorString,::hx::paccDynamic);
HXLINE( 116) this->context->__Field(HX_("fillRect",47,45,b9,6c),::hx::paccDynamic)(0,0,(( (Float)(this->_hx___stage->stageWidth) ) * this->_hx___stage->window->_hx___scale),(( (Float)(this->_hx___stage->stageHeight) ) * this->_hx___stage->window->_hx___scale));
}
else {
HXLINE( 118) bool _hx_tmp;
HXDLIN( 118) if (this->_hx___stage->_hx___transparent) {
HXLINE( 118) _hx_tmp = this->_hx___stage->_hx___clearBeforeRender;
}
else {
HXLINE( 118) _hx_tmp = false;
}
HXDLIN( 118) if (_hx_tmp) {
HXLINE( 120) this->context->__Field(HX_("clearRect",51,35,68,bf),::hx::paccDynamic)(0,0,(( (Float)(this->_hx___stage->stageWidth) ) * this->_hx___stage->window->_hx___scale),(( (Float)(this->_hx___stage->stageHeight) ) * this->_hx___stage->window->_hx___scale));
}
}
HXLINE( 123) this->_hx___setBlendMode(cacheBlendMode);
}
}
void CanvasRenderer_obj::_hx___popMask(){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_129___popMask)
HXDLIN( 129) this->context->__Field(HX_("restore",4e,67,b0,6a),::hx::paccDynamic)();
}
void CanvasRenderer_obj::_hx___popMaskObject( ::openfl::display::DisplayObject object,::hx::Null< bool > __o_handleScrollRect){
bool handleScrollRect = __o_handleScrollRect.Default(true);
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_133___popMaskObject)
HXLINE( 134) bool _hx_tmp;
HXDLIN( 134) if (!(object->_hx___isCacheBitmapRender)) {
HXLINE( 134) _hx_tmp = ::hx::IsNotNull( object->_hx___mask );
}
else {
HXLINE( 134) _hx_tmp = false;
}
HXDLIN( 134) if (_hx_tmp) {
HXLINE( 136) this->_hx___popMask();
}
HXLINE( 139) bool _hx_tmp1;
HXDLIN( 139) if (handleScrollRect) {
HXLINE( 139) _hx_tmp1 = ::hx::IsNotNull( object->_hx___scrollRect );
}
else {
HXLINE( 139) _hx_tmp1 = false;
}
HXDLIN( 139) if (_hx_tmp1) {
HXLINE( 141) this->_hx___popMaskRect();
}
}
void CanvasRenderer_obj::_hx___popMaskRect(){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_147___popMaskRect)
HXDLIN( 147) this->context->__Field(HX_("restore",4e,67,b0,6a),::hx::paccDynamic)();
}
void CanvasRenderer_obj::_hx___pushMask( ::openfl::display::DisplayObject mask){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_151___pushMask)
HXLINE( 152) this->context->__Field(HX_("save",3d,8b,4d,4c),::hx::paccDynamic)();
HXLINE( 154) this->setTransform(mask->_hx___renderTransform,this->context);
HXLINE( 156) this->context->__Field(HX_("beginPath",6e,c4,2b,93),::hx::paccDynamic)();
HXLINE( 157) this->_hx___renderDrawableMask(mask);
HXLINE( 158) this->context->__Field(HX_("closePath",7d,65,20,14),::hx::paccDynamic)();
HXLINE( 160) this->context->__Field(HX_("clip",d0,6e,c2,41),::hx::paccDynamic)();
}
void CanvasRenderer_obj::_hx___pushMaskObject( ::openfl::display::DisplayObject object,::hx::Null< bool > __o_handleScrollRect){
bool handleScrollRect = __o_handleScrollRect.Default(true);
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_164___pushMaskObject)
HXLINE( 165) bool _hx_tmp;
HXDLIN( 165) if (handleScrollRect) {
HXLINE( 165) _hx_tmp = ::hx::IsNotNull( object->_hx___scrollRect );
}
else {
HXLINE( 165) _hx_tmp = false;
}
HXDLIN( 165) if (_hx_tmp) {
HXLINE( 167) this->_hx___pushMaskRect(object->_hx___scrollRect,object->_hx___renderTransform);
}
HXLINE( 170) bool _hx_tmp1;
HXDLIN( 170) if (!(object->_hx___isCacheBitmapRender)) {
HXLINE( 170) _hx_tmp1 = ::hx::IsNotNull( object->_hx___mask );
}
else {
HXLINE( 170) _hx_tmp1 = false;
}
HXDLIN( 170) if (_hx_tmp1) {
HXLINE( 172) this->_hx___pushMask(object->_hx___mask);
}
}
void CanvasRenderer_obj::_hx___pushMaskRect( ::openfl::geom::Rectangle rect, ::openfl::geom::Matrix transform){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_177___pushMaskRect)
HXLINE( 178) this->context->__Field(HX_("save",3d,8b,4d,4c),::hx::paccDynamic)();
HXLINE( 180) this->setTransform(transform,this->context);
HXLINE( 182) this->context->__Field(HX_("beginPath",6e,c4,2b,93),::hx::paccDynamic)();
HXLINE( 183) this->context->__Field(HX_("rect",24,4d,a7,4b),::hx::paccDynamic)(rect->x,rect->y,rect->width,rect->height);
HXLINE( 184) this->context->__Field(HX_("clip",d0,6e,c2,41),::hx::paccDynamic)();
}
void CanvasRenderer_obj::_hx___render(::Dynamic object){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_189___render)
HXDLIN( 189) this->_hx___renderDrawable(object);
}
void CanvasRenderer_obj::_hx___renderDrawable(::Dynamic object){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_193___renderDrawable)
HXLINE( 194) if (::hx::IsNull( object )) {
HXLINE( 194) return;
}
HXLINE( 196) switch((int)(( (int)(object->__Field(HX_("__drawableType",98,b4,3c,42),::hx::paccDynamic)) ))){
case (int)0: {
HXLINE( 199) ::openfl::display::_internal::CanvasBitmapData_obj::renderDrawable(( ( ::openfl::display::BitmapData)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)2: {
HXLINE( 203) ::openfl::display::_internal::CanvasBitmap_obj::renderDrawable(( ( ::openfl::display::Bitmap)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)3: {
HXLINE( 205) ::openfl::display::_internal::CanvasDisplayObject_obj::renderDrawable(( ( ::openfl::display::DisplayObject)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)4: case (int)5: {
HXLINE( 201) ::openfl::display::_internal::CanvasDisplayObjectContainer_obj::renderDrawable(( ( ::openfl::display::DisplayObjectContainer)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)6: {
HXLINE( 207) ::openfl::display::_internal::CanvasSimpleButton_obj::renderDrawable(( ( ::openfl::display::SimpleButton)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)7: {
HXLINE( 209) ::openfl::display::_internal::CanvasTextField_obj::renderDrawable(( ( ::openfl::text::TextField)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)8: {
HXLINE( 211) ::openfl::display::_internal::CanvasVideo_obj::renderDrawable(( ( ::openfl::media::Video)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)9: {
HXLINE( 213) ::openfl::display::_internal::CanvasTilemap_obj::renderDrawable(( ( ::openfl::display::Tilemap)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
default:{
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(CanvasRenderer_obj,_hx___renderDrawable,(void))
void CanvasRenderer_obj::_hx___renderDrawableMask(::Dynamic object){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_219___renderDrawableMask)
HXLINE( 220) if (::hx::IsNull( object )) {
HXLINE( 220) return;
}
HXLINE( 222) switch((int)(( (int)(object->__Field(HX_("__drawableType",98,b4,3c,42),::hx::paccDynamic)) ))){
case (int)0: {
HXLINE( 225) ::openfl::display::_internal::CanvasBitmapData_obj::renderDrawableMask(( ( ::openfl::display::BitmapData)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)2: {
HXLINE( 229) ::openfl::display::_internal::CanvasBitmap_obj::renderDrawableMask(( ( ::openfl::display::Bitmap)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)3: {
HXLINE( 231) ::openfl::display::_internal::CanvasDisplayObject_obj::renderDrawableMask(( ( ::openfl::display::DisplayObject)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)4: case (int)5: {
HXLINE( 227) ::openfl::display::_internal::CanvasDisplayObjectContainer_obj::renderDrawableMask(( ( ::openfl::display::DisplayObjectContainer)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)6: {
HXLINE( 233) ::openfl::display::_internal::CanvasSimpleButton_obj::renderDrawableMask(( ( ::openfl::display::SimpleButton)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)7: {
HXLINE( 235) ::openfl::display::_internal::CanvasTextField_obj::renderDrawableMask(( ( ::openfl::text::TextField)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)8: {
HXLINE( 237) ::openfl::display::_internal::CanvasVideo_obj::renderDrawableMask(( ( ::openfl::media::Video)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
case (int)9: {
HXLINE( 239) ::openfl::display::_internal::CanvasTilemap_obj::renderDrawableMask(( ( ::openfl::display::Tilemap)(object) ),::hx::ObjectPtr<OBJ_>(this));
}
break;
default:{
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(CanvasRenderer_obj,_hx___renderDrawableMask,(void))
void CanvasRenderer_obj::_hx___setBlendMode( ::Dynamic value){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_245___setBlendMode)
HXLINE( 246) if (::hx::IsNotNull( this->_hx___overrideBlendMode )) {
HXLINE( 246) value = this->_hx___overrideBlendMode;
}
HXLINE( 247) if (::hx::IsEq( this->_hx___blendMode,value )) {
HXLINE( 247) return;
}
HXLINE( 249) this->_hx___blendMode = value;
HXLINE( 250) this->_hx___setBlendModeContext(this->context,value);
}
void CanvasRenderer_obj::_hx___setBlendModeContext( ::Dynamic context, ::Dynamic value){
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_256___setBlendModeContext)
HXDLIN( 256) ::Dynamic _hx_switch_0 = value;
if ( (_hx_switch_0==0) ){
HXLINE( 259) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("lighter",c3,4a,e3,19),::hx::paccDynamic);
HXDLIN( 259) goto _hx_goto_14;
}
if ( (_hx_switch_0==2) ){
HXLINE( 266) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("darken",5f,36,3a,21),::hx::paccDynamic);
HXDLIN( 266) goto _hx_goto_14;
}
if ( (_hx_switch_0==3) ){
HXLINE( 269) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("difference",fd,9b,91,46),::hx::paccDynamic);
HXDLIN( 269) goto _hx_goto_14;
}
if ( (_hx_switch_0==5) ){
HXLINE( 276) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("hard-light",b4,7e,9e,35),::hx::paccDynamic);
HXDLIN( 276) goto _hx_goto_14;
}
if ( (_hx_switch_0==8) ){
HXLINE( 287) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("lighten",bf,4a,e3,19),::hx::paccDynamic);
HXDLIN( 287) goto _hx_goto_14;
}
if ( (_hx_switch_0==9) ){
HXLINE( 290) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("multiply",24,e2,8c,9a),::hx::paccDynamic);
HXDLIN( 290) goto _hx_goto_14;
}
if ( (_hx_switch_0==11) ){
HXLINE( 293) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("overlay",90,43,10,a9),::hx::paccDynamic);
HXDLIN( 293) goto _hx_goto_14;
}
if ( (_hx_switch_0==12) ){
HXLINE( 296) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("screen",6c,3b,5d,47),::hx::paccDynamic);
HXDLIN( 296) goto _hx_goto_14;
}
/* default */{
HXLINE( 307) context->__SetField(HX_("globalCompositeOperation",63,05,f9,c0),HX_("source-over",46,01,99,ce),::hx::paccDynamic);
}
_hx_goto_14:;
}
HX_DEFINE_DYNAMIC_FUNC2(CanvasRenderer_obj,_hx___setBlendModeContext,(void))
::hx::ObjectPtr< CanvasRenderer_obj > CanvasRenderer_obj::__new( ::Dynamic context) {
::hx::ObjectPtr< CanvasRenderer_obj > __this = new CanvasRenderer_obj();
__this->__construct(context);
return __this;
}
::hx::ObjectPtr< CanvasRenderer_obj > CanvasRenderer_obj::__alloc(::hx::Ctx *_hx_ctx, ::Dynamic context) {
CanvasRenderer_obj *__this = (CanvasRenderer_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(CanvasRenderer_obj), true, "openfl.display.CanvasRenderer"));
*(void **)__this = CanvasRenderer_obj::_hx_vtable;
__this->__construct(context);
return __this;
}
CanvasRenderer_obj::CanvasRenderer_obj()
{
}
void CanvasRenderer_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(CanvasRenderer);
HX_MARK_MEMBER_NAME(context,"context");
HX_MARK_MEMBER_NAME(pixelRatio,"pixelRatio");
HX_MARK_MEMBER_NAME(_hx___isDOM,"__isDOM");
HX_MARK_MEMBER_NAME(_hx___tempMatrix,"__tempMatrix");
::openfl::display::DisplayObjectRenderer_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void CanvasRenderer_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(context,"context");
HX_VISIT_MEMBER_NAME(pixelRatio,"pixelRatio");
HX_VISIT_MEMBER_NAME(_hx___isDOM,"__isDOM");
HX_VISIT_MEMBER_NAME(_hx___tempMatrix,"__tempMatrix");
::openfl::display::DisplayObjectRenderer_obj::__Visit(HX_VISIT_ARG);
}
::hx::Val CanvasRenderer_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 7:
if (HX_FIELD_EQ(inName,"context") ) { return ::hx::Val( context ); }
if (HX_FIELD_EQ(inName,"__isDOM") ) { return ::hx::Val( _hx___isDOM ); }
if (HX_FIELD_EQ(inName,"__clear") ) { return ::hx::Val( _hx___clear_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"__render") ) { return ::hx::Val( _hx___render_dyn() ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"__popMask") ) { return ::hx::Val( _hx___popMask_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"pixelRatio") ) { return ::hx::Val( pixelRatio ); }
if (HX_FIELD_EQ(inName,"__pushMask") ) { return ::hx::Val( _hx___pushMask_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"__tempMatrix") ) { return ::hx::Val( _hx___tempMatrix ); }
if (HX_FIELD_EQ(inName,"setTransform") ) { return ::hx::Val( setTransform_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"__popMaskRect") ) { return ::hx::Val( _hx___popMaskRect_dyn() ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"applySmoothing") ) { return ::hx::Val( applySmoothing_dyn() ); }
if (HX_FIELD_EQ(inName,"__pushMaskRect") ) { return ::hx::Val( _hx___pushMaskRect_dyn() ); }
if (HX_FIELD_EQ(inName,"__setBlendMode") ) { return ::hx::Val( _hx___setBlendMode_dyn() ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"__popMaskObject") ) { return ::hx::Val( _hx___popMaskObject_dyn() ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"__pushMaskObject") ) { return ::hx::Val( _hx___pushMaskObject_dyn() ); }
if (HX_FIELD_EQ(inName,"__renderDrawable") ) { return ::hx::Val( _hx___renderDrawable_dyn() ); }
break;
case 20:
if (HX_FIELD_EQ(inName,"__renderDrawableMask") ) { return ::hx::Val( _hx___renderDrawableMask_dyn() ); }
break;
case 21:
if (HX_FIELD_EQ(inName,"__setBlendModeContext") ) { return ::hx::Val( _hx___setBlendModeContext_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val CanvasRenderer_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 7:
if (HX_FIELD_EQ(inName,"context") ) { context=inValue.Cast< ::Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"__isDOM") ) { _hx___isDOM=inValue.Cast< bool >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"pixelRatio") ) { pixelRatio=inValue.Cast< Float >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"__tempMatrix") ) { _hx___tempMatrix=inValue.Cast< ::openfl::geom::Matrix >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void CanvasRenderer_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("context",ef,95,77,19));
outFields->push(HX_("pixelRatio",a5,78,12,83));
outFields->push(HX_("__isDOM",98,a9,a8,2b));
outFields->push(HX_("__tempMatrix",95,6f,cb,0f));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo CanvasRenderer_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::Dynamic */ ,(int)offsetof(CanvasRenderer_obj,context),HX_("context",ef,95,77,19)},
{::hx::fsFloat,(int)offsetof(CanvasRenderer_obj,pixelRatio),HX_("pixelRatio",a5,78,12,83)},
{::hx::fsBool,(int)offsetof(CanvasRenderer_obj,_hx___isDOM),HX_("__isDOM",98,a9,a8,2b)},
{::hx::fsObject /* ::openfl::geom::Matrix */ ,(int)offsetof(CanvasRenderer_obj,_hx___tempMatrix),HX_("__tempMatrix",95,6f,cb,0f)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *CanvasRenderer_obj_sStaticStorageInfo = 0;
#endif
static ::String CanvasRenderer_obj_sMemberFields[] = {
HX_("context",ef,95,77,19),
HX_("pixelRatio",a5,78,12,83),
HX_("__isDOM",98,a9,a8,2b),
HX_("__tempMatrix",95,6f,cb,0f),
HX_("applySmoothing",26,12,60,84),
HX_("setTransform",6a,ed,e2,69),
HX_("__clear",6d,ca,b9,b2),
HX_("__popMask",fd,b7,5f,c4),
HX_("__popMaskObject",9c,46,0d,10),
HX_("__popMaskRect",c1,73,e8,16),
HX_("__pushMask",06,e7,7f,ba),
HX_("__pushMaskObject",65,e2,3b,45),
HX_("__pushMaskRect",4a,5b,e7,a0),
HX_("__render",76,d6,58,ad),
HX_("__renderDrawable",34,e4,0f,12),
HX_("__renderDrawableMask",40,7b,d7,45),
HX_("__setBlendMode",72,27,48,51),
HX_("__setBlendModeContext",9d,48,5a,f6),
::String(null()) };
::hx::Class CanvasRenderer_obj::__mClass;
void CanvasRenderer_obj::__register()
{
CanvasRenderer_obj _hx_dummy;
CanvasRenderer_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.display.CanvasRenderer",25,88,96,c8);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(CanvasRenderer_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< CanvasRenderer_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = CanvasRenderer_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = CanvasRenderer_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void CanvasRenderer_obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_dcbf857ab860ed73_35_boot)
HXDLIN( 35) __mClass->__meta__ = ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("fields",79,8e,8e,80), ::Dynamic(::hx::Anon_obj::Create(5)
->setFixed(0,HX_("applySmoothing",26,12,60,84), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c)))))
->setFixed(1,HX_("__setBlendModeContext",9d,48,5a,f6), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c)))))
->setFixed(2,HX_("_",5f,00,00,00), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c)))))
->setFixed(3,HX_("context",ef,95,77,19), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c)))))
->setFixed(4,HX_("setTransform",6a,ed,e2,69), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:Dynamic",ce,ea,47,3c))))))));
}
}
} // end namespace openfl
} // end namespace display
| 47.28 | 266 | 0.697807 | [
"object",
"transform",
"3d"
] |
cd26fc87f4beaca2630d770b28e3fd7c5155041c | 646 | cpp | C++ | Sid's Contests/Codechef contests/Basic Problems/MinimumNoOfMoves.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Contests/Codechef contests/Basic Problems/MinimumNoOfMoves.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Contests/Codechef contests/Basic Problems/MinimumNoOfMoves.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | //OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long int t;
cin >> t;
while(t--)
{
long long int n;
cin >> n;
long long int i;
vector<long long int> a;
for(i = 0; i < n; i++)
{
long long int x;
cin >> x;
a.push_back(x);
}
long long int sum = 0;
sort(a.begin(),a.end());
for(i = 0; i < n; i++)
sum = sum + (a[i] - a[0]);
cout << sum << endl;
}
}
| 21.533333 | 65 | 0.46904 | [
"vector"
] |
cd2c23f23457cf248d4a012f48c0035512531d25 | 9,915 | cpp | C++ | driver/convrt.cpp | htran118/MD-MS-CG | 80a3104101348d1c599ecc0a1e08aec855fc70a9 | [
"MIT"
] | null | null | null | driver/convrt.cpp | htran118/MD-MS-CG | 80a3104101348d1c599ecc0a1e08aec855fc70a9 | [
"MIT"
] | null | null | null | driver/convrt.cpp | htran118/MD-MS-CG | 80a3104101348d1c599ecc0a1e08aec855fc70a9 | [
"MIT"
] | null | null | null | /****************************************************************************
* Convert trajectory files to standard ouput
* Default input file is data/trajc.trj
***************************************************************************/
#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <fstream>
#include <cmath>
#include "../libs/const.h"
#include "../libs/tlist.h"
#include "../libs/world.h"
using namespace MD;
using namespace std;
int obPtypNo(const ptype* ptyp, const tlist* typs);
int obBtypNo(const btype* btyp, const tlist* typs);
int obAtypNo(const atype* atyp, const tlist* typs);
int obDtypNo(const dtype* dtyp, const tlist* typs);
int main(int argc, char *argv[]) {
world systm;
tlist types;
const vector<partk> *parts;
char optFle[256], outFle[256], inpFle[256], format[256];
int ctrl;
FILE *pf;
cout << "This program converts the output from simula.exe to standard\n"
<< "output. Currently support LAMMPS dump format, GROMACS top and gro\n"
<< "format\n"
<< endl;
cout << "Choose the format for conversion:\n"
<< "1 for conversion from .gro, 2 for conversion to .gro,\n"
<< "3 for conversion from .top, 4 for conversion to .top,\n"
<< "5 for conversion from .dump, 6 for conversion to .dump\n"
<< endl;
cin >> ctrl;
if(argc != 3) {
cerr << "Usage:" << argv[0] << " <inpt> <outp>" << endl;
cerr << "Using default path" << endl;
if(ctrl == 3) {
strcpy(inpFle, topoFl);
strcat(inpFle, ".top");
strcpy(outFle, topoFl);
}
else if(ctrl == 6) {
strcpy(inpFle, trajFl);
strcpy(outFle, trajFl);
strcat(outFle, ".dump");
}
}
else {
strcpy(inpFle, argv[1]);
strcpy(outFle, argv[2]);
}
cout << argv[0] << " < " << inpFle << " > " << outFle << endl;
ifstream para(paraFl, ios_base::in);
types.adType(para);
para.close();
ifstream topo(topoFl, ios_base::in);
types.adType(topo);
topo.close();
ifstream strc(strcFl, ios_base::in);
systm.iniSys(strc, &types);
strc.close();
ifstream coor(coorFl, ios_base::in);
systm.iniTrj(coor);
coor.close();
parts = &(systm.obPartLs());
if(ctrl == 1) {
}
else if(ctrl == 3) {
string dummy;
vector <string> rName, pName;
vector <int> pNums, bNums, aNums, dNums;
ifstream inpt(inpFle, ios_base::in);
ifstream topo(topoFl, ios_base::in);
ofstream dump("scratch.txt", ios_base::out);
while(inpt >> dummy) {
if(dummy == ";")
inpt.ignore(256, '\n');
else if(dummy == "moleculetype") {
inpt.ignore(256, '\n');
inpt.ignore(256, '\n');
inpt >> dummy;
rName.push_back(dummy);
pNums.push_back(0);
bNums.push_back(0);
aNums.push_back(0);
dNums.push_back(0);
inpt.ignore(256, '\n');
}
}
while(!topo.eof()) {
topo.getline(format, 256);
if(strcmp(format, "END"))
dump << format << endl;
else
break;
}
}
else if(ctrl == 6) {
int duration, interval;
//Write structure/topology
ofstream file;
file.open(string(defNme) + "struc.lj");
file << "LAMMPS input file" << endl;
file << endl;
file << systm.obNpartk() << " atoms" << endl;
file << systm.obNbound() << " bonds" << endl;
file << systm.obNangle() << " angles" << endl;
file << systm.obNdihed() << " dihedrals" << endl;
file << "0 impropers" << endl;
file << endl;
file << types.obNptype() << " atom types" << endl;
if(types.obNbtype() != 0)
file << types.obNbtype() << " bond types" << endl;
if(types.obNatype() != 0)
file << types.obNatype() << " angle types" << endl;
if(types.obNdtype() != 0)
file << types.obNdtype() << " dihedral types" << endl;
file << endl;
file << "0.000 " << myVectGet(systm.obEdge(), 0)
<< " xlo xhi" << endl;
file << "0.000 " << myVectGet(systm.obEdge(), 1)
<< " ylo yhi" << endl;
file << "0.000 " << myVectGet(systm.obEdge(), 2)
<< " zlo zhi" << endl;
file << endl;
file << "Masses" << endl;
file << endl;
for(int i = 0; i < types.obNptype(); ++i)
file << (i + 1) << " " << (*(types.obPtyp(i))).obMass() << endl;
file << endl;
file << "Nonbond Coeffs" << endl;
file << endl;
for(int i = 0; i < types.obNptype(); ++i)
file << (i + 1) << " " << (*(types.obPtyp(i))).obEpsl() << " "
<< (*(types.obPtyp(i))).obRmin() << endl;
file << endl;
file << "Bond Coeffs" << endl;
file << endl;
for(int i = 0; i < types.obNbtype(); ++i)
file << (i + 1) << " " << (*(types.obBtyp(i))).obRelx() << " "
<< (*(types.obBtyp(i))).obRigd() << endl;
file << endl;
file << "Angle Coeffs" << endl;
file << endl;
for(int i = 0; i < types.obNatype(); ++i)
file << (i + 1) << " " << (*(types.obAtyp(i))).obRelx() << " "
<< (*(types.obAtyp(i))).obRigd() << endl;
file << endl;
file << "Dihedral Coeffs" << endl;
file << endl;
for(int i = 0; i < types.obNdtype(); ++i)
file << (i + 1) << " " << (*(types.obDtyp(i))).obRelx() << " "
<< (*(types.obDtyp(i))).obRig1() << " "
<< (*(types.obDtyp(i))).obRig2() << " "
<< (*(types.obDtyp(i))).obRig3() << endl;
file << endl;
file << "Atoms" << endl;
file << endl;
for(int i = 0; i < systm.obNpartk(); ++i) {
file << (i + 1) << " "
<< (*((*(systm.obPart(i))).obRsid())).obName() << " "
<< obPtypNo((*(systm.obPart(i))).obType(), &types) << " "
//<< (*(systm.obPart(i))).obChrg()
<< " ";
for(int k = 0; k < DIM; ++k)
file << myVectGet((*(systm.obPart(i))).obPost(), k) << " ";
file << endl;
}
file << endl;
file << "Velocities" << endl;
file << endl;
for(int i = 0; i < systm.obNpartk(); ++i) {
file << (i + 1) << " ";
for(int k = 0; k < DIM; ++k)
file << myVectGet((*(systm.obPart(i))).obVelo(), k) << " ";
file << endl;
}
file << endl;
file << "Bonds" << endl;
for(int i = 0; i < systm.obNbound(); ++i) {
file << (i + 1) << " "
<< (obBtypNo((*(systm.obBond(i))).obType(), &types) + 1) << " "
<< (*((*(systm.obBond(i))).obLeft())).obName() << " "
<< (*((*(systm.obBond(i))).obRigh())).obName() << endl;
}
file << endl;
file << "Angle" << endl;
file << endl;
for(int i = 0; i < systm.obNangle(); ++i) {
file << (i + 1) << " "
<< (obAtypNo((*(systm.obAngl(i))).obType(), &types) + 1) << " "
<< (*((*(systm.obAngl(i))).obLeft())).obName() << " "
<< (*((*(systm.obAngl(i))).obMidl())).obName() << " "
<< (*((*(systm.obAngl(i))).obRigh())).obName() << endl;
}
file << endl;
file << "Dihedrals" << endl;
file << endl;
for(int i = 0; i < systm.obNdihed(); ++i) {
file << (i + 1) << " "
<< (obDtypNo((*(systm.obDhed(i))).obType(), &types) + 1) << " "
<< (*((*(systm.obDhed(i))).obUppr())).obName() << " "
<< (*((*(systm.obDhed(i))).obLeft())).obName() << " "
<< (*((*(systm.obDhed(i))).obRigh())).obName() << " "
<< (*((*(systm.obDhed(i))).obLowr())).obName() << endl;
}
file << endl;
file << "Impropers" << endl;
file << endl;
file.close();
//Write trajectory
ifstream traj(inpFle, ios_base::in);
pf = fopen(outFle, "w");
systm.iniCon(traj);
systm.mkDcon(0);
traj >> duration >> interval;
for(int i = 0; i < (duration / interval); ++i) {
systm.iniTrj(traj);
fprintf(pf, "ITEM: TIMESTEP\n");
fprintf(pf, crdFmt, systm.obTime());
fprintf(pf, "\n");
fprintf(pf, "ITEM: NUMBER OF ATOMS\n");
fprintf(pf, "%-80d\n", systm.obNpartk());
fprintf(pf, "ITEM: BOX BOUNDS pp pp pp\n");
switch(systm.obBcon()) {
case 1:
strcpy(format, crdFmt);
strcat(format, crdFmt);
strcat(format, "\n");
for(int k = 0; k < DIM; ++k)
fprintf(pf, format,
0.0, myVectGet(systm.obEdge(), k));
break;
}
fprintf(pf, "ITEM: ATOMS id mol type x y z vx vy vz\n");
for(int j = 0; j < systm.obNpartk(); ++j) {
strcpy(format, sNmFmt);
strcat(format, sNmFmt);
strcat(format, sNmFmt);
fprintf(pf, format,
(((*parts).at(j)).obName()).c_str(),
((*(((*parts).at(j)).obRsid())).obName()).c_str(),
(((*parts).at(j)).obMark()).c_str());
for(int k = 0; k < DIM; ++k)
fprintf(pf, crdFmt, myVectGet(((*parts).at(j)).obPost(), k));
for(int k = 0; k < DIM; ++k)
fprintf(pf, crdFmt, myVectGet(((*parts).at(j)).obVelo(), k));
fprintf(pf, "\n");
}
}
}
return 0;
}
int obPtypNo(const ptype* ptyp, const tlist* typs) {
const vector<ptype>* ptyps = &((*typs).obPtypLs());
for(int i = 0; i < (*typs).obNptype(); i++)
if((*ptyps).at(i) == (*ptyp))
return i;
cerr << "Cannot find ptype" << endl;
}
int obBtypNo(const btype* btyp, const tlist* typs) {
const vector<btype>* btyps = &((*typs).obBtypLs());
for(int i = 0; i < (*typs).obNbtype(); i++)
if((*btyps).at(i) == (*btyp))
return i;
cerr << "Cannot find btype" << endl;
}
int obAtypNo(const atype* atyp, const tlist* typs) {
const vector<atype>* atyps = &((*typs).obAtypLs());
for(int i = 0; i < (*typs).obNatype(); i++)
if((*atyps).at(i) == (*atyp))
return i;
cerr << "Cannot find atype" << endl;
}
int obDtypNo(const dtype* dtyp, const tlist* typs) {
const vector<dtype>* dtyps = &((*typs).obDtypLs());
for(int i = 0; i < (*typs).obNdtype(); i++)
if((*dtyps).at(i) == (*dtyp))
return i;
cerr << "Cannot find dtype" << endl;
}
| 32.831126 | 79 | 0.494402 | [
"vector"
] |
cd2eae0a6367c1489305126c3c34e6fc3a37b7ae | 561 | cpp | C++ | leetcode/84. Largest Rectangle in Histogram/s1.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | 1 | 2021-02-09T11:38:51.000Z | 2021-02-09T11:38:51.000Z | leetcode/84. Largest Rectangle in Histogram/s1.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | null | null | null | leetcode/84. Largest Rectangle in Histogram/s1.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | null | null | null | class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> index;
int maxArea = 0;
heights.push_back(0);
for (int i = 0; i < heights.size(); ++i) {
while (!index.empty() && heights[index.top()] >= heights[i]) {
int h = heights[index.top()];
index.pop();
int j = index.size() > 0 ? index.top() : -1;
maxArea = max(maxArea, h * (i - j - 1));
}
index.push(i);
}
return maxArea;
}
}; | 31.166667 | 74 | 0.449198 | [
"vector"
] |
cd3148ba4073a1a3eb8e6065b7e1a22b796fe7a4 | 1,527 | cpp | C++ | src/UI/src/presenter.cpp | TTitcombe/Casset | 5f15eb65f5eece1761f857e995a8f68084012125 | [
"BSD-2-Clause"
] | null | null | null | src/UI/src/presenter.cpp | TTitcombe/Casset | 5f15eb65f5eece1761f857e995a8f68084012125 | [
"BSD-2-Clause"
] | 44 | 2019-02-13T14:49:37.000Z | 2019-08-02T08:15:05.000Z | src/UI/src/presenter.cpp | TTitcombe/Casset | 5f15eb65f5eece1761f857e995a8f68084012125 | [
"BSD-2-Clause"
] | null | null | null | #include "../hdr/presenter.h"
#include "../../API/hdr/stockinfo.h"
#include <algorithm>
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include <regex>
using json = nlohmann::json;
namespace UI {
Presenter::Presenter(MainWindow *v) : m_view(v) {
QObject::connect(m_view, SIGNAL(ViewButtonClicked()), this, SLOT(onViewButtonClicked()));
try {
m_logger = spdlog::stderr_color_mt("PRESENTER_LOG");
} catch (spdlog::spdlog_ex) {
m_logger = spdlog::get("PRESENTER_LOG");
}
}
void Presenter::onViewButtonClicked() {
std::string symbol = m_view->getSymbol();
// Stock symbols can only be 4 characters at most
if (symbol.length() > 4) {
const std::string message = fmt::format("{} is too long for a stock symbol", symbol);
m_view->updateStockMessage(message);
return;
}
// Stock symbols contain alphabetical characters only
if (!std::regex_match(symbol, std::regex("^[A-Za-z]+$"))) {
const std::string message = fmt::format("{} contains not alphabetical characters", symbol);
m_view->updateStockMessage(message);
return;
}
// Stock symbols are uppercase
std::transform(symbol.begin(), symbol.end(),symbol.begin(), ::toupper);
if (m_iex.isValidSymbol(symbol)) {
const json chart = m_iex.getChart(symbol);
StockInfo stock(symbol, chart);
m_view->updateStockMessage(stock.getStockReport());
} else {
const std::string message = fmt::format("{} was not a recognised stock symbol", symbol);
m_view->updateStockMessage(message);
}
}
} // UI
| 31.163265 | 95 | 0.682384 | [
"transform"
] |
cd39ae5ea3af1e5244f894216f9fba66ecdf6261 | 8,386 | hpp | C++ | library/include/borealis/core/box.hpp | FaultyPine/borealis | 6053f78ec2eec829b4d9c9330cf3b5d591a7bfa2 | [
"Apache-2.0"
] | 188 | 2020-06-17T12:23:21.000Z | 2022-03-28T15:52:36.000Z | library/include/borealis/core/box.hpp | GLIKCH/borealis | 20e2d33b6c4ffce139ce304c503c04f5b94da920 | [
"Apache-2.0"
] | 132 | 2020-06-17T18:03:42.000Z | 2021-12-25T00:21:30.000Z | library/include/borealis/core/box.hpp | GLIKCH/borealis | 20e2d33b6c4ffce139ce304c503c04f5b94da920 | [
"Apache-2.0"
] | 54 | 2020-06-18T05:11:41.000Z | 2022-03-12T23:47:29.000Z | /*
Copyright 2020-2021 natinusala
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.
*/
#pragma once
#include <borealis/core/view.hpp>
namespace brls
{
enum class JustifyContent
{
FLEX_START,
CENTER,
FLEX_END,
SPACE_BETWEEN,
SPACE_AROUND,
SPACE_EVENLY,
};
enum class AlignItems
{
AUTO,
FLEX_START,
CENTER,
FLEX_END,
STRETCH,
BASELINE,
SPACE_BETWEEN,
SPACE_AROUND,
};
enum class Axis
{
ROW,
COLUMN,
};
enum class Direction
{
INHERIT,
LEFT_TO_RIGHT,
RIGHT_TO_LEFT,
};
// Generic FlexBox layout
class Box : public View
{
public:
Box(Axis flexDirection);
Box();
void draw(NVGcontext* vg, float x, float y, float width, float height, Style style, FrameContext* ctx) override;
View* getDefaultFocus() override;
View* getNextFocus(FocusDirection direction, View* currentView) override;
void willAppear(bool resetState) override;
void willDisappear(bool resetState) override;
void onWindowSizeChanged() override;
void onFocusGained() override;
void onFocusLost() override;
void onParentFocusGained(View* focusedView) override;
void onParentFocusLost(View* focusedView) override;
bool applyXMLAttribute(std::string name, std::string value) override;
static View* create();
/**
* Adds a view to this Box.
* Returns the position the view was added at.
*/
virtual void addView(View* view);
/**
* Adds a view to this Box at the given position.
* Returns the position the view was added at.
*/
virtual void addView(View* view, size_t position);
/**
* Removes the given view from the Box. It will be freed.
*/
virtual void removeView(View* view);
/**
* Sets the padding of the view, aka the internal space to give
* between this view boundaries and its children.
*
* Only does one layout pass instead of four when using the four methods separately.
*/
virtual void setPadding(float padding);
/**
* Sets the padding of the view, aka the internal space to give
* between this view boundaries and its children.
*
* Only does one layout pass instead of four when using the four methods separately.
*/
virtual void setPadding(float top, float right, float bottom, float left);
/**
* Sets the padding of the view, aka the internal space to give
* between this view boundaries and its children.
*/
virtual void setPaddingTop(float top);
/**
* Sets the padding of the view, aka the internal space to give
* between this view boundaries and its children.
*/
virtual void setPaddingRight(float right);
/**
* Sets the padding of the view, aka the internal space to give
* between this view boundaries and its children.
*/
virtual void setPaddingBottom(float bottom);
/**
* Sets the padding of the view, aka the internal space to give
* between this view boundaries and its children.
*/
virtual void setPaddingLeft(float left);
/**
* Sets the children alignment along the Box axis.
*
* Default is FLEX_START.
*/
void setJustifyContent(JustifyContent justify);
/**
* Sets the children alignment along the Box cross axis.
*
* Default is AUTO.
*/
void setAlignItems(AlignItems alignment);
/**
* Sets the direction of the box, aka place the views
* left to right or right to left (flips the children).
*
* Default is INHERIT.
*/
void setDirection(Direction direction);
void setAxis(Axis axis);
std::vector<View*>& getChildren();
/**
* Returns the bounds used for culling children.
*/
virtual void getCullingBounds(float* top, float* right, float* bottom, float* left);
/**
* Registers an XML attribute to be forwarded to the given view. Works regardless of the target attribute type.
* Useful to expose attributes of children views in the parent box without copy pasting them individually.
*
* The forwarded attribute value will override the value of the regular attribute if it already exists in the target view.
*/
void forwardXMLAttribute(std::string attributeName, View* target);
/**
* Registers an XML attribute to be forwarded to the given view, while changing the target attribute name.
* Works regardless of the target attribute type.
* Useful to expose attributes of children views in the parent box without copy pasting them individually, but with a different name.
*
* The forwarded attribute value will override the value of the regular attribute if it already exists in the target view.
*/
void forwardXMLAttribute(std::string attributeName, View* target, std::string targetAttributeName);
/**
* Fired when focus is gained on one of this view's children, or one of the children
* of the children...
*
* directChild is guaranteed to be one of your children. It may not be the view that has been
* focused.
*
* If focusedView == directChild, then the child of yours has been focused.
* Otherwise, focusedView is a child of directChild.
*/
virtual void onChildFocusGained(View* directChild, View* focusedView);
/**
* Fired when focus is lost on one of this view's children. Works similarly to
* onChildFocusGained().
*/
virtual void onChildFocusLost(View* directChild, View* focusedView);
View* getView(std::string id) override;
private:
Axis axis;
std::vector<View*> children;
size_t defaultFocusedIndex = 0;
std::unordered_map<std::string, std::pair<std::string, View*>> forwardedAttributes;
protected:
/**
* Inflates the Box with the given XML string.
*
* The root element MUST be a brls::Box, corresponding to the inflated Box itself. Its
* attributes will be applied to the Box.
*
* Each child node in the root brls::Box will be treated as a view and added
* as a child of the Box.
*/
void inflateFromXMLString(std::string xml);
/**
* Inflates the Box with the given XML element.
*
* The root element MUST be a brls::Box, corresponding to the inflated Box itself. Its
* attributes will be applied to the Box.
*
* Each child node in the root brls::Box will be treated as a view and added
* as a child of the Box.
*/
void inflateFromXMLElement(tinyxml2::XMLElement* element);
/**
* Inflates the Box with the given XML resource.
*
* The root element MUST be a brls::Box, corresponding to the inflated Box itself. Its
* attributes will be applied to the Box.
*
* Each child node in the root brls::Box will be treated as a view and added
* as a child of the Box.
*/
void inflateFromXMLRes(std::string res);
/**
* Inflates the Box with the given XML file path.
*
* The root element MUST be a brls::Box, corresponding to the inflated Box itself. Its
* attributes will be applied to the Box.
*
* Each child node in the root brls::Box will be treated as a view and added
* as a child of the Box.
*/
void inflateFromXMLFile(std::string path);
/**
* Handles a child XML element.
*
* By default, calls createFromXMLElement() and adds the result
* to the children of the Box.
*/
void handleXMLElement(tinyxml2::XMLElement* element) override;
};
// An empty view that has auto x auto and grow=1.0 to push
// all the next views in its box to the right (or to the bottom)
class Padding : public View
{
public:
Padding();
void draw(NVGcontext* vg, float x, float y, float width, float height, Style style, FrameContext* ctx) override;
static View* create();
};
} // namespace brls
| 29.843416 | 137 | 0.671715 | [
"vector"
] |
cd3c23022b16ecbe26024d655e5ddc8ad644ff88 | 4,812 | cpp | C++ | interprocess/acceptor.cpp | bitdewy/interprocess | c21a96105ca969635a35489eb77e80037725c4e4 | [
"BSL-1.0"
] | 1 | 2021-05-05T18:54:39.000Z | 2021-05-05T18:54:39.000Z | interprocess/acceptor.cpp | bitdewy/interprocess | c21a96105ca969635a35489eb77e80037725c4e4 | [
"BSL-1.0"
] | null | null | null | interprocess/acceptor.cpp | bitdewy/interprocess | c21a96105ca969635a35489eb77e80037725c4e4 | [
"BSL-1.0"
] | 1 | 2021-05-05T18:54:40.000Z | 2021-05-05T18:54:40.000Z | // Copyright 2014, bitdewy@gmail.com
// Distributed under the Boost Software License, Version 1.0.
// You may obtain a copy of the License at
//
// http://www.boost.org/LICENSE_1_0.txt
#include "interprocess/acceptor.h"
#include <windows.h>
#include <string>
namespace interprocess {
Acceptor::Acceptor(const std::string& endpoint)
: pipe_name_(std::string("\\\\.\\pipe\\").append(endpoint)),
next_pipe_(NULL),
close_event_(CreateEvent(NULL, FALSE, FALSE, NULL)) {
ZeroMemory(&connect_overlap_, sizeof connect_overlap_);
pendding_function_map_.insert(
std::make_pair(ERROR_IO_PENDING, [] { return true; }));
pendding_function_map_.insert(std::make_pair(ERROR_PIPE_CONNECTED, [this] {
if (!SetEvent(connect_overlap_.hEvent)) {
raise_exception();
}
return false;
}));
}
Acceptor::~Acceptor() {
Stop();
}
void Acceptor::Listen() {
listen_thread_.swap(std::thread(std::bind(&Acceptor::ListenInThread, this)));
}
void Acceptor::Stop() {
SetEvent(close_event_.get());
DisconnectNamedPipe(next_pipe_.get());
if (listen_thread_.joinable()) {
listen_thread_.join();
}
}
void Acceptor::SetNewConnectionCallback(const NewConnectionCallback& cb) {
new_connection_callback_ = cb;
}
void Acceptor::SetExceptionCallback(const ExceptionCallback& cb) {
exception_callback_ = cb;
}
void Acceptor::MoveAsyncIOFunctionToAlertableThread(
const std::function<void()>& cb) {
async_io_callback_ = cb;
}
void Acceptor::MoveWaitResponseIOFunctionToAlertableThread(
const std::function<void()>& cb) {
async_wait_io_callback_ = cb;
}
void Acceptor::ListenInThread() {
std::exception_ptr eptr;
try {
SECURITY_CREATE_EVENT(conn_event, TRUE, TRUE);
SECURITY_CREATE_EVENT(post_event, FALSE, FALSE);
SECURITY_CREATE_EVENT(send_event, FALSE, FALSE);
HANDLE events[4] = {
conn_event, post_event, send_event, close_event_.get()
};
connect_overlap_.hEvent = conn_event;
bool pendding = CreateConnectInstance();
while (true) {
auto wait = WaitForMultipleObjectsEx(
3,
events, // events object to wait for
FALSE, // wait any one
INFINITE, // wait indefinitely
TRUE); // alertable wait enabled
switch (wait) {
case WAIT_OBJECT_0:
// If an operation is pending, get the result of the
// connect operation.
if (pendding) {
raise_exception_if([&, this]() {
DWORD ret = 0;
return !GetOverlappedResult(
next_pipe_.get(), // pipe handle
&connect_overlap_, // OVERLAPPED structure
&ret, // bytes transferred
FALSE); // does not wait
});
}
call_if_exist(
new_connection_callback_,
next_pipe_.get(),
post_event,
send_event);
pendding = CreateConnectInstance();
break;
// Send operation pendding
case WAIT_OBJECT_0 + 1:
call_if_exist(async_io_callback_);
break;
case WAIT_OBJECT_0 + 2:
call_if_exist(async_wait_io_callback_);
break;
case WAIT_OBJECT_0 + 3:
return;
// The wait is satisfied by a completed read or write
// operation. This allows the system to execute the
// completion routine.
case WAIT_IO_COMPLETION:
break;
// An error occurred in the wait function.
default:
raise_exception();
}
}
} catch (...) {
eptr = std::current_exception();
}
call_if_exist(exception_callback_, eptr);
}
bool Acceptor::CreateConnectInstance() {
next_pipe_.reset(CreateNamedPipe(
pipe_name_.c_str(), // pipe name
PIPE_ACCESS_DUPLEX | // read/write access
FILE_FLAG_OVERLAPPED, // overlapped mode
PIPE_TYPE_MESSAGE | // message-type pipe
PIPE_READMODE_MESSAGE | // message read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // unlimited instances
kBufferSize, // output buffer size
kBufferSize, // input buffer size
kTimeout, // client time-out
NULL)); // default security attributes
raise_exception_if([this]() {
return next_pipe_.get() == INVALID_HANDLE_VALUE;
});
// Overlapped ConnectNamedPipe should return zero.
raise_exception_if([this]() {
return ConnectNamedPipe(next_pipe_.get(), &connect_overlap_);
});
return Pendding(GetLastError());
}
bool Acceptor::Pendding(int err) {
auto it = pendding_function_map_.find(err);
if (it != pendding_function_map_.end()) {
return it->second();
} else {
raise_exception();
return false;
}
}
} // namespace interprocess
| 27.815029 | 79 | 0.636949 | [
"object"
] |
cd3f9e978fe84342a329fa744861daa6ef8be7b2 | 13,900 | cpp | C++ | DemoApps/GLES3/FurShellRendering/source/OptionParser.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 3 | 2019-01-19T20:21:24.000Z | 2021-08-10T02:11:32.000Z | DemoApps/GLES3/FurShellRendering/source/OptionParser.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoApps/GLES3/FurShellRendering/source/OptionParser.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2021-08-10T02:11:33.000Z | 2021-08-10T02:11:33.000Z | /****************************************************************************************************************************************************
* Copyright (c) 2014 Freescale Semiconductor, 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 Freescale Semiconductor, Inc. nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************************************************************************************/
#include "OptionParser.hpp"
#include <FslBase/BasicTypes.hpp>
#include <FslBase/Log/Log.hpp>
#include <FslBase/Math/MathHelper.hpp>
#include <FslBase/String/StringParseUtil.hpp>
#include <FslBase/Getopt/OptionBaseValues.hpp>
#include <FslBase/Exceptions.hpp>
#include <algorithm>
#include <cmath>
#include <cstring>
namespace Fsl
{
namespace
{
struct CommandId
{
enum Enum
{
RenderMode = DEMO_APP_OPTION_BASE,
LayerCount,
HairLength,
HairDensity,
FurTextureSize,
TorusMajorSegments,
TorusMinorSegments,
UseTriangleStrips,
ShowNormals,
TextureRepeatCountX,
TextureRepeatCountY,
HighShaderPrecision,
Lights,
ForceFinish,
Demo,
Quality,
BackgroundColor
};
};
}
OptionParser::OptionParser()
: m_config()
, m_modified()
, m_quality(Quality::Low)
{
}
OptionParser::~OptionParser()
{
}
void OptionParser::OnArgumentSetup(std::deque<Option>& rOptions)
{
rOptions.push_back(Option("RenderMode", OptionArgument::OptionRequired, CommandId::RenderMode, "The render mode: 0=Multi-pass, 1=Multi-pass VB, 2=OldSchool instancing, 3=ES3 instancing (default)."));
rOptions.push_back(Option("LayerCount", OptionArgument::OptionRequired, CommandId::LayerCount, "The number of layers to use for rendering the fur"));
rOptions.push_back(Option("HairLength", OptionArgument::OptionRequired, CommandId::HairLength, "The length of the hairs"));
rOptions.push_back(Option("HairDensity", OptionArgument::OptionRequired, CommandId::HairDensity, "The hair density"));
rOptions.push_back(Option("FurTextureSize", OptionArgument::OptionRequired, CommandId::FurTextureSize, "This controls the resolution of the fur density texture, applied on both axis"));
rOptions.push_back(Option("TorusMajorSegments", OptionArgument::OptionRequired, CommandId::TorusMajorSegments, "..."));
rOptions.push_back(Option("TorusMinorSegments", OptionArgument::OptionRequired, CommandId::TorusMinorSegments, "..."));
rOptions.push_back(Option("UseTriangleStrip", OptionArgument::OptionRequired, CommandId::UseTriangleStrips, "Use triangle strips if true, triangle lists if false"));
rOptions.push_back(Option("ShowNormals", OptionArgument::OptionRequired, CommandId::ShowNormals, "Render the normals"));
rOptions.push_back(Option("TextureRepeatCountX", OptionArgument::OptionRequired, CommandId::TextureRepeatCountX, "Controls the amount of times we show the texture in the x direction (1=once, 2=twice)"));
rOptions.push_back(Option("TextureRepeatCountY", OptionArgument::OptionRequired, CommandId::TextureRepeatCountY, "Controls the amount of times we show the texture in the y direction (1=once, 2=twice)"));
rOptions.push_back(Option("HighShaderPrecision", OptionArgument::OptionRequired, CommandId::HighShaderPrecision, "Shader arithmetic precision. \nfalse = low, \ntrue = high"));
rOptions.push_back(Option("Lights", OptionArgument::OptionRequired, CommandId::Lights, "number of light sources used in fragment shader calculations"));
rOptions.push_back(Option("ForceFinish", OptionArgument::OptionRequired, CommandId::ForceFinish, "If true each frame will execute a glFinish call"));
rOptions.push_back(Option("Demo", OptionArgument::OptionRequired, CommandId::Demo, "Select the demo to run (0 to 3)"));
rOptions.push_back(Option("Quality", OptionArgument::OptionRequired, CommandId::Quality, "Select the rendering quality (low,medium,high)."));
rOptions.push_back(Option("BackgroundColor", OptionArgument::OptionRequired, CommandId::BackgroundColor, "Set the background color 0xRRGGBB (use decimal values)."));
}
OptionParseResult::Enum OptionParser::OnParse(const int32_t cmdId, const char*const pszOptArg)
{
bool boolValue;
int intValue;
uint32_t uint32Value;
float floatValue;
switch (cmdId)
{
case CommandId::RenderMode:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetRenderMode((RenderMode::Enum)intValue);
return OptionParseResult::Parsed;
case CommandId::LayerCount:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetLayerCount(intValue);
m_modified.Flag(ModifiedFlags::LayerCount);
return OptionParseResult::Parsed;
case CommandId::HairLength:
if (StringParseUtil::Parse(floatValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetHairLength(floatValue);
m_modified.Flag(ModifiedFlags::HairLength);
return OptionParseResult::Parsed;
case CommandId::HairDensity:
if (StringParseUtil::Parse(floatValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetHairDensity(floatValue);
return OptionParseResult::Parsed;
case CommandId::FurTextureSize:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
if (intValue < 0 || intValue >= std::numeric_limits<uint16_t>::max())
throw std::invalid_argument("Texture resolution out of range");
m_config.SetFurTextureDimensions(intValue);
m_modified.Flag(ModifiedFlags::FurTextureDimension);
return OptionParseResult::Parsed;
case CommandId::TorusMajorSegments:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetTorusMajorSegments(intValue);
m_modified.Flag(ModifiedFlags::TorusMajor);
return OptionParseResult::Parsed;
case CommandId::TorusMinorSegments:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetTorusMinorSegments(intValue);
m_modified.Flag(ModifiedFlags::TorusMinor);
return OptionParseResult::Parsed;
case CommandId::UseTriangleStrips:
if (StringParseUtil::Parse(boolValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetUseTriangleStrip(boolValue);
return OptionParseResult::Parsed;
case CommandId::ShowNormals:
if (StringParseUtil::Parse(boolValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetShowNormals(boolValue);
return OptionParseResult::Parsed;
case CommandId::TextureRepeatCountX:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetTextureRepeatCountX(intValue);
m_modified.Flag(ModifiedFlags::TextureRepeatX);
return OptionParseResult::Parsed;
case CommandId::TextureRepeatCountY:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetTextureRepeatCountY(intValue);
m_modified.Flag(ModifiedFlags::TextureRepeatY);
return OptionParseResult::Parsed;
case CommandId::HighShaderPrecision:
if (StringParseUtil::Parse(boolValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetUseHighShaderPrecision(boolValue);
return OptionParseResult::Parsed;
case CommandId::Lights:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetLightCount(intValue);
return OptionParseResult::Parsed;
case CommandId::ForceFinish:
if (StringParseUtil::Parse(boolValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetForceFinishEachFrame(boolValue);
return OptionParseResult::Parsed;
case CommandId::BackgroundColor:
if (StringParseUtil::Parse(uint32Value, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetBackgroundColor(uint32Value);
m_modified.Flag(ModifiedFlags::BackgroundColor);
return OptionParseResult::Parsed;
case CommandId::Demo:
if (StringParseUtil::Parse(intValue, pszOptArg) <= 0)
return OptionParseResult::Failed;
m_config.SetDemoId(intValue);
return OptionParseResult::Parsed;
case CommandId::Quality:
if (strcmp(pszOptArg, "low") == 0)
m_quality = Quality::Low;
else if (strcmp(pszOptArg, "medium") == 0)
m_quality = Quality::Medium;
else if (strcmp(pszOptArg, "high") == 0)
m_quality = Quality::High;
else
return OptionParseResult::Failed;
return OptionParseResult::Parsed;
default:
return OptionParseResult::NotHandled;
}
}
bool OptionParser::OnParsingComplete()
{
switch (m_quality)
{
case Quality::Low:
if (!m_modified.IsFlagged(ModifiedFlags::LayerCount))
m_config.SetLayerCount(10);
if (!m_modified.IsFlagged(ModifiedFlags::FurTextureDimension))
{
if (m_config.GetDemoId() != 0 && m_config.GetDemoId() != 3)
m_config.SetFurTextureDimensions(Point2(512, 512));
else
m_config.SetFurTextureDimensions(Point2(1024, 512));
}
if (!m_modified.IsFlagged(ModifiedFlags::TextureRepeatX))
m_config.SetTextureRepeatCountX(1);
if (!m_modified.IsFlagged(ModifiedFlags::TextureRepeatY))
m_config.SetTextureRepeatCountY(1);
if (!m_modified.IsFlagged(ModifiedFlags::HairLength))
m_config.SetHairLength(2.0f);
if (!m_modified.IsFlagged(ModifiedFlags::TorusMajor))
m_config.SetTorusMajorSegments(64);
if (!m_modified.IsFlagged(ModifiedFlags::TorusMinor))
m_config.SetTorusMinorSegments(64);
if (m_config.GetDemoId() == 0 && !m_modified.IsFlagged(ModifiedFlags::BackgroundColor))
m_config.SetBackgroundColor(0xFF000000);
break;
case Quality::Medium:
if (!m_modified.IsFlagged(ModifiedFlags::LayerCount))
m_config.SetLayerCount(20);
if (!m_modified.IsFlagged(ModifiedFlags::FurTextureDimension))
{
if (m_config.GetDemoId() != 0 && m_config.GetDemoId() != 3)
m_config.SetFurTextureDimensions(Point2(1024, 1024));
else
m_config.SetFurTextureDimensions(Point2(1024, 512));
}
if (!m_modified.IsFlagged(ModifiedFlags::TextureRepeatX))
m_config.SetTextureRepeatCountX(1);
if (!m_modified.IsFlagged(ModifiedFlags::TextureRepeatY))
m_config.SetTextureRepeatCountY(1);
if (!m_modified.IsFlagged(ModifiedFlags::HairLength))
m_config.SetHairLength(4.0f);
if (!m_modified.IsFlagged(ModifiedFlags::TorusMajor))
m_config.SetTorusMajorSegments(64);
if (!m_modified.IsFlagged(ModifiedFlags::TorusMinor))
m_config.SetTorusMinorSegments(64);
if (m_config.GetDemoId() == 0 && !m_modified.IsFlagged(ModifiedFlags::BackgroundColor))
m_config.SetBackgroundColor(0xFF000000);
break;
case Quality::High:
if (!m_modified.IsFlagged(ModifiedFlags::LayerCount))
m_config.SetLayerCount(40);
if (!m_modified.IsFlagged(ModifiedFlags::FurTextureDimension))
{
if (m_config.GetDemoId() != 0 && m_config.GetDemoId() != 3)
m_config.SetFurTextureDimensions(Point2(1024, 1024));
else
m_config.SetFurTextureDimensions(Point2(1024, 512));
}
if (!m_modified.IsFlagged(ModifiedFlags::TextureRepeatX))
m_config.SetTextureRepeatCountX(1);
if (!m_modified.IsFlagged(ModifiedFlags::TextureRepeatY))
m_config.SetTextureRepeatCountY(1);
if (!m_modified.IsFlagged(ModifiedFlags::HairLength))
m_config.SetHairLength(4.0f);
if (!m_modified.IsFlagged(ModifiedFlags::TorusMajor))
m_config.SetTorusMajorSegments(64);
if (!m_modified.IsFlagged(ModifiedFlags::TorusMinor))
m_config.SetTorusMinorSegments(64);
if (m_config.GetDemoId() == 0 && !m_modified.IsFlagged(ModifiedFlags::BackgroundColor))
m_config.SetBackgroundColor(0xFF000000);
break;
default:
break;
}
// If you return false, the app exits.
return true;
}
}
| 45.12987 | 207 | 0.70036 | [
"render"
] |
cd407b41482906f5405891127e9b264f6e90c482 | 2,695 | cpp | C++ | src/LeviathanModelViewer/mainwindow.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | 3 | 2019-03-05T13:05:30.000Z | 2019-12-16T05:56:21.000Z | src/LeviathanModelViewer/mainwindow.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | src/LeviathanModelViewer/mainwindow.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | #include <QFileDialog>
#include <QGridLayout>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qevent.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_pLevStruct(nullptr)
{
ui->setupUi(this);
// Register
connect(ui->actionLoad_MeshFile, SIGNAL(triggered(bool)), this, SLOT(LoadMeshFile()));
connect(ui->actionLoad_PointCloud, SIGNAL(triggered(bool)), this, SLOT(LoadPointCloudFile()));
connect(ui->openGLWidget, SIGNAL(resized()), this, SLOT(OpenglWidgetResize()));
m_updateTimer.setInterval(200);
connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(Update()));
m_updateTimer.start();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::LoadMeshFile()
{
QString path = QFileDialog::getOpenFileName(this,QString("Select mesh file"), QString("."), QString("Mesh file(*.*)"));
if (path.length() == 0) return;
_controller().LoadMeshFile(path.toStdString().c_str());
}
void MainWindow::LoadPointCloudFile()
{
QString path = QFileDialog::getOpenFileName(this, QString("Select point cloud file"), QString("."), QString("Mesh file(*.*)"));
if (path.length() == 0) return;
_controller().LoadPointCloudFile(path.toStdString().c_str());
}
void MainWindow::resizeEvent(QResizeEvent * event)
{
static bool bFirstEvent = true;
if (bFirstEvent)
{
_initialized();
m_pLevStruct.reset(new LeviathanInitStruct);
m_pLevStruct->parentHandle = ui->openGLWidget->winId();
m_pLevStruct->width = event->size().width();
m_pLevStruct->height = event->size().height();
_runRenderService();
bFirstEvent = false;
}
QWidget::resizeEvent(event);
}
void MainWindow::_pushTask(std::function<void()> task)
{
m_taskLock.lock();
m_tasks.push_back(task);
m_taskLock.unlock();
}
void MainWindow::_processTask()
{
m_taskLock.lock();
for (auto& task : m_tasks)
{
task();
}
m_tasks.clear();
m_taskLock.unlock();
}
void MainWindow::_initialized()
{
}
void MainWindow::_runRenderService()
{
std::thread renderThread([this]()
{
_controller().Init(m_pLevStruct->width, m_pLevStruct->height, m_pLevStruct->parentHandle);
_controller().Run();
});
renderThread.detach();
}
void MainWindow::OpenglWidgetResize()
{
auto _task = [this]()
{
HWND handle = (HWND)_controller().GetWindowHandle();
if (!handle) return;
int width = ui->openGLWidget->width();
int height = ui->openGLWidget->height();
MoveWindow(handle, 0, 0, width, height, true);
};
_pushTask(_task);
}
void MainWindow::Update()
{
if (_controller().GetCurrentAppState() >= Leviathan::EAS_RUNNING)
{
_processTask();
}
}
IController& MainWindow::_controller()
{
return ModelViewerPresenter::Instance();
}
| 21.388889 | 128 | 0.703154 | [
"mesh"
] |
cd45d5f9e7680b06de14ea4a3fb18d38abf659af | 489 | cpp | C++ | leetcode_solutions/MaximumSubarray.cpp | senlinzhan/experiments | f3983da0bb5080db900021b7473295262df68af8 | [
"MIT"
] | null | null | null | leetcode_solutions/MaximumSubarray.cpp | senlinzhan/experiments | f3983da0bb5080db900021b7473295262df68af8 | [
"MIT"
] | null | null | null | leetcode_solutions/MaximumSubarray.cpp | senlinzhan/experiments | f3983da0bb5080db900021b7473295262df68af8 | [
"MIT"
] | null | null | null | class Solution {
public:
int maxSubArray( const vector<int> &nums )
{
if( nums.empty() ) {
return 0;
}
vector<int> values( nums.size(), 0 );
int maxValue = nums[0];
values[0] = nums[0];
for( int i = 1; i < nums.size(); ++i )
{
values[i] = std::max( values[i - 1] + nums[i], nums[i] );
maxValue = std::max( maxValue, values[i] );
}
return maxValue;
}
};
| 22.227273 | 69 | 0.435583 | [
"vector"
] |
cd4e7a839fcb8b6e5beb49f0e85144a8e561b208 | 2,301 | cpp | C++ | Engine/Source/Developer/AssetTools/Private/AssetTypeActions/AssetTypeActions_TextureRenderTarget.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Developer/AssetTools/Private/AssetTypeActions/AssetTypeActions_TextureRenderTarget.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Developer/AssetTools/Private/AssetTypeActions/AssetTypeActions_TextureRenderTarget.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "AssetTypeActions/AssetTypeActions_TextureRenderTarget.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "Engine/Texture2D.h"
#include "EditorStyleSet.h"
#include "Engine/TextureCube.h"
#include "Engine/TextureRenderTarget2D.h"
#include "Engine/TextureRenderTargetCube.h"
#include "AssetRegistryModule.h"
#define LOCTEXT_NAMESPACE "AssetTypeActions"
void FAssetTypeActions_TextureRenderTarget::GetActions( const TArray<UObject*>& InObjects, FMenuBuilder& MenuBuilder )
{
FAssetTypeActions_Texture::GetActions(InObjects, MenuBuilder);
auto RenderTargets = GetTypedWeakObjectPtrs<UTextureRenderTarget>(InObjects);
MenuBuilder.AddMenuEntry(
LOCTEXT("TextureRenderTarget_CreateStatic", "Create Static Texture"),
LOCTEXT("TextureRenderTarget_CreateStaticTooltip", "Creates a static texture from the selected render targets."),
FSlateIcon(FEditorStyle::GetStyleSetName(), "ClassIcon.Texture2D"),
FUIAction(
FExecuteAction::CreateSP( this, &FAssetTypeActions_TextureRenderTarget::ExecuteCreateStatic, RenderTargets ),
FCanExecuteAction()
)
);
}
void FAssetTypeActions_TextureRenderTarget::ExecuteCreateStatic(TArray<TWeakObjectPtr<UTextureRenderTarget>> Objects)
{
for (auto ObjIt = Objects.CreateConstIterator(); ObjIt; ++ObjIt)
{
auto Object = (*ObjIt).Get();
if ( Object )
{
FString Name;
FString PackageName;
CreateUniqueAssetName(Object->GetOutermost()->GetName(), TEXT("_Tex"), PackageName, Name);
UObject* NewObj = NULL;
UTextureRenderTarget2D* TexRT = Cast<UTextureRenderTarget2D>(Object);
UTextureRenderTargetCube* TexRTCube = Cast<UTextureRenderTargetCube>(Object);
if( TexRTCube )
{
// create a static cube texture as well as its 6 faces
NewObj = TexRTCube->ConstructTextureCube( CreatePackage(NULL,*PackageName), Name, Object->GetMaskedFlags() );
}
else if( TexRT )
{
// create a static 2d texture
NewObj = TexRT->ConstructTexture2D( CreatePackage(NULL,*PackageName), Name, Object->GetMaskedFlags(), CTF_Default, NULL );
}
if( NewObj )
{
// package needs saving
NewObj->MarkPackageDirty();
// Notify the asset registry
FAssetRegistryModule::AssetCreated(NewObj);
}
}
}
}
#undef LOCTEXT_NAMESPACE
| 33.347826 | 126 | 0.760539 | [
"render",
"object"
] |
cd510219344a98a88e2e6519611c0f1bb1cdd211 | 2,583 | cpp | C++ | Application/src/contactsworker.cpp | DavidRomanovizc/adressbook | d03448d6ccb563e9403dc63d31c3a6df1539b7b9 | [
"MIT"
] | null | null | null | Application/src/contactsworker.cpp | DavidRomanovizc/adressbook | d03448d6ccb563e9403dc63d31c3a6df1539b7b9 | [
"MIT"
] | null | null | null | Application/src/contactsworker.cpp | DavidRomanovizc/adressbook | d03448d6ccb563e9403dc63d31c3a6df1539b7b9 | [
"MIT"
] | null | null | null | #include "contactsworker.h"
ContactsWorker::ContactsWorker()
: m_clientManager{ClientManager::instance()} {
connect(&m_clientManager, &ClientManager::connectionStateChanged,
this, &ContactsWorker::onConnectionStateChanged);
connect(&m_clientManager, &ClientManager::contactsResponse,
this, &ContactsWorker::onContactsDownloadSucceed);
}
bool ContactsWorker::requestBrowseContacts() {
const auto &package = net::Package{QVariant::fromValue(true), net::PackageType::CONTACTS_REQUEST};
return m_clientManager.sendPackage(package);
}
void ContactsWorker::onConnectionStateChanged(net::ConnectionState state) {
if (state == net::ConnectionState::Connected) {
requestBrowseContacts();
}
}
std::vector <Contact> transform(const std::vector <QVariant> &source) {
std::vector <Contact> target;
std::transform(source.begin(), source.end(), std::back_inserter(target),
[](const QVariant &entry) {
QSequentialIterable value = entry.value<QSequentialIterable>();
return Contact{
value.at(1).toString(),
value.at(2).toString(),
value.at(3).toString(),
value.at(0).toInt()
};
});
return target;
}
void ContactsWorker::onContactsDownloadSucceed(const std::vector <QVariant> &data) {
emit browsingContactsCompleted(transform(data));
}
#include "contactsworker.h"
#include "Processor.h"
#include "dbtypes.h"
using namespace DBTypes;
ContactsReader::ContactsReader()
: m_processor{new db::Processor{}} {
}
ContactsReader::~ContactsReader() {
}
// FIXME : no matching constructor for initialization of 'Conatct'
std::vector <Contact> transform(const std::vector <DBEntry> &source) {
std::vector <Contact> target;
std::transform(source.begin(), source.end(), std::back_inserter(target),
[](const DBEntry &entry) {
return Contact{entry[1].toString(),
entry[2].toString(),
entry[3].toString()
};
});
}
// FIXME : no matching constructor for initialization of 'Conatct'
std::pair<bool, std::vector<Contact>> ContactsReader::reqestsContactsBrowse() {
DBResult result;
std::vector <DBEntry> entries;
std::tie(result, entries) = m_processor->requestTableData(DBTables::Contacts);
return {};
}
| 33.986842 | 102 | 0.610918 | [
"vector",
"transform"
] |
cd51dc5f48d163610bfecf3f98434c70467f24e4 | 140,711 | cpp | C++ | runtime/src/kmp_tasking.cpp | sshudler/llvm-omp-chunks | 6263bbf27e9e1de53be6a19429b8b20ec9a5eccd | [
"MIT"
] | null | null | null | runtime/src/kmp_tasking.cpp | sshudler/llvm-omp-chunks | 6263bbf27e9e1de53be6a19429b8b20ec9a5eccd | [
"MIT"
] | null | null | null | runtime/src/kmp_tasking.cpp | sshudler/llvm-omp-chunks | 6263bbf27e9e1de53be6a19429b8b20ec9a5eccd | [
"MIT"
] | null | null | null | /*
* kmp_tasking.cpp -- OpenMP 3.0 tasking support.
*/
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
#include "kmp.h"
#include "kmp_i18n.h"
#include "kmp_itt.h"
#include "kmp_wait_release.h"
#include "kmp_stats.h"
#if OMPT_SUPPORT
#include "ompt-specific.h"
#endif
#include "tsan_annotations.h"
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
/* forward declaration */
static void __kmp_enable_tasking( kmp_task_team_t *task_team, kmp_info_t *this_thr );
static void __kmp_alloc_task_deque( kmp_info_t *thread, kmp_thread_data_t *thread_data );
static int __kmp_realloc_task_threads_data( kmp_info_t *thread, kmp_task_team_t *task_team );
#ifdef OMP_45_ENABLED
static void __kmp_bottom_half_finish_proxy( kmp_int32 gtid, kmp_task_t * ptask );
#endif
#ifdef BUILD_TIED_TASK_STACK
//---------------------------------------------------------------------------
// __kmp_trace_task_stack: print the tied tasks from the task stack in order
// from top do bottom
//
// gtid: global thread identifier for thread containing stack
// thread_data: thread data for task team thread containing stack
// threshold: value above which the trace statement triggers
// location: string identifying call site of this function (for trace)
static void
__kmp_trace_task_stack( kmp_int32 gtid, kmp_thread_data_t *thread_data, int threshold, char *location )
{
kmp_task_stack_t *task_stack = & thread_data->td.td_susp_tied_tasks;
kmp_taskdata_t **stack_top = task_stack -> ts_top;
kmp_int32 entries = task_stack -> ts_entries;
kmp_taskdata_t *tied_task;
KA_TRACE(threshold, ("__kmp_trace_task_stack(start): location = %s, gtid = %d, entries = %d, "
"first_block = %p, stack_top = %p \n",
location, gtid, entries, task_stack->ts_first_block, stack_top ) );
KMP_DEBUG_ASSERT( stack_top != NULL );
KMP_DEBUG_ASSERT( entries > 0 );
while ( entries != 0 )
{
KMP_DEBUG_ASSERT( stack_top != & task_stack->ts_first_block.sb_block[0] );
// fix up ts_top if we need to pop from previous block
if ( entries & TASK_STACK_INDEX_MASK == 0 )
{
kmp_stack_block_t *stack_block = (kmp_stack_block_t *) (stack_top) ;
stack_block = stack_block -> sb_prev;
stack_top = & stack_block -> sb_block[TASK_STACK_BLOCK_SIZE];
}
// finish bookkeeping
stack_top--;
entries--;
tied_task = * stack_top;
KMP_DEBUG_ASSERT( tied_task != NULL );
KMP_DEBUG_ASSERT( tied_task -> td_flags.tasktype == TASK_TIED );
KA_TRACE(threshold, ("__kmp_trace_task_stack(%s): gtid=%d, entry=%d, "
"stack_top=%p, tied_task=%p\n",
location, gtid, entries, stack_top, tied_task ) );
}
KMP_DEBUG_ASSERT( stack_top == & task_stack->ts_first_block.sb_block[0] );
KA_TRACE(threshold, ("__kmp_trace_task_stack(exit): location = %s, gtid = %d\n",
location, gtid ) );
}
//---------------------------------------------------------------------------
// __kmp_init_task_stack: initialize the task stack for the first time
// after a thread_data structure is created.
// It should not be necessary to do this again (assuming the stack works).
//
// gtid: global thread identifier of calling thread
// thread_data: thread data for task team thread containing stack
static void
__kmp_init_task_stack( kmp_int32 gtid, kmp_thread_data_t *thread_data )
{
kmp_task_stack_t *task_stack = & thread_data->td.td_susp_tied_tasks;
kmp_stack_block_t *first_block;
// set up the first block of the stack
first_block = & task_stack -> ts_first_block;
task_stack -> ts_top = (kmp_taskdata_t **) first_block;
memset( (void *) first_block, '\0', TASK_STACK_BLOCK_SIZE * sizeof(kmp_taskdata_t *));
// initialize the stack to be empty
task_stack -> ts_entries = TASK_STACK_EMPTY;
first_block -> sb_next = NULL;
first_block -> sb_prev = NULL;
}
//---------------------------------------------------------------------------
// __kmp_free_task_stack: free the task stack when thread_data is destroyed.
//
// gtid: global thread identifier for calling thread
// thread_data: thread info for thread containing stack
static void
__kmp_free_task_stack( kmp_int32 gtid, kmp_thread_data_t *thread_data )
{
kmp_task_stack_t *task_stack = & thread_data->td.td_susp_tied_tasks;
kmp_stack_block_t *stack_block = & task_stack -> ts_first_block;
KMP_DEBUG_ASSERT( task_stack -> ts_entries == TASK_STACK_EMPTY );
// free from the second block of the stack
while ( stack_block != NULL ) {
kmp_stack_block_t *next_block = (stack_block) ? stack_block -> sb_next : NULL;
stack_block -> sb_next = NULL;
stack_block -> sb_prev = NULL;
if (stack_block != & task_stack -> ts_first_block) {
__kmp_thread_free( thread, stack_block ); // free the block, if not the first
}
stack_block = next_block;
}
// initialize the stack to be empty
task_stack -> ts_entries = 0;
task_stack -> ts_top = NULL;
}
//---------------------------------------------------------------------------
// __kmp_push_task_stack: Push the tied task onto the task stack.
// Grow the stack if necessary by allocating another block.
//
// gtid: global thread identifier for calling thread
// thread: thread info for thread containing stack
// tied_task: the task to push on the stack
static void
__kmp_push_task_stack( kmp_int32 gtid, kmp_info_t *thread, kmp_taskdata_t * tied_task )
{
// GEH - need to consider what to do if tt_threads_data not allocated yet
kmp_thread_data_t *thread_data = & thread -> th.th_task_team ->
tt.tt_threads_data[ __kmp_tid_from_gtid( gtid ) ];
kmp_task_stack_t *task_stack = & thread_data->td.td_susp_tied_tasks ;
if ( tied_task->td_flags.team_serial || tied_task->td_flags.tasking_ser ) {
return; // Don't push anything on stack if team or team tasks are serialized
}
KMP_DEBUG_ASSERT( tied_task -> td_flags.tasktype == TASK_TIED );
KMP_DEBUG_ASSERT( task_stack -> ts_top != NULL );
KA_TRACE(20, ("__kmp_push_task_stack(enter): GTID: %d; THREAD: %p; TASK: %p\n",
gtid, thread, tied_task ) );
// Store entry
* (task_stack -> ts_top) = tied_task;
// Do bookkeeping for next push
task_stack -> ts_top++;
task_stack -> ts_entries++;
if ( task_stack -> ts_entries & TASK_STACK_INDEX_MASK == 0 )
{
// Find beginning of this task block
kmp_stack_block_t *stack_block =
(kmp_stack_block_t *) (task_stack -> ts_top - TASK_STACK_BLOCK_SIZE);
// Check if we already have a block
if ( stack_block -> sb_next != NULL )
{ // reset ts_top to beginning of next block
task_stack -> ts_top = & stack_block -> sb_next -> sb_block[0];
}
else
{ // Alloc new block and link it up
kmp_stack_block_t *new_block = (kmp_stack_block_t *)
__kmp_thread_calloc(thread, sizeof(kmp_stack_block_t));
task_stack -> ts_top = & new_block -> sb_block[0];
stack_block -> sb_next = new_block;
new_block -> sb_prev = stack_block;
new_block -> sb_next = NULL;
KA_TRACE(30, ("__kmp_push_task_stack(): GTID: %d; TASK: %p; Alloc new block: %p\n",
gtid, tied_task, new_block ) );
}
}
KA_TRACE(20, ("__kmp_push_task_stack(exit): GTID: %d; TASK: %p\n", gtid, tied_task ) );
}
//---------------------------------------------------------------------------
// __kmp_pop_task_stack: Pop the tied task from the task stack. Don't return
// the task, just check to make sure it matches the ending task passed in.
//
// gtid: global thread identifier for the calling thread
// thread: thread info structure containing stack
// tied_task: the task popped off the stack
// ending_task: the task that is ending (should match popped task)
static void
__kmp_pop_task_stack( kmp_int32 gtid, kmp_info_t *thread, kmp_taskdata_t *ending_task )
{
// GEH - need to consider what to do if tt_threads_data not allocated yet
kmp_thread_data_t *thread_data = & thread -> th.th_task_team -> tt_threads_data[ __kmp_tid_from_gtid( gtid ) ];
kmp_task_stack_t *task_stack = & thread_data->td.td_susp_tied_tasks ;
kmp_taskdata_t *tied_task;
if ( ending_task->td_flags.team_serial || ending_task->td_flags.tasking_ser ) {
return; // Don't pop anything from stack if team or team tasks are serialized
}
KMP_DEBUG_ASSERT( task_stack -> ts_top != NULL );
KMP_DEBUG_ASSERT( task_stack -> ts_entries > 0 );
KA_TRACE(20, ("__kmp_pop_task_stack(enter): GTID: %d; THREAD: %p\n", gtid, thread ) );
// fix up ts_top if we need to pop from previous block
if ( task_stack -> ts_entries & TASK_STACK_INDEX_MASK == 0 )
{
kmp_stack_block_t *stack_block =
(kmp_stack_block_t *) (task_stack -> ts_top) ;
stack_block = stack_block -> sb_prev;
task_stack -> ts_top = & stack_block -> sb_block[TASK_STACK_BLOCK_SIZE];
}
// finish bookkeeping
task_stack -> ts_top--;
task_stack -> ts_entries--;
tied_task = * (task_stack -> ts_top );
KMP_DEBUG_ASSERT( tied_task != NULL );
KMP_DEBUG_ASSERT( tied_task -> td_flags.tasktype == TASK_TIED );
KMP_DEBUG_ASSERT( tied_task == ending_task ); // If we built the stack correctly
KA_TRACE(20, ("__kmp_pop_task_stack(exit): GTID: %d; TASK: %p\n", gtid, tied_task ) );
return;
}
#endif /* BUILD_TIED_TASK_STACK */
//---------------------------------------------------
// __kmp_push_task: Add a task to the thread's deque
static kmp_int32
__kmp_push_task(kmp_int32 gtid, kmp_task_t * task )
{
kmp_info_t * thread = __kmp_threads[ gtid ];
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(task);
kmp_task_team_t * task_team = thread->th.th_task_team;
kmp_int32 tid = __kmp_tid_from_gtid( gtid );
kmp_thread_data_t * thread_data;
KA_TRACE(20, ("__kmp_push_task: T#%d trying to push task %p.\n", gtid, taskdata ) );
if ( taskdata->td_flags.tiedness == TASK_UNTIED ) {
// untied task needs to increment counter so that the task structure is not freed prematurely
kmp_int32 counter = 1 + KMP_TEST_THEN_INC32(&taskdata->td_untied_count);
KA_TRACE(20, ( "__kmp_push_task: T#%d untied_count (%d) incremented for task %p\n",
gtid, counter, taskdata ) );
}
// The first check avoids building task_team thread data if serialized
if ( taskdata->td_flags.task_serial ) {
KA_TRACE(20, ( "__kmp_push_task: T#%d team serialized; returning TASK_NOT_PUSHED for task %p\n",
gtid, taskdata ) );
return TASK_NOT_PUSHED;
}
// Now that serialized tasks have returned, we can assume that we are not in immediate exec mode
KMP_DEBUG_ASSERT( __kmp_tasking_mode != tskm_immediate_exec );
if ( ! KMP_TASKING_ENABLED(task_team) ) {
__kmp_enable_tasking( task_team, thread );
}
KMP_DEBUG_ASSERT( TCR_4(task_team -> tt.tt_found_tasks) == TRUE );
KMP_DEBUG_ASSERT( TCR_PTR(task_team -> tt.tt_threads_data) != NULL );
// Find tasking deque specific to encountering thread
thread_data = & task_team -> tt.tt_threads_data[ tid ];
// No lock needed since only owner can allocate
if (thread_data -> td.td_deque == NULL ) {
__kmp_alloc_task_deque( thread, thread_data );
}
// Check if deque is full
if ( TCR_4(thread_data -> td.td_deque_ntasks) >= TASK_DEQUE_SIZE(thread_data->td) )
{
KA_TRACE(20, ( "__kmp_push_task: T#%d deque is full; returning TASK_NOT_PUSHED for task %p\n",
gtid, taskdata ) );
return TASK_NOT_PUSHED;
}
// Lock the deque for the task push operation
__kmp_acquire_bootstrap_lock( & thread_data -> td.td_deque_lock );
#if OMP_45_ENABLED
// Need to recheck as we can get a proxy task from a thread outside of OpenMP
if ( TCR_4(thread_data -> td.td_deque_ntasks) >= TASK_DEQUE_SIZE(thread_data->td) )
{
__kmp_release_bootstrap_lock( & thread_data -> td.td_deque_lock );
KA_TRACE(20, ( "__kmp_push_task: T#%d deque is full on 2nd check; returning TASK_NOT_PUSHED for task %p\n",
gtid, taskdata ) );
return TASK_NOT_PUSHED;
}
#else
// Must have room since no thread can add tasks but calling thread
KMP_DEBUG_ASSERT( TCR_4(thread_data -> td.td_deque_ntasks) < TASK_DEQUE_SIZE(thread_data->td) );
#endif
thread_data -> td.td_deque[ thread_data -> td.td_deque_tail ] = taskdata; // Push taskdata
// Wrap index.
thread_data -> td.td_deque_tail = ( thread_data -> td.td_deque_tail + 1 ) & TASK_DEQUE_MASK(thread_data->td);
TCW_4(thread_data -> td.td_deque_ntasks, TCR_4(thread_data -> td.td_deque_ntasks) + 1); // Adjust task count
KA_TRACE(20, ("__kmp_push_task: T#%d returning TASK_SUCCESSFULLY_PUSHED: "
"task=%p ntasks=%d head=%u tail=%u\n",
gtid, taskdata, thread_data->td.td_deque_ntasks,
thread_data->td.td_deque_head, thread_data->td.td_deque_tail) );
__kmp_release_bootstrap_lock( & thread_data->td.td_deque_lock );
return TASK_SUCCESSFULLY_PUSHED;
}
//-----------------------------------------------------------------------------------------
// __kmp_pop_current_task_from_thread: set up current task from called thread when team ends
// this_thr: thread structure to set current_task in.
void
__kmp_pop_current_task_from_thread( kmp_info_t *this_thr )
{
KF_TRACE( 10, ("__kmp_pop_current_task_from_thread(enter): T#%d this_thread=%p, curtask=%p, "
"curtask_parent=%p\n",
0, this_thr, this_thr -> th.th_current_task,
this_thr -> th.th_current_task -> td_parent ) );
this_thr -> th.th_current_task = this_thr -> th.th_current_task -> td_parent;
KF_TRACE( 10, ("__kmp_pop_current_task_from_thread(exit): T#%d this_thread=%p, curtask=%p, "
"curtask_parent=%p\n",
0, this_thr, this_thr -> th.th_current_task,
this_thr -> th.th_current_task -> td_parent ) );
}
//---------------------------------------------------------------------------------------
// __kmp_push_current_task_to_thread: set up current task in called thread for a new team
// this_thr: thread structure to set up
// team: team for implicit task data
// tid: thread within team to set up
void
__kmp_push_current_task_to_thread( kmp_info_t *this_thr, kmp_team_t *team, int tid )
{
// current task of the thread is a parent of the new just created implicit tasks of new team
KF_TRACE( 10, ( "__kmp_push_current_task_to_thread(enter): T#%d this_thread=%p curtask=%p "
"parent_task=%p\n",
tid, this_thr, this_thr->th.th_current_task,
team->t.t_implicit_task_taskdata[tid].td_parent ) );
KMP_DEBUG_ASSERT (this_thr != NULL);
if( tid == 0 ) {
if( this_thr->th.th_current_task != & team -> t.t_implicit_task_taskdata[ 0 ] ) {
team -> t.t_implicit_task_taskdata[ 0 ].td_parent = this_thr->th.th_current_task;
this_thr->th.th_current_task = & team -> t.t_implicit_task_taskdata[ 0 ];
}
} else {
team -> t.t_implicit_task_taskdata[ tid ].td_parent = team -> t.t_implicit_task_taskdata[ 0 ].td_parent;
this_thr->th.th_current_task = & team -> t.t_implicit_task_taskdata[ tid ];
}
KF_TRACE( 10, ( "__kmp_push_current_task_to_thread(exit): T#%d this_thread=%p curtask=%p "
"parent_task=%p\n",
tid, this_thr, this_thr->th.th_current_task,
team->t.t_implicit_task_taskdata[tid].td_parent ) );
}
//----------------------------------------------------------------------
// __kmp_task_start: bookkeeping for a task starting execution
// GTID: global thread id of calling thread
// task: task starting execution
// current_task: task suspending
static void
__kmp_task_start( kmp_int32 gtid, kmp_task_t * task, kmp_taskdata_t * current_task )
{
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(task);
kmp_info_t * thread = __kmp_threads[ gtid ];
KA_TRACE(10, ("__kmp_task_start(enter): T#%d starting task %p: current_task=%p\n",
gtid, taskdata, current_task) );
KMP_DEBUG_ASSERT( taskdata -> td_flags.tasktype == TASK_EXPLICIT );
// mark currently executing task as suspended
// TODO: GEH - make sure root team implicit task is initialized properly.
// KMP_DEBUG_ASSERT( current_task -> td_flags.executing == 1 );
current_task -> td_flags.executing = 0;
// Add task to stack if tied
#ifdef BUILD_TIED_TASK_STACK
if ( taskdata -> td_flags.tiedness == TASK_TIED )
{
__kmp_push_task_stack( gtid, thread, taskdata );
}
#endif /* BUILD_TIED_TASK_STACK */
// mark starting task as executing and as current task
thread -> th.th_current_task = taskdata;
KMP_DEBUG_ASSERT( taskdata->td_flags.started == 0 || taskdata->td_flags.tiedness == TASK_UNTIED );
KMP_DEBUG_ASSERT( taskdata->td_flags.executing == 0 || taskdata->td_flags.tiedness == TASK_UNTIED );
taskdata -> td_flags.started = 1;
taskdata -> td_flags.executing = 1;
KMP_DEBUG_ASSERT( taskdata -> td_flags.complete == 0 );
KMP_DEBUG_ASSERT( taskdata -> td_flags.freed == 0 );
// GEH TODO: shouldn't we pass some sort of location identifier here?
// APT: yes, we will pass location here.
// need to store current thread state (in a thread or taskdata structure)
// before setting work_state, otherwise wrong state is set after end of task
KA_TRACE(10, ("__kmp_task_start(exit): T#%d task=%p\n",
gtid, taskdata ) );
#if OMPT_SUPPORT
/* let OMPT know that we're about to run this task */
if (ompt_enabled &&
ompt_callbacks.ompt_callback(ompt_callback_task_schedule))
{
ompt_callbacks.ompt_callback(ompt_callback_task_schedule)(
&(current_task->ompt_task_info.task_data),
ompt_task_others,
&(taskdata->ompt_task_info.task_data));
}
if (ompt_enabled)
taskdata->ompt_task_info.scheduling_parent = current_task;
#endif
return;
}
//----------------------------------------------------------------------
// __kmpc_omp_task_begin_if0: report that a given serialized task has started execution
// loc_ref: source location information; points to beginning of task block.
// gtid: global thread number.
// task: task thunk for the started task.
void
__kmpc_omp_task_begin_if0( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t * task )
{
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(task);
kmp_taskdata_t * current_task = __kmp_threads[ gtid ] -> th.th_current_task;
KA_TRACE(10, ("__kmpc_omp_task_begin_if0(enter): T#%d loc=%p task=%p current_task=%p\n",
gtid, loc_ref, taskdata, current_task ) );
if ( taskdata->td_flags.tiedness == TASK_UNTIED ) {
// untied task needs to increment counter so that the task structure is not freed prematurely
kmp_int32 counter = 1 + KMP_TEST_THEN_INC32(&taskdata->td_untied_count);
KA_TRACE(20, ( "__kmpc_omp_task_begin_if0: T#%d untied_count (%d) incremented for task %p\n",
gtid, counter, taskdata ) );
}
#if OMPT_SUPPORT
if (ompt_enabled && current_task->ompt_task_info.frame.reenter_runtime_frame == NULL) {
current_task->ompt_task_info.frame.reenter_runtime_frame =
taskdata->ompt_task_info.frame.exit_runtime_frame =
OMPT_GET_FRAME_ADDRESS(1);
}
if (ompt_enabled) {
if (ompt_callbacks.ompt_callback(ompt_callback_task_create)) {
kmp_taskdata_t *parent = taskdata->td_parent;
ompt_task_data_t task_data = ompt_task_id_none;
ompt_callbacks.ompt_callback(ompt_callback_task_create)(
parent ? &(parent->ompt_task_info.task_data) : &task_data,
parent ? &(parent->ompt_task_info.frame) : NULL,
&(taskdata->ompt_task_info.task_data),
ompt_task_explicit,
0,
taskdata->ompt_task_info.function);
}
}
#endif
taskdata -> td_flags.task_serial = 1; // Execute this task immediately, not deferred.
__kmp_task_start( gtid, task, current_task );
KA_TRACE(10, ("__kmpc_omp_task_begin_if0(exit): T#%d loc=%p task=%p,\n",
gtid, loc_ref, taskdata ) );
return;
}
#ifdef TASK_UNUSED
//----------------------------------------------------------------------
// __kmpc_omp_task_begin: report that a given task has started execution
// NEVER GENERATED BY COMPILER, DEPRECATED!!!
void
__kmpc_omp_task_begin( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t * task )
{
kmp_taskdata_t * current_task = __kmp_threads[ gtid ] -> th.th_current_task;
KA_TRACE(10, ("__kmpc_omp_task_begin(enter): T#%d loc=%p task=%p current_task=%p\n",
gtid, loc_ref, KMP_TASK_TO_TASKDATA(task), current_task ) );
__kmp_task_start( gtid, task, current_task );
KA_TRACE(10, ("__kmpc_omp_task_begin(exit): T#%d loc=%p task=%p,\n",
gtid, loc_ref, KMP_TASK_TO_TASKDATA(task) ) );
return;
}
#endif // TASK_UNUSED
//-------------------------------------------------------------------------------------
// __kmp_free_task: free the current task space and the space for shareds
// gtid: Global thread ID of calling thread
// taskdata: task to free
// thread: thread data structure of caller
static void
__kmp_free_task( kmp_int32 gtid, kmp_taskdata_t * taskdata, kmp_info_t * thread )
{
KA_TRACE(30, ("__kmp_free_task: T#%d freeing data from task %p\n",
gtid, taskdata) );
// Check to make sure all flags and counters have the correct values
KMP_DEBUG_ASSERT( taskdata->td_flags.tasktype == TASK_EXPLICIT );
KMP_DEBUG_ASSERT( taskdata->td_flags.executing == 0 );
KMP_DEBUG_ASSERT( taskdata->td_flags.complete == 1 );
KMP_DEBUG_ASSERT( taskdata->td_flags.freed == 0 );
KMP_DEBUG_ASSERT( TCR_4(taskdata->td_allocated_child_tasks) == 0 || taskdata->td_flags.task_serial == 1);
KMP_DEBUG_ASSERT( TCR_4(taskdata->td_incomplete_child_tasks) == 0 );
taskdata->td_flags.freed = 1;
ANNOTATE_HAPPENS_BEFORE(taskdata);
// deallocate the taskdata and shared variable blocks associated with this task
#if USE_FAST_MEMORY
__kmp_fast_free( thread, taskdata );
#else /* ! USE_FAST_MEMORY */
__kmp_thread_free( thread, taskdata );
#endif
KA_TRACE(20, ("__kmp_free_task: T#%d freed task %p\n",
gtid, taskdata) );
}
//-------------------------------------------------------------------------------------
// __kmp_free_task_and_ancestors: free the current task and ancestors without children
//
// gtid: Global thread ID of calling thread
// taskdata: task to free
// thread: thread data structure of caller
static void
__kmp_free_task_and_ancestors( kmp_int32 gtid, kmp_taskdata_t * taskdata, kmp_info_t * thread )
{
#if OMP_45_ENABLED
// Proxy tasks must always be allowed to free their parents
// because they can be run in background even in serial mode.
kmp_int32 team_serial = ( taskdata->td_flags.team_serial ||
taskdata->td_flags.tasking_ser ) && !taskdata->td_flags.proxy;
#else
kmp_int32 team_serial = taskdata->td_flags.team_serial ||
taskdata->td_flags.tasking_ser;
#endif
KMP_DEBUG_ASSERT( taskdata -> td_flags.tasktype == TASK_EXPLICIT );
kmp_int32 children = KMP_TEST_THEN_DEC32( (kmp_int32 *)(& taskdata -> td_allocated_child_tasks) ) - 1;
KMP_DEBUG_ASSERT( children >= 0 );
// Now, go up the ancestor tree to see if any ancestors can now be freed.
while ( children == 0 )
{
kmp_taskdata_t * parent_taskdata = taskdata -> td_parent;
KA_TRACE(20, ("__kmp_free_task_and_ancestors(enter): T#%d task %p complete "
"and freeing itself\n", gtid, taskdata) );
// --- Deallocate my ancestor task ---
__kmp_free_task( gtid, taskdata, thread );
taskdata = parent_taskdata;
// Stop checking ancestors at implicit task
// instead of walking up ancestor tree to avoid premature deallocation of ancestors.
if ( team_serial || taskdata -> td_flags.tasktype == TASK_IMPLICIT )
return;
// Predecrement simulated by "- 1" calculation
children = KMP_TEST_THEN_DEC32( (kmp_int32 *)(& taskdata -> td_allocated_child_tasks) ) - 1;
KMP_DEBUG_ASSERT( children >= 0 );
}
KA_TRACE(20, ("__kmp_free_task_and_ancestors(exit): T#%d task %p has %d children; "
"not freeing it yet\n", gtid, taskdata, children) );
}
//---------------------------------------------------------------------
// __kmp_task_finish: bookkeeping to do when a task finishes execution
// gtid: global thread ID for calling thread
// task: task to be finished
// resumed_task: task to be resumed. (may be NULL if task is serialized)
static void
__kmp_task_finish( kmp_int32 gtid, kmp_task_t *task, kmp_taskdata_t *resumed_task )
{
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(task);
kmp_info_t * thread = __kmp_threads[ gtid ];
kmp_task_team_t * task_team = thread->th.th_task_team; // might be NULL for serial teams...
kmp_int32 children = 0;
#if OMPT_SUPPORT
/* let OMPT know that we're returning to the callee task */
if (ompt_enabled &&
ompt_callbacks.ompt_callback(ompt_callback_task_schedule))
{
ompt_callbacks.ompt_callback(ompt_callback_task_schedule)(
&(taskdata->ompt_task_info.task_data),
ompt_task_complete,
&((resumed_task?resumed_task:
(taskdata->ompt_task_info.scheduling_parent?taskdata->ompt_task_info.scheduling_parent:
taskdata->td_parent))
->ompt_task_info.task_data));
}
#endif
KA_TRACE(10, ("__kmp_task_finish(enter): T#%d finishing task %p and resuming task %p\n",
gtid, taskdata, resumed_task) );
KMP_DEBUG_ASSERT( taskdata -> td_flags.tasktype == TASK_EXPLICIT );
// Pop task from stack if tied
#ifdef BUILD_TIED_TASK_STACK
if ( taskdata -> td_flags.tiedness == TASK_TIED )
{
__kmp_pop_task_stack( gtid, thread, taskdata );
}
#endif /* BUILD_TIED_TASK_STACK */
if ( taskdata->td_flags.tiedness == TASK_UNTIED ) {
// untied task needs to check the counter so that the task structure is not freed prematurely
kmp_int32 counter = KMP_TEST_THEN_DEC32(&taskdata->td_untied_count) - 1;
KA_TRACE(20, ( "__kmp_task_finish: T#%d untied_count (%d) decremented for task %p\n",
gtid, counter, taskdata ) );
if ( counter > 0 ) {
// untied task is not done, to be continued possibly by other thread, do not free it now
if (resumed_task == NULL) {
KMP_DEBUG_ASSERT( taskdata->td_flags.task_serial );
resumed_task = taskdata->td_parent; // In a serialized task, the resumed task is the parent
}
thread->th.th_current_task = resumed_task; // restore current_task
resumed_task->td_flags.executing = 1; // resume previous task
KA_TRACE(10, ("__kmp_task_finish(exit): T#%d partially done task %p, resuming task %p\n",
gtid, taskdata, resumed_task) );
return;
}
}
KMP_DEBUG_ASSERT( taskdata -> td_flags.complete == 0 );
taskdata -> td_flags.complete = 1; // mark the task as completed
KMP_DEBUG_ASSERT( taskdata -> td_flags.started == 1 );
KMP_DEBUG_ASSERT( taskdata -> td_flags.freed == 0 );
// Only need to keep track of count if team parallel and tasking not serialized
if ( !( taskdata -> td_flags.team_serial || taskdata -> td_flags.tasking_ser ) ) {
// Predecrement simulated by "- 1" calculation
children = KMP_TEST_THEN_DEC32( (kmp_int32 *)(& taskdata -> td_parent -> td_incomplete_child_tasks) ) - 1;
KMP_DEBUG_ASSERT( children >= 0 );
#if OMP_40_ENABLED
if ( taskdata->td_taskgroup )
KMP_TEST_THEN_DEC32( (kmp_int32 *)(& taskdata->td_taskgroup->count) );
#if OMP_45_ENABLED
}
// if we found proxy tasks there could exist a dependency chain
// with the proxy task as origin
if ( !( taskdata -> td_flags.team_serial || taskdata -> td_flags.tasking_ser ) || (task_team && task_team->tt.tt_found_proxy_tasks) ) {
#endif
__kmp_release_deps(gtid,taskdata);
#endif
}
// td_flags.executing must be marked as 0 after __kmp_release_deps has been called
// Othertwise, if a task is executed immediately from the release_deps code
// the flag will be reset to 1 again by this same function
KMP_DEBUG_ASSERT( taskdata -> td_flags.executing == 1 );
taskdata -> td_flags.executing = 0; // suspend the finishing task
KA_TRACE(20, ("__kmp_task_finish: T#%d finished task %p, %d incomplete children\n",
gtid, taskdata, children) );
#if OMP_40_ENABLED
/* If the tasks' destructor thunk flag has been set, we need to invoke the
destructor thunk that has been generated by the compiler.
The code is placed here, since at this point other tasks might have been released
hence overlapping the destructor invokations with some other work in the
released tasks. The OpenMP spec is not specific on when the destructors are
invoked, so we should be free to choose.
*/
if (taskdata->td_flags.destructors_thunk) {
kmp_routine_entry_t destr_thunk = task->data1.destructors;
KMP_ASSERT(destr_thunk);
destr_thunk(gtid, task);
}
#endif // OMP_40_ENABLED
// bookkeeping for resuming task:
// GEH - note tasking_ser => task_serial
KMP_DEBUG_ASSERT( (taskdata->td_flags.tasking_ser || taskdata->td_flags.task_serial) ==
taskdata->td_flags.task_serial);
if ( taskdata->td_flags.task_serial )
{
if (resumed_task == NULL) {
resumed_task = taskdata->td_parent; // In a serialized task, the resumed task is the parent
}
else
#if OMP_45_ENABLED
if ( !(task_team && task_team->tt.tt_found_proxy_tasks) )
#endif
{
// verify resumed task passed in points to parent
KMP_DEBUG_ASSERT( resumed_task == taskdata->td_parent );
}
}
else {
KMP_DEBUG_ASSERT( resumed_task != NULL ); // verify that resumed task is passed as arguemnt
}
// Free this task and then ancestor tasks if they have no children.
// Restore th_current_task first as suggested by John:
// johnmc: if an asynchronous inquiry peers into the runtime system
// it doesn't see the freed task as the current task.
thread->th.th_current_task = resumed_task;
__kmp_free_task_and_ancestors(gtid, taskdata, thread);
// TODO: GEH - make sure root team implicit task is initialized properly.
// KMP_DEBUG_ASSERT( resumed_task->td_flags.executing == 0 );
resumed_task->td_flags.executing = 1; // resume previous task
KA_TRACE(10, ("__kmp_task_finish(exit): T#%d finished task %p, resuming task %p\n",
gtid, taskdata, resumed_task) );
return;
}
//---------------------------------------------------------------------
// __kmpc_omp_task_complete_if0: report that a task has completed execution
// loc_ref: source location information; points to end of task block.
// gtid: global thread number.
// task: task thunk for the completed task.
void
__kmpc_omp_task_complete_if0( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *task )
{
KA_TRACE(10, ("__kmpc_omp_task_complete_if0(enter): T#%d loc=%p task=%p\n",
gtid, loc_ref, KMP_TASK_TO_TASKDATA(task) ) );
__kmp_task_finish( gtid, task, NULL ); // this routine will provide task to resume
KA_TRACE(10, ("__kmpc_omp_task_complete_if0(exit): T#%d loc=%p task=%p\n",
gtid, loc_ref, KMP_TASK_TO_TASKDATA(task) ) );
#if OMPT_SUPPORT
if (ompt_enabled) {
ompt_frame_t* ompt_frame;
__ompt_get_task_info_internal(0, NULL, NULL, &ompt_frame, NULL, NULL);
ompt_frame->reenter_runtime_frame = NULL;
}
#endif
return;
}
#ifdef TASK_UNUSED
//---------------------------------------------------------------------
// __kmpc_omp_task_complete: report that a task has completed execution
// NEVER GENERATED BY COMPILER, DEPRECATED!!!
void
__kmpc_omp_task_complete( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *task )
{
KA_TRACE(10, ("__kmpc_omp_task_complete(enter): T#%d loc=%p task=%p\n",
gtid, loc_ref, KMP_TASK_TO_TASKDATA(task) ) );
__kmp_task_finish( gtid, task, NULL ); // Not sure how to find task to resume
KA_TRACE(10, ("__kmpc_omp_task_complete(exit): T#%d loc=%p task=%p\n",
gtid, loc_ref, KMP_TASK_TO_TASKDATA(task) ) );
return;
}
#endif // TASK_UNUSED
#if OMPT_SUPPORT
//----------------------------------------------------------------------------------------------------
// __kmp_task_init_ompt:
// Initialize OMPT fields maintained by a task. This will only be called after
// ompt_tool, so we already know whether ompt is enabled or not.
static inline void
__kmp_task_init_ompt( kmp_taskdata_t * task, int tid, void * function )
{
if (ompt_enabled) {
task->ompt_task_info.task_data.value = __ompt_task_id_new(tid);
task->ompt_task_info.function = function;
task->ompt_task_info.frame.exit_runtime_frame = NULL;
task->ompt_task_info.frame.reenter_runtime_frame = NULL;
#if OMP_40_ENABLED
task->ompt_task_info.ndeps = 0;
task->ompt_task_info.deps = NULL;
#endif /* OMP_40_ENABLED */
}
}
#endif
//----------------------------------------------------------------------------------------------------
// __kmp_init_implicit_task: Initialize the appropriate fields in the implicit task for a given thread
//
// loc_ref: reference to source location of parallel region
// this_thr: thread data structure corresponding to implicit task
// team: team for this_thr
// tid: thread id of given thread within team
// set_curr_task: TRUE if need to push current task to thread
// NOTE: Routine does not set up the implicit task ICVS. This is assumed to have already been done elsewhere.
// TODO: Get better loc_ref. Value passed in may be NULL
void
__kmp_init_implicit_task( ident_t *loc_ref, kmp_info_t *this_thr, kmp_team_t *team, int tid, int set_curr_task )
{
kmp_taskdata_t * task = & team->t.t_implicit_task_taskdata[ tid ];
KF_TRACE(10, ("__kmp_init_implicit_task(enter): T#:%d team=%p task=%p, reinit=%s\n",
tid, team, task, set_curr_task ? "TRUE" : "FALSE" ) );
task->td_task_id = KMP_GEN_TASK_ID();
task->td_team = team;
// task->td_parent = NULL; // fix for CQ230101 (broken parent task info in debugger)
task->td_ident = loc_ref;
task->td_taskwait_ident = NULL;
task->td_taskwait_counter = 0;
task->td_taskwait_thread = 0;
task->td_flags.tiedness = TASK_TIED;
task->td_flags.tasktype = TASK_IMPLICIT;
#if OMP_45_ENABLED
task->td_flags.proxy = TASK_FULL;
#endif
// All implicit tasks are executed immediately, not deferred
task->td_flags.task_serial = 1;
task->td_flags.tasking_ser = ( __kmp_tasking_mode == tskm_immediate_exec );
task->td_flags.team_serial = ( team->t.t_serialized ) ? 1 : 0;
task->td_flags.started = 1;
task->td_flags.executing = 1;
task->td_flags.complete = 0;
task->td_flags.freed = 0;
#if OMP_40_ENABLED
task->td_depnode = NULL;
#endif
if (set_curr_task) { // only do this initialization the first time a thread is created
task->td_incomplete_child_tasks = 0;
task->td_allocated_child_tasks = 0; // Not used because do not need to deallocate implicit task
#if OMP_40_ENABLED
task->td_taskgroup = NULL; // An implicit task does not have taskgroup
task->td_dephash = NULL;
#endif
__kmp_push_current_task_to_thread( this_thr, team, tid );
} else {
KMP_DEBUG_ASSERT(task->td_incomplete_child_tasks == 0);
KMP_DEBUG_ASSERT(task->td_allocated_child_tasks == 0);
}
#if OMPT_SUPPORT
__kmp_task_init_ompt(task, tid, NULL);
#endif
KF_TRACE(10, ("__kmp_init_implicit_task(exit): T#:%d team=%p task=%p\n",
tid, team, task ) );
}
//-----------------------------------------------------------------------------
//// __kmp_finish_implicit_task: Release resources associated to implicit tasks
//// at the end of parallel regions. Some resources are kept for reuse in the
//// next parallel region.
////
//// thread: thread data structure corresponding to implicit task
//
void
__kmp_finish_implicit_task(kmp_info_t *thread)
{
kmp_taskdata_t *task = thread->th.th_current_task;
if (task->td_dephash)
__kmp_dephash_free_entries(thread, task->td_dephash);
}
//-----------------------------------------------------------------------------
//// __kmp_free_implicit_task: Release resources associated to implicit tasks
//// when these are destroyed regions
////
//// thread: thread data structure corresponding to implicit task
//
void
__kmp_free_implicit_task(kmp_info_t *thread)
{
kmp_taskdata_t *task = thread->th.th_current_task;
if (task->td_dephash)
__kmp_dephash_free(thread, task->td_dephash);
task->td_dephash = NULL;
}
// Round up a size to a power of two specified by val
// Used to insert padding between structures co-allocated using a single malloc() call
static size_t
__kmp_round_up_to_val( size_t size, size_t val ) {
if ( size & ( val - 1 ) ) {
size &= ~ ( val - 1 );
if ( size <= KMP_SIZE_T_MAX - val ) {
size += val; // Round up if there is no overflow.
}; // if
}; // if
return size;
} // __kmp_round_up_to_va
//---------------------------------------------------------------------------------
// __kmp_task_alloc: Allocate the taskdata and task data structures for a task
//
// loc_ref: source location information
// gtid: global thread number.
// flags: include tiedness & task type (explicit vs. implicit) of the ''new'' task encountered.
// Converted from kmp_int32 to kmp_tasking_flags_t in routine.
// sizeof_kmp_task_t: Size in bytes of kmp_task_t data structure including private vars accessed in task.
// sizeof_shareds: Size in bytes of array of pointers to shared vars accessed in task.
// task_entry: Pointer to task code entry point generated by compiler.
// returns: a pointer to the allocated kmp_task_t structure (task).
kmp_task_t *
__kmp_task_alloc( ident_t *loc_ref, kmp_int32 gtid, kmp_tasking_flags_t *flags,
size_t sizeof_kmp_task_t, size_t sizeof_shareds,
kmp_routine_entry_t task_entry )
{
kmp_task_t *task;
kmp_taskdata_t *taskdata;
kmp_info_t *thread = __kmp_threads[ gtid ];
kmp_team_t *team = thread->th.th_team;
kmp_taskdata_t *parent_task = thread->th.th_current_task;
size_t shareds_offset;
KA_TRACE(10, ("__kmp_task_alloc(enter): T#%d loc=%p, flags=(0x%x) "
"sizeof_task=%ld sizeof_shared=%ld entry=%p\n",
gtid, loc_ref, *((kmp_int32 *)flags), sizeof_kmp_task_t,
sizeof_shareds, task_entry) );
if ( parent_task->td_flags.final ) {
if (flags->merged_if0) {
}
flags->final = 1;
}
#if OMP_45_ENABLED
if ( flags->proxy == TASK_PROXY ) {
flags->tiedness = TASK_UNTIED;
flags->merged_if0 = 1;
/* are we running in a sequential parallel or tskm_immediate_exec... we need tasking support enabled */
if ( (thread->th.th_task_team) == NULL ) {
/* This should only happen if the team is serialized
setup a task team and propagate it to the thread
*/
KMP_DEBUG_ASSERT(team->t.t_serialized);
KA_TRACE(30,("T#%d creating task team in __kmp_task_alloc for proxy task\n", gtid));
__kmp_task_team_setup(thread,team,1); // 1 indicates setup the current team regardless of nthreads
thread->th.th_task_team = team->t.t_task_team[thread->th.th_task_state];
}
kmp_task_team_t * task_team = thread->th.th_task_team;
/* tasking must be enabled now as the task might not be pushed */
if ( !KMP_TASKING_ENABLED( task_team ) ) {
KA_TRACE(30,("T#%d enabling tasking in __kmp_task_alloc for proxy task\n", gtid));
__kmp_enable_tasking( task_team, thread );
kmp_int32 tid = thread->th.th_info.ds.ds_tid;
kmp_thread_data_t * thread_data = & task_team -> tt.tt_threads_data[ tid ];
// No lock needed since only owner can allocate
if (thread_data -> td.td_deque == NULL ) {
__kmp_alloc_task_deque( thread, thread_data );
}
}
if ( task_team->tt.tt_found_proxy_tasks == FALSE )
TCW_4(task_team -> tt.tt_found_proxy_tasks, TRUE);
}
#endif
// Calculate shared structure offset including padding after kmp_task_t struct
// to align pointers in shared struct
shareds_offset = sizeof( kmp_taskdata_t ) + sizeof_kmp_task_t;
shareds_offset = __kmp_round_up_to_val( shareds_offset, sizeof( void * ));
// Allocate a kmp_taskdata_t block and a kmp_task_t block.
KA_TRACE(30, ("__kmp_task_alloc: T#%d First malloc size: %ld\n",
gtid, shareds_offset) );
KA_TRACE(30, ("__kmp_task_alloc: T#%d Second malloc size: %ld\n",
gtid, sizeof_shareds) );
// Avoid double allocation here by combining shareds with taskdata
#if USE_FAST_MEMORY
taskdata = (kmp_taskdata_t *) __kmp_fast_allocate( thread, shareds_offset + sizeof_shareds );
#else /* ! USE_FAST_MEMORY */
taskdata = (kmp_taskdata_t *) __kmp_thread_malloc( thread, shareds_offset + sizeof_shareds );
#endif /* USE_FAST_MEMORY */
ANNOTATE_HAPPENS_AFTER(taskdata);
task = KMP_TASKDATA_TO_TASK(taskdata);
// Make sure task & taskdata are aligned appropriately
#if KMP_ARCH_X86 || KMP_ARCH_PPC64 || !KMP_HAVE_QUAD
KMP_DEBUG_ASSERT( ( ((kmp_uintptr_t)taskdata) & (sizeof(double)-1) ) == 0 );
KMP_DEBUG_ASSERT( ( ((kmp_uintptr_t)task) & (sizeof(double)-1) ) == 0 );
#else
KMP_DEBUG_ASSERT( ( ((kmp_uintptr_t)taskdata) & (sizeof(_Quad)-1) ) == 0 );
KMP_DEBUG_ASSERT( ( ((kmp_uintptr_t)task) & (sizeof(_Quad)-1) ) == 0 );
#endif
if (sizeof_shareds > 0) {
// Avoid double allocation here by combining shareds with taskdata
task->shareds = & ((char *) taskdata)[ shareds_offset ];
// Make sure shareds struct is aligned to pointer size
KMP_DEBUG_ASSERT( ( ((kmp_uintptr_t)task->shareds) & (sizeof(void *)-1) ) == 0 );
} else {
task->shareds = NULL;
}
task->routine = task_entry;
task->part_id = 0; // AC: Always start with 0 part id
taskdata->td_task_id = KMP_GEN_TASK_ID();
taskdata->td_team = team;
taskdata->td_alloc_thread = thread;
taskdata->td_parent = parent_task;
taskdata->td_level = parent_task->td_level + 1; // increment nesting level
taskdata->td_untied_count = 0;
taskdata->td_ident = loc_ref;
taskdata->td_taskwait_ident = NULL;
taskdata->td_taskwait_counter = 0;
taskdata->td_taskwait_thread = 0;
KMP_DEBUG_ASSERT( taskdata->td_parent != NULL );
#if OMP_45_ENABLED
// avoid copying icvs for proxy tasks
if ( flags->proxy == TASK_FULL )
#endif
copy_icvs( &taskdata->td_icvs, &taskdata->td_parent->td_icvs );
taskdata->td_flags.tiedness = flags->tiedness;
taskdata->td_flags.final = flags->final;
taskdata->td_flags.merged_if0 = flags->merged_if0;
#if OMP_40_ENABLED
taskdata->td_flags.destructors_thunk = flags->destructors_thunk;
#endif // OMP_40_ENABLED
#if OMP_45_ENABLED
taskdata->td_flags.proxy = flags->proxy;
taskdata->td_task_team = thread->th.th_task_team;
taskdata->td_size_alloc = shareds_offset + sizeof_shareds;
#endif
taskdata->td_flags.tasktype = TASK_EXPLICIT;
// GEH - TODO: fix this to copy parent task's value of tasking_ser flag
taskdata->td_flags.tasking_ser = ( __kmp_tasking_mode == tskm_immediate_exec );
// GEH - TODO: fix this to copy parent task's value of team_serial flag
taskdata->td_flags.team_serial = ( team->t.t_serialized ) ? 1 : 0;
// GEH - Note we serialize the task if the team is serialized to make sure implicit parallel region
// tasks are not left until program termination to execute. Also, it helps locality to execute
// immediately.
taskdata->td_flags.task_serial = ( parent_task->td_flags.final
|| taskdata->td_flags.team_serial || taskdata->td_flags.tasking_ser );
taskdata->td_flags.started = 0;
taskdata->td_flags.executing = 0;
taskdata->td_flags.complete = 0;
taskdata->td_flags.freed = 0;
taskdata->td_flags.native = flags->native;
taskdata->td_incomplete_child_tasks = 0;
taskdata->td_allocated_child_tasks = 1; // start at one because counts current task and children
#if OMP_40_ENABLED
taskdata->td_taskgroup = parent_task->td_taskgroup; // task inherits the taskgroup from the parent task
taskdata->td_dephash = NULL;
taskdata->td_depnode = NULL;
#endif
// Only need to keep track of child task counts if team parallel and tasking not serialized or if it is a proxy task
#if OMP_45_ENABLED
if ( flags->proxy == TASK_PROXY || !( taskdata -> td_flags.team_serial || taskdata -> td_flags.tasking_ser ) )
#else
if ( !( taskdata -> td_flags.team_serial || taskdata -> td_flags.tasking_ser ) )
#endif
{
KMP_TEST_THEN_INC32( (kmp_int32 *)(& parent_task->td_incomplete_child_tasks) );
#if OMP_40_ENABLED
if ( parent_task->td_taskgroup )
KMP_TEST_THEN_INC32( (kmp_int32 *)(& parent_task->td_taskgroup->count) );
#endif
// Only need to keep track of allocated child tasks for explicit tasks since implicit not deallocated
if ( taskdata->td_parent->td_flags.tasktype == TASK_EXPLICIT ) {
KMP_TEST_THEN_INC32( (kmp_int32 *)(& taskdata->td_parent->td_allocated_child_tasks) );
}
}
KA_TRACE(20, ("__kmp_task_alloc(exit): T#%d created task %p parent=%p\n",
gtid, taskdata, taskdata->td_parent) );
ANNOTATE_HAPPENS_BEFORE(task);
#if OMPT_SUPPORT
__kmp_task_init_ompt(taskdata, gtid, (void*) task_entry);
#endif
return task;
}
kmp_task_t *
__kmpc_omp_task_alloc( ident_t *loc_ref, kmp_int32 gtid, kmp_int32 flags,
size_t sizeof_kmp_task_t, size_t sizeof_shareds,
kmp_routine_entry_t task_entry )
{
kmp_task_t *retval;
kmp_tasking_flags_t *input_flags = (kmp_tasking_flags_t *) & flags;
input_flags->native = FALSE;
// __kmp_task_alloc() sets up all other runtime flags
#if OMP_45_ENABLED
KA_TRACE(10, ("__kmpc_omp_task_alloc(enter): T#%d loc=%p, flags=(%s %s) "
"sizeof_task=%ld sizeof_shared=%ld entry=%p\n",
gtid, loc_ref, input_flags->tiedness ? "tied " : "untied",
input_flags->proxy ? "proxy" : "",
sizeof_kmp_task_t, sizeof_shareds, task_entry) );
#else
KA_TRACE(10, ("__kmpc_omp_task_alloc(enter): T#%d loc=%p, flags=(%s) "
"sizeof_task=%ld sizeof_shared=%ld entry=%p\n",
gtid, loc_ref, input_flags->tiedness ? "tied " : "untied",
sizeof_kmp_task_t, sizeof_shareds, task_entry) );
#endif
// PVL: Notify tool about start of task creation
#if OMPT_SUPPORT
kmp_info_t *thread = __kmp_threads[ gtid ];
kmp_taskdata_t *parent_task = thread->th.th_current_task;
if (ompt_enabled) {
if (ompt_callbacks.ompt_callback(ext_callback_task_create_begin)) {
ompt_callbacks.ompt_callback(ext_callback_task_create_begin)(
parent_task ? &(parent_task->ompt_task_info.task_data) : NULL,
parent_task ? &(parent_task->ompt_task_info.frame) : NULL,
ompt_task_explicit
);
}
}
#endif
// PVL: Taskdata and task structures do not exist before this point
retval = __kmp_task_alloc( loc_ref, gtid, input_flags, sizeof_kmp_task_t,
sizeof_shareds, task_entry );
KA_TRACE(20, ("__kmpc_omp_task_alloc(exit): T#%d retval %p\n", gtid, retval) );
return retval;
}
//-----------------------------------------------------------
// __kmp_invoke_task: invoke the specified task
//
// gtid: global thread ID of caller
// task: the task to invoke
// current_task: the task to resume after task invokation
static void
__kmp_invoke_task( kmp_int32 gtid, kmp_task_t *task, kmp_taskdata_t * current_task )
{
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(task);
kmp_uint64 cur_time;
#if OMP_40_ENABLED
int discard = 0 /* false */;
#endif
KA_TRACE(30, ("__kmp_invoke_task(enter): T#%d invoking task %p, current_task=%p\n",
gtid, taskdata, current_task) );
KMP_DEBUG_ASSERT(task);
#if OMP_45_ENABLED
if ( taskdata->td_flags.proxy == TASK_PROXY &&
taskdata->td_flags.complete == 1)
{
// This is a proxy task that was already completed but it needs to run
// its bottom-half finish
KA_TRACE(30, ("__kmp_invoke_task: T#%d running bottom finish for proxy task %p\n",
gtid, taskdata) );
__kmp_bottom_half_finish_proxy(gtid,task);
KA_TRACE(30, ("__kmp_invoke_task(exit): T#%d completed bottom finish for proxy task %p, resuming task %p\n", gtid, taskdata, current_task) );
return;
}
#endif
#if USE_ITT_BUILD && USE_ITT_NOTIFY
if(__kmp_forkjoin_frames_mode == 3) {
// Get the current time stamp to measure task execution time to correct barrier imbalance time
cur_time = __itt_get_timestamp();
}
#endif
#if OMP_45_ENABLED
// Proxy tasks are not handled by the runtime
if ( taskdata->td_flags.proxy != TASK_PROXY ) {
#endif
ANNOTATE_HAPPENS_AFTER(task);
__kmp_task_start( gtid, task, current_task );
#if OMP_45_ENABLED
}
#endif
#if OMPT_SUPPORT
ompt_thread_info_t oldInfo;
kmp_info_t * thread;
if (ompt_enabled) {
// Store the threads states and restore them after the task
thread = __kmp_threads[ gtid ];
oldInfo = thread->th.ompt_thread_info;
thread->th.ompt_thread_info.wait_id = 0;
thread->th.ompt_thread_info.state = ompt_state_work_parallel;
taskdata->ompt_task_info.frame.exit_runtime_frame = OMPT_GET_FRAME_ADDRESS(0);
}
#endif
#if OMP_40_ENABLED
// TODO: cancel tasks if the parallel region has also been cancelled
// TODO: check if this sequence can be hoisted above __kmp_task_start
// if cancellation has been enabled for this run ...
if (__kmp_omp_cancellation) {
kmp_info_t *this_thr = __kmp_threads [ gtid ];
kmp_team_t * this_team = this_thr->th.th_team;
kmp_taskgroup_t * taskgroup = taskdata->td_taskgroup;
if ((taskgroup && taskgroup->cancel_request) || (this_team->t.t_cancel_request == cancel_parallel)) {
#if OMPT_SUPPORT && OMPT_OPTIONAL
ompt_task_data_t *task_data;
__ompt_get_task_info_internal(0, NULL, &task_data, NULL, NULL, NULL);
if (ompt_enabled &&
ompt_callbacks.ompt_callback(ompt_callback_cancel)) {
ompt_callbacks.ompt_callback(ompt_callback_cancel)(
task_data,
((taskgroup && taskgroup->cancel_request) ? ompt_cancel_taskgroup : ompt_cancel_parallel) | ompt_cancel_discarded_task,
OMPT_GET_RETURN_ADDRESS(0));
}
#endif
KMP_COUNT_BLOCK(TASK_cancelled);
// this task belongs to a task group and we need to cancel it
discard = 1 /* true */;
}
}
//
// Invoke the task routine and pass in relevant data.
// Thunks generated by gcc take a different argument list.
//
if (!discard) {
#if KMP_STATS_ENABLED
KMP_COUNT_BLOCK(TASK_executed);
switch(KMP_GET_THREAD_STATE()) {
case FORK_JOIN_BARRIER: KMP_PUSH_PARTITIONED_TIMER(OMP_task_join_bar); break;
case PLAIN_BARRIER: KMP_PUSH_PARTITIONED_TIMER(OMP_task_plain_bar); break;
case TASKYIELD: KMP_PUSH_PARTITIONED_TIMER(OMP_task_taskyield); break;
case TASKWAIT: KMP_PUSH_PARTITIONED_TIMER(OMP_task_taskwait); break;
case TASKGROUP: KMP_PUSH_PARTITIONED_TIMER(OMP_task_taskgroup); break;
default: KMP_PUSH_PARTITIONED_TIMER(OMP_task_immediate); break;
}
#endif // KMP_STATS_ENABLED
#endif // OMP_40_ENABLED
#ifdef KMP_GOMP_COMPAT
if (taskdata->td_flags.native) {
((void (*)(void *))(*(task->routine)))(task->shareds);
}
else
#endif /* KMP_GOMP_COMPAT */
{
(*(task->routine))(gtid, task);
}
KMP_POP_PARTITIONED_TIMER();
#if OMP_40_ENABLED
}
#endif // OMP_40_ENABLED
#if OMPT_SUPPORT
if (ompt_enabled) {
thread->th.ompt_thread_info = oldInfo;
taskdata->ompt_task_info.frame.exit_runtime_frame = NULL;
}
#endif
#if OMP_45_ENABLED
// Proxy tasks are not handled by the runtime
if ( taskdata->td_flags.proxy != TASK_PROXY ) {
#endif
ANNOTATE_HAPPENS_BEFORE(taskdata->td_parent);
__kmp_task_finish( gtid, task, current_task );
#if OMP_45_ENABLED
}
#endif
#if USE_ITT_BUILD && USE_ITT_NOTIFY
// Barrier imbalance - correct arrive time after the task finished
if(__kmp_forkjoin_frames_mode == 3) {
kmp_info_t *this_thr = __kmp_threads [ gtid ];
if(this_thr->th.th_bar_arrive_time) {
this_thr->th.th_bar_arrive_time += (__itt_get_timestamp() - cur_time);
}
}
#endif
KA_TRACE(30, ("__kmp_invoke_task(exit): T#%d completed task %p, resuming task %p\n",
gtid, taskdata, current_task) );
return;
}
//-----------------------------------------------------------------------
// __kmpc_omp_task_parts: Schedule a thread-switchable task for execution
//
// loc_ref: location of original task pragma (ignored)
// gtid: Global Thread ID of encountering thread
// new_task: task thunk allocated by __kmp_omp_task_alloc() for the ''new task''
// Returns:
// TASK_CURRENT_NOT_QUEUED (0) if did not suspend and queue current task to be resumed later.
// TASK_CURRENT_QUEUED (1) if suspended and queued the current task to be resumed later.
kmp_int32
__kmpc_omp_task_parts( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t * new_task)
{
kmp_taskdata_t * new_taskdata = KMP_TASK_TO_TASKDATA(new_task);
KA_TRACE(10, ("__kmpc_omp_task_parts(enter): T#%d loc=%p task=%p\n",
gtid, loc_ref, new_taskdata ) );
#if OMPT_SUPPORT
kmp_taskdata_t *parent;
if (ompt_enabled) {
parent = new_taskdata->td_parent;
parent->ompt_task_info.frame.reenter_runtime_frame =
OMPT_GET_FRAME_ADDRESS(1);
if (ompt_callbacks.ompt_callback(ompt_callback_task_create)) {
ompt_task_data_t task_data = ompt_task_id_none;
ompt_callbacks.ompt_callback(ompt_callback_task_create)(
parent ? &(parent->ompt_task_info.task_data) : &task_data,
parent ? &(parent->ompt_task_info.frame) : NULL,
&(new_taskdata->ompt_task_info.task_data),
ompt_task_explicit,
0,
new_taskdata->ompt_task_info.function);
}
}
#endif
/* Should we execute the new task or queue it? For now, let's just always try to
queue it. If the queue fills up, then we'll execute it. */
if ( __kmp_push_task( gtid, new_task ) == TASK_NOT_PUSHED ) // if cannot defer
{ // Execute this task immediately
kmp_taskdata_t * current_task = __kmp_threads[ gtid ] -> th.th_current_task;
new_taskdata->td_flags.task_serial = 1;
__kmp_invoke_task( gtid, new_task, current_task );
}
KA_TRACE(10, ("__kmpc_omp_task_parts(exit): T#%d returning TASK_CURRENT_NOT_QUEUED: "
"loc=%p task=%p, return: TASK_CURRENT_NOT_QUEUED\n", gtid, loc_ref,
new_taskdata ) );
ANNOTATE_HAPPENS_BEFORE(new_task);
#if OMPT_SUPPORT
if (ompt_enabled) {
parent->ompt_task_info.frame.reenter_runtime_frame =
NULL;
}
#endif
return TASK_CURRENT_NOT_QUEUED;
}
//---------------------------------------------------------------------
// __kmp_omp_task: Schedule a non-thread-switchable task for execution
// gtid: Global Thread ID of encountering thread
// new_task: non-thread-switchable task thunk allocated by __kmp_omp_task_alloc()
// serialize_immediate: if TRUE then if the task is executed immediately its execution will be serialized
// returns:
//
// TASK_CURRENT_NOT_QUEUED (0) if did not suspend and queue current task to be resumed later.
// TASK_CURRENT_QUEUED (1) if suspended and queued the current task to be resumed later.
kmp_int32
__kmp_omp_task( kmp_int32 gtid, kmp_task_t * new_task, bool serialize_immediate )
{
kmp_taskdata_t * new_taskdata = KMP_TASK_TO_TASKDATA(new_task);
#if OMPT_SUPPORT
if (ompt_enabled) {
new_taskdata->ompt_task_info.frame.reenter_runtime_frame =
OMPT_GET_FRAME_ADDRESS(1);
}
#endif
#if OMP_45_ENABLED
// TODO: (PVL) Call ompt_callback_task_create for proxy tasks as well
if ( new_taskdata->td_flags.proxy == TASK_PROXY ) {
kmp_taskdata_t * current_task = __kmp_threads[ gtid ] -> th.th_current_task;
if ( serialize_immediate )
new_taskdata -> td_flags.task_serial = 1;
__kmp_invoke_task( gtid, new_task, current_task );
}
else {
#endif
// Attempt to push
kmp_int32 push_ret = __kmp_push_task(gtid, new_task);
/* Should we execute the new task or queue it? For now, let's just always try to
queue it. If the queue fills up, then we'll execute it. */
if (push_ret == TASK_NOT_PUSHED) // if cannot defer
{ // Execute this task immediately
kmp_taskdata_t *current_task = __kmp_threads[gtid]->th.th_current_task;
if (serialize_immediate)
new_taskdata->td_flags.task_serial = 1;
__kmp_invoke_task(gtid, new_task, current_task);
}
#if OMP_45_ENABLED
}
#endif
#if OMPT_SUPPORT
if (ompt_enabled) {
new_taskdata->ompt_task_info.frame.reenter_runtime_frame = NULL;
}
#endif
ANNOTATE_HAPPENS_BEFORE(new_task);
return TASK_CURRENT_NOT_QUEUED;
}
//---------------------------------------------------------------------
// __kmpc_omp_task: Wrapper around __kmp_omp_task to schedule a non-thread-switchable task from
// the parent thread only!
// loc_ref: location of original task pragma (ignored)
// gtid: Global Thread ID of encountering thread
// new_task: non-thread-switchable task thunk allocated by __kmp_omp_task_alloc()
// returns:
//
// TASK_CURRENT_NOT_QUEUED (0) if did not suspend and queue current task to be resumed later.
// TASK_CURRENT_QUEUED (1) if suspended and queued the current task to be resumed later.
kmp_int32
__kmpc_omp_task( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t * new_task)
{
kmp_int32 res;
KMP_SET_THREAD_STATE_BLOCK(EXPLICIT_TASK);
#if KMP_DEBUG || OMPT_SUPPORT
kmp_taskdata_t * new_taskdata = KMP_TASK_TO_TASKDATA(new_task);
#endif
KA_TRACE(10, ("__kmpc_omp_task(enter): T#%d loc=%p task=%p\n",
gtid, loc_ref, new_taskdata ) );
#if OMPT_SUPPORT
kmp_taskdata_t *parent;
if (ompt_enabled) {
parent = new_taskdata->td_parent;
parent->ompt_task_info.frame.reenter_runtime_frame =
OMPT_GET_FRAME_ADDRESS(1);
if (ompt_callbacks.ompt_callback(ompt_callback_task_create)) {
ompt_task_data_t task_data = ompt_task_id_none;
ompt_callbacks.ompt_callback(ompt_callback_task_create)(
parent ? &(parent->ompt_task_info.task_data) : &task_data,
parent ? &(parent->ompt_task_info.frame) : NULL,
&(new_taskdata->ompt_task_info.task_data),
ompt_task_explicit,
0,
new_taskdata->ompt_task_info.function);
}
}
#endif
res = __kmp_omp_task(gtid,new_task,true);
KA_TRACE(10, ("__kmpc_omp_task(exit): T#%d returning TASK_CURRENT_NOT_QUEUED: loc=%p task=%p\n",
gtid, loc_ref, new_taskdata ) );
#if OMPT_SUPPORT
if (ompt_enabled) {
parent = new_taskdata->td_parent;
parent->ompt_task_info.frame.reenter_runtime_frame =
NULL;
}
#endif
return res;
}
//-------------------------------------------------------------------------------------
// __kmpc_omp_taskwait: Wait until all tasks generated by the current task are complete
kmp_int32
__kmpc_omp_taskwait( ident_t *loc_ref, kmp_int32 gtid )
{
kmp_taskdata_t * taskdata;
kmp_info_t * thread;
int thread_finished = FALSE;
KMP_SET_THREAD_STATE_BLOCK(TASKWAIT);
KA_TRACE(10, ("__kmpc_omp_taskwait(enter): T#%d loc=%p\n", gtid, loc_ref) );
if ( __kmp_tasking_mode != tskm_immediate_exec ) {
// GEH TODO: shouldn't we have some sort of OMPRAP API calls here to mark begin wait?
thread = __kmp_threads[ gtid ];
taskdata = thread -> th.th_current_task;
#if OMPT_SUPPORT && OMPT_OPTIONAL
ompt_task_data_t my_task_data;
ompt_parallel_data_t my_parallel_data;
if (ompt_enabled) {
kmp_team_t *team = thread->th.th_team;
my_task_data = taskdata->ompt_task_info.task_data;
my_parallel_data = team->t.ompt_team_info.parallel_data;
taskdata->ompt_task_info.frame.reenter_runtime_frame = OMPT_GET_FRAME_ADDRESS(0);
if (ompt_callbacks.ompt_callback(ompt_callback_sync_region)) {
ompt_callbacks.ompt_callback(ompt_callback_sync_region)(
ompt_sync_region_taskwait,
ompt_scope_begin,
&(my_parallel_data),
&(my_task_data),
OMPT_GET_RETURN_ADDRESS(1));
}
}
#endif
// Debugger: The taskwait is active. Store location and thread encountered the taskwait.
#if USE_ITT_BUILD
// Note: These values are used by ITT events as well.
#endif /* USE_ITT_BUILD */
taskdata->td_taskwait_counter += 1;
taskdata->td_taskwait_ident = loc_ref;
taskdata->td_taskwait_thread = gtid + 1;
#if USE_ITT_BUILD
void * itt_sync_obj = __kmp_itt_taskwait_object( gtid );
if ( itt_sync_obj != NULL )
__kmp_itt_taskwait_starting( gtid, itt_sync_obj );
#endif /* USE_ITT_BUILD */
bool must_wait = ! taskdata->td_flags.team_serial && ! taskdata->td_flags.final;
#if OMP_45_ENABLED
must_wait = must_wait || (thread->th.th_task_team != NULL && thread->th.th_task_team->tt.tt_found_proxy_tasks);
#endif
if (must_wait)
{
kmp_flag_32 flag(&(taskdata->td_incomplete_child_tasks), 0U);
while ( TCR_4(taskdata -> td_incomplete_child_tasks) != 0 ) {
flag.execute_tasks(thread, gtid, FALSE, &thread_finished
USE_ITT_BUILD_ARG(itt_sync_obj), __kmp_task_stealing_constraint );
}
}
#if USE_ITT_BUILD
if ( itt_sync_obj != NULL )
__kmp_itt_taskwait_finished( gtid, itt_sync_obj );
#endif /* USE_ITT_BUILD */
// GEH TODO: shouldn't we have some sort of OMPRAP API calls here to mark end of wait?
// Debugger: The taskwait is completed. Location remains, but thread is negated.
taskdata->td_taskwait_thread = - taskdata->td_taskwait_thread;
#if OMPT_SUPPORT && OMPT_OPTIONAL
if (ompt_enabled) {
if (ompt_callbacks.ompt_callback(ompt_callback_sync_region)) {
ompt_callbacks.ompt_callback(ompt_callback_sync_region)(
ompt_sync_region_taskwait,
ompt_scope_end,
&(my_parallel_data),
&(my_task_data),
OMPT_GET_RETURN_ADDRESS(1));
}
taskdata->ompt_task_info.frame.reenter_runtime_frame = NULL;
}
#endif
ANNOTATE_HAPPENS_AFTER(taskdata);
}
KA_TRACE(10, ("__kmpc_omp_taskwait(exit): T#%d task %p finished waiting, "
"returning TASK_CURRENT_NOT_QUEUED\n", gtid, taskdata) );
return TASK_CURRENT_NOT_QUEUED;
}
//-------------------------------------------------
// __kmpc_omp_taskyield: switch to a different task
kmp_int32
__kmpc_omp_taskyield( ident_t *loc_ref, kmp_int32 gtid, int end_part )
{
kmp_taskdata_t * taskdata;
kmp_info_t * thread;
int thread_finished = FALSE;
KMP_COUNT_BLOCK(OMP_TASKYIELD);
KMP_SET_THREAD_STATE_BLOCK(TASKYIELD);
KA_TRACE(10, ("__kmpc_omp_taskyield(enter): T#%d loc=%p end_part = %d\n",
gtid, loc_ref, end_part) );
if ( __kmp_tasking_mode != tskm_immediate_exec && __kmp_init_parallel ) {
// GEH TODO: shouldn't we have some sort of OMPRAP API calls here to mark begin wait?
thread = __kmp_threads[ gtid ];
taskdata = thread -> th.th_current_task;
// Should we model this as a task wait or not?
// Debugger: The taskwait is active. Store location and thread encountered the taskwait.
#if USE_ITT_BUILD
// Note: These values are used by ITT events as well.
#endif /* USE_ITT_BUILD */
taskdata->td_taskwait_counter += 1;
taskdata->td_taskwait_ident = loc_ref;
taskdata->td_taskwait_thread = gtid + 1;
#if USE_ITT_BUILD
void * itt_sync_obj = __kmp_itt_taskwait_object( gtid );
if ( itt_sync_obj != NULL )
__kmp_itt_taskwait_starting( gtid, itt_sync_obj );
#endif /* USE_ITT_BUILD */
if ( ! taskdata->td_flags.team_serial ) {
kmp_task_team_t * task_team = thread->th.th_task_team;
if (task_team != NULL) {
if (KMP_TASKING_ENABLED(task_team)) {
__kmp_execute_tasks_32( thread, gtid, NULL, FALSE, &thread_finished
USE_ITT_BUILD_ARG(itt_sync_obj), __kmp_task_stealing_constraint );
}
}
}
#if USE_ITT_BUILD
if ( itt_sync_obj != NULL )
__kmp_itt_taskwait_finished( gtid, itt_sync_obj );
#endif /* USE_ITT_BUILD */
// GEH TODO: shouldn't we have some sort of OMPRAP API calls here to mark end of wait?
// Debugger: The taskwait is completed. Location remains, but thread is negated.
taskdata->td_taskwait_thread = - taskdata->td_taskwait_thread;
}
KA_TRACE(10, ("__kmpc_omp_taskyield(exit): T#%d task %p resuming, "
"returning TASK_CURRENT_NOT_QUEUED\n", gtid, taskdata) );
return TASK_CURRENT_NOT_QUEUED;
}
#if OMP_40_ENABLED
//-------------------------------------------------------------------------------------
// __kmpc_taskgroup: Start a new taskgroup
void
__kmpc_taskgroup( ident_t* loc, int gtid )
{
kmp_info_t * thread = __kmp_threads[ gtid ];
kmp_taskdata_t * taskdata = thread->th.th_current_task;
kmp_taskgroup_t * tg_new =
(kmp_taskgroup_t *)__kmp_thread_malloc( thread, sizeof( kmp_taskgroup_t ) );
KA_TRACE(10, ("__kmpc_taskgroup: T#%d loc=%p group=%p\n", gtid, loc, tg_new) );
tg_new->count = 0;
tg_new->cancel_request = cancel_noreq;
tg_new->parent = taskdata->td_taskgroup;
taskdata->td_taskgroup = tg_new;
#if OMPT_SUPPORT && OMPT_OPTIONAL
if (ompt_enabled &&
ompt_callbacks.ompt_callback(ompt_callback_sync_region)) {
kmp_team_t *team = thread->th.th_team;
ompt_task_data_t my_task_data = taskdata->ompt_task_info.task_data;
// FIXME: I think this is wrong for lwt!
ompt_parallel_data_t my_parallel_data = team->t.ompt_team_info.parallel_data;
ompt_callbacks.ompt_callback(ompt_callback_sync_region)(
ompt_sync_region_taskgroup,
ompt_scope_begin,
&(my_parallel_data),
&(my_task_data),
OMPT_GET_RETURN_ADDRESS(1));
}
#endif
}
//-------------------------------------------------------------------------------------
// __kmpc_end_taskgroup: Wait until all tasks generated by the current task
// and its descendants are complete
void
__kmpc_end_taskgroup( ident_t* loc, int gtid )
{
kmp_info_t * thread = __kmp_threads[ gtid ];
kmp_taskdata_t * taskdata = thread->th.th_current_task;
kmp_taskgroup_t * taskgroup = taskdata->td_taskgroup;
int thread_finished = FALSE;
KA_TRACE(10, ("__kmpc_end_taskgroup(enter): T#%d loc=%p\n", gtid, loc) );
KMP_DEBUG_ASSERT( taskgroup != NULL );
KMP_SET_THREAD_STATE_BLOCK(TASKGROUP);
if ( __kmp_tasking_mode != tskm_immediate_exec ) {
#if USE_ITT_BUILD
// For ITT the taskgroup wait is similar to taskwait until we need to distinguish them
void * itt_sync_obj = __kmp_itt_taskwait_object( gtid );
if ( itt_sync_obj != NULL )
__kmp_itt_taskwait_starting( gtid, itt_sync_obj );
#endif /* USE_ITT_BUILD */
#if OMP_45_ENABLED
if ( ! taskdata->td_flags.team_serial || (thread->th.th_task_team != NULL && thread->th.th_task_team->tt.tt_found_proxy_tasks) )
#else
if ( ! taskdata->td_flags.team_serial )
#endif
{
kmp_flag_32 flag(&(taskgroup->count), 0U);
while ( TCR_4(taskgroup->count) != 0 ) {
flag.execute_tasks(thread, gtid, FALSE, &thread_finished
USE_ITT_BUILD_ARG(itt_sync_obj), __kmp_task_stealing_constraint );
}
}
#if USE_ITT_BUILD
if ( itt_sync_obj != NULL )
__kmp_itt_taskwait_finished( gtid, itt_sync_obj );
#endif /* USE_ITT_BUILD */
}
KMP_DEBUG_ASSERT( taskgroup->count == 0 );
// Restore parent taskgroup for the current task
taskdata->td_taskgroup = taskgroup->parent;
__kmp_thread_free( thread, taskgroup );
KA_TRACE(10, ("__kmpc_end_taskgroup(exit): T#%d task %p finished waiting\n", gtid, taskdata) );
ANNOTATE_HAPPENS_AFTER(taskdata);
#if OMPT_SUPPORT && OMPT_OPTIONAL
if (ompt_enabled &&
ompt_callbacks.ompt_callback(ompt_callback_sync_region)) {
kmp_team_t *team = thread->th.th_team;
ompt_task_data_t my_task_data = taskdata->ompt_task_info.task_data;
// FIXME: I think this is wrong for lwt!
ompt_parallel_data_t my_parallel_data = team->t.ompt_team_info.parallel_data;
ompt_callbacks.ompt_callback(ompt_callback_sync_region)(
ompt_sync_region_taskgroup,
ompt_scope_end,
&(my_parallel_data),
&(my_task_data),
OMPT_GET_RETURN_ADDRESS(1));
}
#endif
}
#endif
//------------------------------------------------------
// __kmp_remove_my_task: remove a task from my own deque
static kmp_task_t *
__kmp_remove_my_task( kmp_info_t * thread, kmp_int32 gtid, kmp_task_team_t *task_team,
kmp_int32 is_constrained )
{
kmp_task_t * task;
kmp_taskdata_t * taskdata;
kmp_thread_data_t *thread_data;
kmp_uint32 tail;
KMP_DEBUG_ASSERT( __kmp_tasking_mode != tskm_immediate_exec );
KMP_DEBUG_ASSERT( task_team -> tt.tt_threads_data != NULL ); // Caller should check this condition
thread_data = & task_team -> tt.tt_threads_data[ __kmp_tid_from_gtid( gtid ) ];
KA_TRACE(10, ("__kmp_remove_my_task(enter): T#%d ntasks=%d head=%u tail=%u\n",
gtid, thread_data->td.td_deque_ntasks, thread_data->td.td_deque_head,
thread_data->td.td_deque_tail) );
if (TCR_4(thread_data -> td.td_deque_ntasks) == 0) {
KA_TRACE(10, ("__kmp_remove_my_task(exit #1): T#%d No tasks to remove: ntasks=%d head=%u tail=%u\n",
gtid, thread_data->td.td_deque_ntasks, thread_data->td.td_deque_head,
thread_data->td.td_deque_tail) );
return NULL;
}
__kmp_acquire_bootstrap_lock( & thread_data -> td.td_deque_lock );
if (TCR_4(thread_data -> td.td_deque_ntasks) == 0) {
__kmp_release_bootstrap_lock( & thread_data -> td.td_deque_lock );
KA_TRACE(10, ("__kmp_remove_my_task(exit #2): T#%d No tasks to remove: ntasks=%d head=%u tail=%u\n",
gtid, thread_data->td.td_deque_ntasks, thread_data->td.td_deque_head,
thread_data->td.td_deque_tail) );
return NULL;
}
tail = ( thread_data -> td.td_deque_tail - 1 ) & TASK_DEQUE_MASK(thread_data->td); // Wrap index.
taskdata = thread_data -> td.td_deque[ tail ];
if (is_constrained && (taskdata->td_flags.tiedness == TASK_TIED)) {
// we need to check if the candidate obeys task scheduling constraint:
// only child of current task can be scheduled
kmp_taskdata_t * current = thread->th.th_current_task;
kmp_int32 level = current->td_level;
kmp_taskdata_t * parent = taskdata->td_parent;
while ( parent != current && parent->td_level > level ) {
parent = parent->td_parent; // check generation up to the level of the current task
KMP_DEBUG_ASSERT(parent != NULL);
}
if ( parent != current ) {
// If the tail task is not a child, then no other child can appear in the deque.
__kmp_release_bootstrap_lock( & thread_data -> td.td_deque_lock );
KA_TRACE(10, ("__kmp_remove_my_task(exit #2): T#%d No tasks to remove: ntasks=%d head=%u tail=%u\n",
gtid, thread_data->td.td_deque_ntasks, thread_data->td.td_deque_head,
thread_data->td.td_deque_tail) );
return NULL;
}
}
thread_data -> td.td_deque_tail = tail;
TCW_4(thread_data -> td.td_deque_ntasks, thread_data -> td.td_deque_ntasks - 1);
__kmp_release_bootstrap_lock( & thread_data->td.td_deque_lock );
KA_TRACE(10, ("__kmp_remove_my_task(exit #2): T#%d task %p removed: ntasks=%d head=%u tail=%u\n",
gtid, taskdata, thread_data->td.td_deque_ntasks, thread_data->td.td_deque_head,
thread_data->td.td_deque_tail) );
task = KMP_TASKDATA_TO_TASK( taskdata );
return task;
}
//-----------------------------------------------------------
// __kmp_steal_task: remove a task from another thread's deque
// Assume that calling thread has already checked existence of
// task_team thread_data before calling this routine.
static kmp_task_t *
__kmp_steal_task( kmp_info_t *victim, kmp_int32 gtid, kmp_task_team_t *task_team,
volatile kmp_uint32 *unfinished_threads, int *thread_finished,
kmp_int32 is_constrained )
{
kmp_task_t * task;
kmp_taskdata_t * taskdata;
kmp_thread_data_t *victim_td, *threads_data;
kmp_int32 victim_tid;
KMP_DEBUG_ASSERT( __kmp_tasking_mode != tskm_immediate_exec );
threads_data = task_team -> tt.tt_threads_data;
KMP_DEBUG_ASSERT( threads_data != NULL ); // Caller should check this condition
victim_tid = victim->th.th_info.ds.ds_tid;
victim_td = & threads_data[ victim_tid ];
KA_TRACE(10, ("__kmp_steal_task(enter): T#%d try to steal from T#%d: task_team=%p ntasks=%d "
"head=%u tail=%u\n",
gtid, __kmp_gtid_from_thread( victim ), task_team, victim_td->td.td_deque_ntasks,
victim_td->td.td_deque_head, victim_td->td.td_deque_tail) );
if ( (TCR_4(victim_td -> td.td_deque_ntasks) == 0) || // Caller should not check this condition
(TCR_PTR(victim->th.th_task_team) != task_team)) // GEH: why would this happen?
{
KA_TRACE(10, ("__kmp_steal_task(exit #1): T#%d could not steal from T#%d: task_team=%p "
"ntasks=%d head=%u tail=%u\n",
gtid, __kmp_gtid_from_thread( victim ), task_team, victim_td->td.td_deque_ntasks,
victim_td->td.td_deque_head, victim_td->td.td_deque_tail) );
return NULL;
}
__kmp_acquire_bootstrap_lock( & victim_td -> td.td_deque_lock );
// Check again after we acquire the lock
if ( (TCR_4(victim_td -> td.td_deque_ntasks) == 0) ||
(TCR_PTR(victim->th.th_task_team) != task_team)) // GEH: why would this happen?
{
__kmp_release_bootstrap_lock( & victim_td -> td.td_deque_lock );
KA_TRACE(10, ("__kmp_steal_task(exit #2): T#%d could not steal from T#%d: task_team=%p "
"ntasks=%d head=%u tail=%u\n",
gtid, __kmp_gtid_from_thread( victim ), task_team, victim_td->td.td_deque_ntasks,
victim_td->td.td_deque_head, victim_td->td.td_deque_tail) );
return NULL;
}
KMP_DEBUG_ASSERT( victim_td -> td.td_deque != NULL );
taskdata = victim_td->td.td_deque[victim_td->td.td_deque_head];
if ( is_constrained ) {
// we need to check if the candidate obeys task scheduling constraint:
// only descendant of current task can be scheduled
kmp_taskdata_t * current = __kmp_threads[ gtid ]->th.th_current_task;
kmp_int32 level = current->td_level;
kmp_taskdata_t * parent = taskdata->td_parent;
while ( parent != current && parent->td_level > level ) {
parent = parent->td_parent; // check generation up to the level of the current task
KMP_DEBUG_ASSERT(parent != NULL);
}
if ( parent != current ) {
// If the head task is not a descendant of the current task then do not
// steal it. No other task in victim's deque can be a descendant of the
// current task.
__kmp_release_bootstrap_lock( & victim_td -> td.td_deque_lock );
KA_TRACE(10, ("__kmp_steal_task(exit #2): T#%d could not steal from T#%d: task_team=%p "
"ntasks=%d head=%u tail=%u\n",
gtid, __kmp_gtid_from_thread( threads_data[victim_tid].td.td_thr ),
task_team, victim_td->td.td_deque_ntasks,
victim_td->td.td_deque_head, victim_td->td.td_deque_tail) );
return NULL;
}
}
// Bump head pointer and Wrap.
victim_td->td.td_deque_head = (victim_td->td.td_deque_head + 1) & TASK_DEQUE_MASK(victim_td->td);
if (*thread_finished) {
// We need to un-mark this victim as a finished victim. This must be done before
// releasing the lock, or else other threads (starting with the master victim)
// might be prematurely released from the barrier!!!
kmp_uint32 count;
count = KMP_TEST_THEN_INC32( (kmp_int32 *)unfinished_threads );
KA_TRACE(20, ("__kmp_steal_task: T#%d inc unfinished_threads to %d: task_team=%p\n",
gtid, count + 1, task_team) );
*thread_finished = FALSE;
}
TCW_4(victim_td -> td.td_deque_ntasks, TCR_4(victim_td -> td.td_deque_ntasks) - 1);
__kmp_release_bootstrap_lock( & victim_td -> td.td_deque_lock );
KMP_COUNT_BLOCK(TASK_stolen);
KA_TRACE(10, ("__kmp_steal_task(exit #3): T#%d stole task %p from T#%d: task_team=%p "
"ntasks=%d head=%u tail=%u\n",
gtid, taskdata, __kmp_gtid_from_thread( victim ), task_team,
victim_td->td.td_deque_ntasks, victim_td->td.td_deque_head,
victim_td->td.td_deque_tail) );
task = KMP_TASKDATA_TO_TASK( taskdata );
return task;
}
//-----------------------------------------------------------------------------
// __kmp_execute_tasks_template: Choose and execute tasks until either the condition
// is statisfied (return true) or there are none left (return false).
// final_spin is TRUE if this is the spin at the release barrier.
// thread_finished indicates whether the thread is finished executing all
// the tasks it has on its deque, and is at the release barrier.
// spinner is the location on which to spin.
// spinner == NULL means only execute a single task and return.
// checker is the value to check to terminate the spin.
template <class C>
static inline int __kmp_execute_tasks_template(kmp_info_t *thread, kmp_int32 gtid, C *flag, int final_spin,
int *thread_finished
USE_ITT_BUILD_ARG(void * itt_sync_obj), kmp_int32 is_constrained)
{
kmp_task_team_t * task_team = thread->th.th_task_team;
kmp_thread_data_t * threads_data;
kmp_task_t * task;
kmp_info_t * other_thread;
kmp_taskdata_t * current_task = thread -> th.th_current_task;
volatile kmp_uint32 * unfinished_threads;
kmp_int32 nthreads, victim=-2, use_own_tasks=1, new_victim=0, tid=thread->th.th_info.ds.ds_tid;
KMP_DEBUG_ASSERT( __kmp_tasking_mode != tskm_immediate_exec );
KMP_DEBUG_ASSERT( thread == __kmp_threads[ gtid ] );
if (task_team == NULL) return FALSE;
KA_TRACE(15, ("__kmp_execute_tasks_template(enter): T#%d final_spin=%d *thread_finished=%d\n",
gtid, final_spin, *thread_finished) );
thread->th.th_reap_state = KMP_NOT_SAFE_TO_REAP;
threads_data = (kmp_thread_data_t *)TCR_PTR(task_team -> tt.tt_threads_data);
KMP_DEBUG_ASSERT( threads_data != NULL );
nthreads = task_team -> tt.tt_nproc;
unfinished_threads = &(task_team -> tt.tt_unfinished_threads);
#if OMP_45_ENABLED
KMP_DEBUG_ASSERT( nthreads > 1 || task_team->tt.tt_found_proxy_tasks);
#else
KMP_DEBUG_ASSERT( nthreads > 1 );
#endif
KMP_DEBUG_ASSERT( (int)(TCR_4(*unfinished_threads)) >= 0 );
while (1) { // Outer loop keeps trying to find tasks in case of single thread getting tasks from target constructs
while (1) { // Inner loop to find a task and execute it
task = NULL;
if (use_own_tasks) { // check on own queue first
task = __kmp_remove_my_task( thread, gtid, task_team, is_constrained );
}
if ((task == NULL) && (nthreads > 1)) { // Steal a task
int asleep = 1;
use_own_tasks = 0;
// Try to steal from the last place I stole from successfully.
if (victim == -2) { // haven't stolen anything yet
victim = threads_data[tid].td.td_deque_last_stolen;
if (victim != -1) // if we have a last stolen from victim, get the thread
other_thread = threads_data[victim].td.td_thr;
}
if (victim != -1) { // found last victim
asleep = 0;
}
else if (!new_victim) { // no recent steals and we haven't already used a new victim; select a random thread
do { // Find a different thread to steal work from.
// Pick a random thread. Initial plan was to cycle through all the threads, and only return if
// we tried to steal from every thread, and failed. Arch says that's not such a great idea.
victim = __kmp_get_random(thread) % (nthreads - 1);
if (victim >= tid) {
++victim; // Adjusts random distribution to exclude self
}
// Found a potential victim
other_thread = threads_data[victim].td.td_thr;
// There is a slight chance that __kmp_enable_tasking() did not wake up all threads
// waiting at the barrier. If victim is sleeping, then wake it up. Since we were going to
// pay the cache miss penalty for referencing another thread's kmp_info_t struct anyway,
// the check shouldn't cost too much performance at this point. In extra barrier mode, tasks
// do not sleep at the separate tasking barrier, so this isn't a problem.
asleep = 0;
if ( ( __kmp_tasking_mode == tskm_task_teams ) &&
(__kmp_dflt_blocktime != KMP_MAX_BLOCKTIME) &&
(TCR_PTR(other_thread->th.th_sleep_loc) != NULL)) {
asleep = 1;
__kmp_null_resume_wrapper(__kmp_gtid_from_thread(other_thread), other_thread->th.th_sleep_loc);
// A sleeping thread should not have any tasks on it's queue. There is a slight
// possibility that it resumes, steals a task from another thread, which spawns more
// tasks, all in the time that it takes this thread to check => don't write an assertion
// that the victim's queue is empty. Try stealing from a different thread.
}
} while (asleep);
}
if (!asleep) {
// We have a victim to try to steal from
task = __kmp_steal_task(other_thread, gtid, task_team, unfinished_threads, thread_finished, is_constrained);
}
if (task != NULL) { // set last stolen to victim
if (threads_data[tid].td.td_deque_last_stolen != victim) {
threads_data[tid].td.td_deque_last_stolen = victim;
// The pre-refactored code did not try more than 1 successful new vicitm,
// unless the last one generated more local tasks; new_victim keeps track of this
new_victim = 1;
}
}
else { // No tasks found; unset last_stolen
KMP_CHECK_UPDATE(threads_data[tid].td.td_deque_last_stolen, -1);
victim = -2; // no successful victim found
}
}
if (task == NULL) // break out of tasking loop
break;
// Found a task; execute it
#if USE_ITT_BUILD && USE_ITT_NOTIFY
if ( __itt_sync_create_ptr || KMP_ITT_DEBUG ) {
if ( itt_sync_obj == NULL ) { // we are at fork barrier where we could not get the object reliably
itt_sync_obj = __kmp_itt_barrier_object( gtid, bs_forkjoin_barrier );
}
__kmp_itt_task_starting( itt_sync_obj );
}
#endif /* USE_ITT_BUILD && USE_ITT_NOTIFY */
__kmp_invoke_task( gtid, task, current_task );
#if USE_ITT_BUILD
if ( itt_sync_obj != NULL ) __kmp_itt_task_finished( itt_sync_obj );
#endif /* USE_ITT_BUILD */
// If this thread is only partway through the barrier and the condition is met, then return now,
// so that the barrier gather/release pattern can proceed. If this thread is in the last spin loop
// in the barrier, waiting to be released, we know that the termination condition will not be
// satisified, so don't waste any cycles checking it.
if (flag == NULL || (!final_spin && flag->done_check())) {
KA_TRACE(15, ("__kmp_execute_tasks_template: T#%d spin condition satisfied\n", gtid) );
return TRUE;
}
if (thread->th.th_task_team == NULL) {
break;
}
KMP_YIELD( __kmp_library == library_throughput ); // Yield before executing next task
// If execution of a stolen task results in more tasks being placed on our run queue, reset use_own_tasks
if (!use_own_tasks && TCR_4(threads_data[tid].td.td_deque_ntasks) != 0) {
KA_TRACE(20, ("__kmp_execute_tasks_template: T#%d stolen task spawned other tasks, restart\n", gtid));
use_own_tasks = 1;
new_victim = 0;
}
}
// The task source has been exhausted. If in final spin loop of barrier, check if termination condition is satisfied.
#if OMP_45_ENABLED
// The work queue may be empty but there might be proxy tasks still executing
if (final_spin && TCR_4(current_task->td_incomplete_child_tasks) == 0)
#else
if (final_spin)
#endif
{
// First, decrement the #unfinished threads, if that has not already been done. This decrement
// might be to the spin location, and result in the termination condition being satisfied.
if (! *thread_finished) {
kmp_uint32 count;
count = KMP_TEST_THEN_DEC32( (kmp_int32 *)unfinished_threads ) - 1;
KA_TRACE(20, ("__kmp_execute_tasks_template: T#%d dec unfinished_threads to %d task_team=%p\n",
gtid, count, task_team) );
*thread_finished = TRUE;
}
// It is now unsafe to reference thread->th.th_team !!!
// Decrementing task_team->tt.tt_unfinished_threads can allow the master thread to pass through
// the barrier, where it might reset each thread's th.th_team field for the next parallel region.
// If we can steal more work, we know that this has not happened yet.
if (flag != NULL && flag->done_check()) {
KA_TRACE(15, ("__kmp_execute_tasks_template: T#%d spin condition satisfied\n", gtid) );
return TRUE;
}
}
// If this thread's task team is NULL, master has recognized that there are no more tasks; bail out
if (thread->th.th_task_team == NULL) {
KA_TRACE(15, ("__kmp_execute_tasks_template: T#%d no more tasks\n", gtid) );
return FALSE;
}
#if OMP_45_ENABLED
// We could be getting tasks from target constructs; if this is the only thread, keep trying to execute
// tasks from own queue
if (nthreads == 1)
use_own_tasks = 1;
else
#endif
{
KA_TRACE(15, ("__kmp_execute_tasks_template: T#%d can't find work\n", gtid) );
return FALSE;
}
}
}
int __kmp_execute_tasks_32(kmp_info_t *thread, kmp_int32 gtid, kmp_flag_32 *flag, int final_spin,
int *thread_finished
USE_ITT_BUILD_ARG(void * itt_sync_obj), kmp_int32 is_constrained)
{
return __kmp_execute_tasks_template(thread, gtid, flag, final_spin, thread_finished
USE_ITT_BUILD_ARG(itt_sync_obj), is_constrained);
}
int __kmp_execute_tasks_64(kmp_info_t *thread, kmp_int32 gtid, kmp_flag_64 *flag, int final_spin,
int *thread_finished
USE_ITT_BUILD_ARG(void * itt_sync_obj), kmp_int32 is_constrained)
{
return __kmp_execute_tasks_template(thread, gtid, flag, final_spin, thread_finished
USE_ITT_BUILD_ARG(itt_sync_obj), is_constrained);
}
int __kmp_execute_tasks_oncore(kmp_info_t *thread, kmp_int32 gtid, kmp_flag_oncore *flag, int final_spin,
int *thread_finished
USE_ITT_BUILD_ARG(void * itt_sync_obj), kmp_int32 is_constrained)
{
return __kmp_execute_tasks_template(thread, gtid, flag, final_spin, thread_finished
USE_ITT_BUILD_ARG(itt_sync_obj), is_constrained);
}
//-----------------------------------------------------------------------------
// __kmp_enable_tasking: Allocate task team and resume threads sleeping at the
// next barrier so they can assist in executing enqueued tasks.
// First thread in allocates the task team atomically.
static void
__kmp_enable_tasking( kmp_task_team_t *task_team, kmp_info_t *this_thr )
{
kmp_thread_data_t *threads_data;
int nthreads, i, is_init_thread;
KA_TRACE( 10, ( "__kmp_enable_tasking(enter): T#%d\n",
__kmp_gtid_from_thread( this_thr ) ) );
KMP_DEBUG_ASSERT(task_team != NULL);
KMP_DEBUG_ASSERT(this_thr->th.th_team != NULL);
nthreads = task_team->tt.tt_nproc;
KMP_DEBUG_ASSERT(nthreads > 0);
KMP_DEBUG_ASSERT(nthreads == this_thr->th.th_team->t.t_nproc);
// Allocate or increase the size of threads_data if necessary
is_init_thread = __kmp_realloc_task_threads_data( this_thr, task_team );
if (!is_init_thread) {
// Some other thread already set up the array.
KA_TRACE( 20, ( "__kmp_enable_tasking(exit): T#%d: threads array already set up.\n",
__kmp_gtid_from_thread( this_thr ) ) );
return;
}
threads_data = (kmp_thread_data_t *)TCR_PTR(task_team -> tt.tt_threads_data);
KMP_DEBUG_ASSERT( threads_data != NULL );
if ( ( __kmp_tasking_mode == tskm_task_teams ) &&
( __kmp_dflt_blocktime != KMP_MAX_BLOCKTIME ) )
{
// Release any threads sleeping at the barrier, so that they can steal
// tasks and execute them. In extra barrier mode, tasks do not sleep
// at the separate tasking barrier, so this isn't a problem.
for (i = 0; i < nthreads; i++) {
volatile void *sleep_loc;
kmp_info_t *thread = threads_data[i].td.td_thr;
if (i == this_thr->th.th_info.ds.ds_tid) {
continue;
}
// Since we haven't locked the thread's suspend mutex lock at this
// point, there is a small window where a thread might be putting
// itself to sleep, but hasn't set the th_sleep_loc field yet.
// To work around this, __kmp_execute_tasks_template() periodically checks
// see if other threads are sleeping (using the same random
// mechanism that is used for task stealing) and awakens them if
// they are.
if ( ( sleep_loc = TCR_PTR( thread -> th.th_sleep_loc) ) != NULL )
{
KF_TRACE( 50, ( "__kmp_enable_tasking: T#%d waking up thread T#%d\n",
__kmp_gtid_from_thread( this_thr ),
__kmp_gtid_from_thread( thread ) ) );
__kmp_null_resume_wrapper(__kmp_gtid_from_thread(thread), sleep_loc);
}
else {
KF_TRACE( 50, ( "__kmp_enable_tasking: T#%d don't wake up thread T#%d\n",
__kmp_gtid_from_thread( this_thr ),
__kmp_gtid_from_thread( thread ) ) );
}
}
}
KA_TRACE( 10, ( "__kmp_enable_tasking(exit): T#%d\n",
__kmp_gtid_from_thread( this_thr ) ) );
}
/* ------------------------------------------------------------------------ */
/* // TODO: Check the comment consistency
* Utility routines for "task teams". A task team (kmp_task_t) is kind of
* like a shadow of the kmp_team_t data struct, with a different lifetime.
* After a child * thread checks into a barrier and calls __kmp_release() from
* the particular variant of __kmp_<barrier_kind>_barrier_gather(), it can no
* longer assume that the kmp_team_t structure is intact (at any moment, the
* master thread may exit the barrier code and free the team data structure,
* and return the threads to the thread pool).
*
* This does not work with the the tasking code, as the thread is still
* expected to participate in the execution of any tasks that may have been
* spawned my a member of the team, and the thread still needs access to all
* to each thread in the team, so that it can steal work from it.
*
* Enter the existence of the kmp_task_team_t struct. It employs a reference
* counting mechanims, and is allocated by the master thread before calling
* __kmp_<barrier_kind>_release, and then is release by the last thread to
* exit __kmp_<barrier_kind>_release at the next barrier. I.e. the lifetimes
* of the kmp_task_team_t structs for consecutive barriers can overlap
* (and will, unless the master thread is the last thread to exit the barrier
* release phase, which is not typical).
*
* The existence of such a struct is useful outside the context of tasking,
* but for now, I'm trying to keep it specific to the OMP_30_ENABLED macro,
* so that any performance differences show up when comparing the 2.5 vs. 3.0
* libraries.
*
* We currently use the existence of the threads array as an indicator that
* tasks were spawned since the last barrier. If the structure is to be
* useful outside the context of tasking, then this will have to change, but
* not settting the field minimizes the performance impact of tasking on
* barriers, when no explicit tasks were spawned (pushed, actually).
*/
static kmp_task_team_t *__kmp_free_task_teams = NULL; // Free list for task_team data structures
// Lock for task team data structures
static kmp_bootstrap_lock_t __kmp_task_team_lock = KMP_BOOTSTRAP_LOCK_INITIALIZER( __kmp_task_team_lock );
//------------------------------------------------------------------------------
// __kmp_alloc_task_deque:
// Allocates a task deque for a particular thread, and initialize the necessary
// data structures relating to the deque. This only happens once per thread
// per task team since task teams are recycled.
// No lock is needed during allocation since each thread allocates its own
// deque.
static void
__kmp_alloc_task_deque( kmp_info_t *thread, kmp_thread_data_t *thread_data )
{
__kmp_init_bootstrap_lock( & thread_data -> td.td_deque_lock );
KMP_DEBUG_ASSERT( thread_data -> td.td_deque == NULL );
// Initialize last stolen task field to "none"
thread_data -> td.td_deque_last_stolen = -1;
KMP_DEBUG_ASSERT( TCR_4(thread_data -> td.td_deque_ntasks) == 0 );
KMP_DEBUG_ASSERT( thread_data -> td.td_deque_head == 0 );
KMP_DEBUG_ASSERT( thread_data -> td.td_deque_tail == 0 );
KE_TRACE( 10, ( "__kmp_alloc_task_deque: T#%d allocating deque[%d] for thread_data %p\n",
__kmp_gtid_from_thread( thread ), INITIAL_TASK_DEQUE_SIZE, thread_data ) );
// Allocate space for task deque, and zero the deque
// Cannot use __kmp_thread_calloc() because threads not around for
// kmp_reap_task_team( ).
thread_data -> td.td_deque = (kmp_taskdata_t **)
__kmp_allocate( INITIAL_TASK_DEQUE_SIZE * sizeof(kmp_taskdata_t *));
thread_data -> td.td_deque_size = INITIAL_TASK_DEQUE_SIZE;
}
//------------------------------------------------------------------------------
// __kmp_realloc_task_deque:
// Re-allocates a task deque for a particular thread, copies the content from the old deque
// and adjusts the necessary data structures relating to the deque.
// This operation must be done with a the deque_lock being held
static void __kmp_realloc_task_deque ( kmp_info_t *thread, kmp_thread_data_t *thread_data )
{
kmp_int32 size = TASK_DEQUE_SIZE(thread_data->td);
kmp_int32 new_size = 2 * size;
KE_TRACE( 10, ( "__kmp_realloc_task_deque: T#%d reallocating deque[from %d to %d] for thread_data %p\n",
__kmp_gtid_from_thread( thread ), size, new_size, thread_data ) );
kmp_taskdata_t ** new_deque = (kmp_taskdata_t **) __kmp_allocate( new_size * sizeof(kmp_taskdata_t *));
int i,j;
for ( i = thread_data->td.td_deque_head, j = 0; j < size; i = (i+1) & TASK_DEQUE_MASK(thread_data->td), j++ )
new_deque[j] = thread_data->td.td_deque[i];
__kmp_free(thread_data->td.td_deque);
thread_data -> td.td_deque_head = 0;
thread_data -> td.td_deque_tail = size;
thread_data -> td.td_deque = new_deque;
thread_data -> td.td_deque_size = new_size;
}
//------------------------------------------------------------------------------
// __kmp_free_task_deque:
// Deallocates a task deque for a particular thread.
// Happens at library deallocation so don't need to reset all thread data fields.
static void
__kmp_free_task_deque( kmp_thread_data_t *thread_data )
{
__kmp_acquire_bootstrap_lock( & thread_data -> td.td_deque_lock );
if ( thread_data -> td.td_deque != NULL ) {
TCW_4(thread_data -> td.td_deque_ntasks, 0);
__kmp_free( thread_data -> td.td_deque );
thread_data -> td.td_deque = NULL;
}
__kmp_release_bootstrap_lock( & thread_data -> td.td_deque_lock );
#ifdef BUILD_TIED_TASK_STACK
// GEH: Figure out what to do here for td_susp_tied_tasks
if ( thread_data -> td.td_susp_tied_tasks.ts_entries != TASK_STACK_EMPTY ) {
__kmp_free_task_stack( __kmp_thread_from_gtid( gtid ), thread_data );
}
#endif // BUILD_TIED_TASK_STACK
}
//------------------------------------------------------------------------------
// __kmp_realloc_task_threads_data:
// Allocates a threads_data array for a task team, either by allocating an initial
// array or enlarging an existing array. Only the first thread to get the lock
// allocs or enlarges the array and re-initializes the array eleemnts.
// That thread returns "TRUE", the rest return "FALSE".
// Assumes that the new array size is given by task_team -> tt.tt_nproc.
// The current size is given by task_team -> tt.tt_max_threads.
static int
__kmp_realloc_task_threads_data( kmp_info_t *thread, kmp_task_team_t *task_team )
{
kmp_thread_data_t ** threads_data_p;
kmp_int32 nthreads, maxthreads;
int is_init_thread = FALSE;
if ( TCR_4(task_team -> tt.tt_found_tasks) ) {
// Already reallocated and initialized.
return FALSE;
}
threads_data_p = & task_team -> tt.tt_threads_data;
nthreads = task_team -> tt.tt_nproc;
maxthreads = task_team -> tt.tt_max_threads;
// All threads must lock when they encounter the first task of the implicit task
// region to make sure threads_data fields are (re)initialized before used.
__kmp_acquire_bootstrap_lock( & task_team -> tt.tt_threads_lock );
if ( ! TCR_4(task_team -> tt.tt_found_tasks) ) {
// first thread to enable tasking
kmp_team_t *team = thread -> th.th_team;
int i;
is_init_thread = TRUE;
if ( maxthreads < nthreads ) {
if ( *threads_data_p != NULL ) {
kmp_thread_data_t *old_data = *threads_data_p;
kmp_thread_data_t *new_data = NULL;
KE_TRACE( 10, ( "__kmp_realloc_task_threads_data: T#%d reallocating "
"threads data for task_team %p, new_size = %d, old_size = %d\n",
__kmp_gtid_from_thread( thread ), task_team,
nthreads, maxthreads ) );
// Reallocate threads_data to have more elements than current array
// Cannot use __kmp_thread_realloc() because threads not around for
// kmp_reap_task_team( ). Note all new array entries are initialized
// to zero by __kmp_allocate().
new_data = (kmp_thread_data_t *)
__kmp_allocate( nthreads * sizeof(kmp_thread_data_t) );
// copy old data to new data
KMP_MEMCPY_S( (void *) new_data, nthreads * sizeof(kmp_thread_data_t),
(void *) old_data,
maxthreads * sizeof(kmp_taskdata_t *) );
#ifdef BUILD_TIED_TASK_STACK
// GEH: Figure out if this is the right thing to do
for (i = maxthreads; i < nthreads; i++) {
kmp_thread_data_t *thread_data = & (*threads_data_p)[i];
__kmp_init_task_stack( __kmp_gtid_from_thread( thread ), thread_data );
}
#endif // BUILD_TIED_TASK_STACK
// Install the new data and free the old data
(*threads_data_p) = new_data;
__kmp_free( old_data );
}
else {
KE_TRACE( 10, ( "__kmp_realloc_task_threads_data: T#%d allocating "
"threads data for task_team %p, size = %d\n",
__kmp_gtid_from_thread( thread ), task_team, nthreads ) );
// Make the initial allocate for threads_data array, and zero entries
// Cannot use __kmp_thread_calloc() because threads not around for
// kmp_reap_task_team( ).
ANNOTATE_IGNORE_WRITES_BEGIN();
*threads_data_p = (kmp_thread_data_t *)
__kmp_allocate( nthreads * sizeof(kmp_thread_data_t) );
ANNOTATE_IGNORE_WRITES_END();
#ifdef BUILD_TIED_TASK_STACK
// GEH: Figure out if this is the right thing to do
for (i = 0; i < nthreads; i++) {
kmp_thread_data_t *thread_data = & (*threads_data_p)[i];
__kmp_init_task_stack( __kmp_gtid_from_thread( thread ), thread_data );
}
#endif // BUILD_TIED_TASK_STACK
}
task_team -> tt.tt_max_threads = nthreads;
}
else {
// If array has (more than) enough elements, go ahead and use it
KMP_DEBUG_ASSERT( *threads_data_p != NULL );
}
// initialize threads_data pointers back to thread_info structures
for (i = 0; i < nthreads; i++) {
kmp_thread_data_t *thread_data = & (*threads_data_p)[i];
thread_data -> td.td_thr = team -> t.t_threads[i];
if ( thread_data -> td.td_deque_last_stolen >= nthreads) {
// The last stolen field survives across teams / barrier, and the number
// of threads may have changed. It's possible (likely?) that a new
// parallel region will exhibit the same behavior as the previous region.
thread_data -> td.td_deque_last_stolen = -1;
}
}
KMP_MB();
TCW_SYNC_4(task_team -> tt.tt_found_tasks, TRUE);
}
__kmp_release_bootstrap_lock( & task_team -> tt.tt_threads_lock );
return is_init_thread;
}
//------------------------------------------------------------------------------
// __kmp_free_task_threads_data:
// Deallocates a threads_data array for a task team, including any attached
// tasking deques. Only occurs at library shutdown.
static void
__kmp_free_task_threads_data( kmp_task_team_t *task_team )
{
__kmp_acquire_bootstrap_lock( & task_team -> tt.tt_threads_lock );
if ( task_team -> tt.tt_threads_data != NULL ) {
int i;
for (i = 0; i < task_team->tt.tt_max_threads; i++ ) {
__kmp_free_task_deque( & task_team -> tt.tt_threads_data[i] );
}
__kmp_free( task_team -> tt.tt_threads_data );
task_team -> tt.tt_threads_data = NULL;
}
__kmp_release_bootstrap_lock( & task_team -> tt.tt_threads_lock );
}
//------------------------------------------------------------------------------
// __kmp_allocate_task_team:
// Allocates a task team associated with a specific team, taking it from
// the global task team free list if possible. Also initializes data structures.
static kmp_task_team_t *
__kmp_allocate_task_team( kmp_info_t *thread, kmp_team_t *team )
{
kmp_task_team_t *task_team = NULL;
int nthreads;
KA_TRACE( 20, ( "__kmp_allocate_task_team: T#%d entering; team = %p\n",
(thread ? __kmp_gtid_from_thread( thread ) : -1), team ) );
if (TCR_PTR(__kmp_free_task_teams) != NULL) {
// Take a task team from the task team pool
__kmp_acquire_bootstrap_lock( &__kmp_task_team_lock );
if (__kmp_free_task_teams != NULL) {
task_team = __kmp_free_task_teams;
TCW_PTR(__kmp_free_task_teams, task_team -> tt.tt_next);
task_team -> tt.tt_next = NULL;
}
__kmp_release_bootstrap_lock( &__kmp_task_team_lock );
}
if (task_team == NULL) {
KE_TRACE( 10, ( "__kmp_allocate_task_team: T#%d allocating "
"task team for team %p\n",
__kmp_gtid_from_thread( thread ), team ) );
// Allocate a new task team if one is not available.
// Cannot use __kmp_thread_malloc() because threads not around for
// kmp_reap_task_team( ).
task_team = (kmp_task_team_t *) __kmp_allocate( sizeof(kmp_task_team_t) );
__kmp_init_bootstrap_lock( & task_team -> tt.tt_threads_lock );
//task_team -> tt.tt_threads_data = NULL; // AC: __kmp_allocate zeroes returned memory
//task_team -> tt.tt_max_threads = 0;
//task_team -> tt.tt_next = NULL;
}
TCW_4(task_team -> tt.tt_found_tasks, FALSE);
#if OMP_45_ENABLED
TCW_4(task_team -> tt.tt_found_proxy_tasks, FALSE);
#endif
task_team -> tt.tt_nproc = nthreads = team->t.t_nproc;
TCW_4( task_team -> tt.tt_unfinished_threads, nthreads );
TCW_4( task_team -> tt.tt_active, TRUE );
KA_TRACE( 20, ( "__kmp_allocate_task_team: T#%d exiting; task_team = %p unfinished_threads init'd to %d\n",
(thread ? __kmp_gtid_from_thread( thread ) : -1), task_team, task_team -> tt.tt_unfinished_threads) );
return task_team;
}
//------------------------------------------------------------------------------
// __kmp_free_task_team:
// Frees the task team associated with a specific thread, and adds it
// to the global task team free list.
void
__kmp_free_task_team( kmp_info_t *thread, kmp_task_team_t *task_team )
{
KA_TRACE( 20, ( "__kmp_free_task_team: T#%d task_team = %p\n",
thread ? __kmp_gtid_from_thread( thread ) : -1, task_team ) );
// Put task team back on free list
__kmp_acquire_bootstrap_lock( & __kmp_task_team_lock );
KMP_DEBUG_ASSERT( task_team -> tt.tt_next == NULL );
task_team -> tt.tt_next = __kmp_free_task_teams;
TCW_PTR(__kmp_free_task_teams, task_team);
__kmp_release_bootstrap_lock( & __kmp_task_team_lock );
}
//------------------------------------------------------------------------------
// __kmp_reap_task_teams:
// Free all the task teams on the task team free list.
// Should only be done during library shutdown.
// Cannot do anything that needs a thread structure or gtid since they are already gone.
void
__kmp_reap_task_teams( void )
{
kmp_task_team_t *task_team;
if ( TCR_PTR(__kmp_free_task_teams) != NULL ) {
// Free all task_teams on the free list
__kmp_acquire_bootstrap_lock( &__kmp_task_team_lock );
while ( ( task_team = __kmp_free_task_teams ) != NULL ) {
__kmp_free_task_teams = task_team -> tt.tt_next;
task_team -> tt.tt_next = NULL;
// Free threads_data if necessary
if ( task_team -> tt.tt_threads_data != NULL ) {
__kmp_free_task_threads_data( task_team );
}
__kmp_free( task_team );
}
__kmp_release_bootstrap_lock( &__kmp_task_team_lock );
}
}
//------------------------------------------------------------------------------
// __kmp_wait_to_unref_task_teams:
// Some threads could still be in the fork barrier release code, possibly
// trying to steal tasks. Wait for each thread to unreference its task team.
//
void
__kmp_wait_to_unref_task_teams(void)
{
kmp_info_t *thread;
kmp_uint32 spins;
int done;
KMP_INIT_YIELD( spins );
for (;;) {
done = TRUE;
// TODO: GEH - this may be is wrong because some sync would be necessary
// in case threads are added to the pool during the traversal.
// Need to verify that lock for thread pool is held when calling
// this routine.
for (thread = (kmp_info_t *)__kmp_thread_pool;
thread != NULL;
thread = thread->th.th_next_pool)
{
#if KMP_OS_WINDOWS
DWORD exit_val;
#endif
if ( TCR_PTR(thread->th.th_task_team) == NULL ) {
KA_TRACE( 10, ("__kmp_wait_to_unref_task_team: T#%d task_team == NULL\n",
__kmp_gtid_from_thread( thread ) ) );
continue;
}
#if KMP_OS_WINDOWS
// TODO: GEH - add this check for Linux* OS / OS X* as well?
if (!__kmp_is_thread_alive(thread, &exit_val)) {
thread->th.th_task_team = NULL;
continue;
}
#endif
done = FALSE; // Because th_task_team pointer is not NULL for this thread
KA_TRACE( 10, ("__kmp_wait_to_unref_task_team: Waiting for T#%d to unreference task_team\n",
__kmp_gtid_from_thread( thread ) ) );
if ( __kmp_dflt_blocktime != KMP_MAX_BLOCKTIME ) {
volatile void *sleep_loc;
// If the thread is sleeping, awaken it.
if ( ( sleep_loc = TCR_PTR( thread->th.th_sleep_loc) ) != NULL ) {
KA_TRACE( 10, ( "__kmp_wait_to_unref_task_team: T#%d waking up thread T#%d\n",
__kmp_gtid_from_thread( thread ), __kmp_gtid_from_thread( thread ) ) );
__kmp_null_resume_wrapper(__kmp_gtid_from_thread(thread), sleep_loc);
}
}
}
if (done) {
break;
}
// If we are oversubscribed,
// or have waited a bit (and library mode is throughput), yield.
// Pause is in the following code.
KMP_YIELD( TCR_4(__kmp_nth) > __kmp_avail_proc );
KMP_YIELD_SPIN( spins ); // Yields only if KMP_LIBRARY=throughput
}
}
//------------------------------------------------------------------------------
// __kmp_task_team_setup: Create a task_team for the current team, but use
// an already created, unused one if it already exists.
void
__kmp_task_team_setup( kmp_info_t *this_thr, kmp_team_t *team, int always )
{
KMP_DEBUG_ASSERT( __kmp_tasking_mode != tskm_immediate_exec );
// If this task_team hasn't been created yet, allocate it. It will be used in the region after the next.
// If it exists, it is the current task team and shouldn't be touched yet as it may still be in use.
if (team->t.t_task_team[this_thr->th.th_task_state] == NULL && (always || team->t.t_nproc > 1) ) {
team->t.t_task_team[this_thr->th.th_task_state] = __kmp_allocate_task_team( this_thr, team );
KA_TRACE(20, ("__kmp_task_team_setup: Master T#%d created new task_team %p for team %d at parity=%d\n",
__kmp_gtid_from_thread(this_thr), team->t.t_task_team[this_thr->th.th_task_state],
((team != NULL) ? team->t.t_id : -1), this_thr->th.th_task_state));
}
// After threads exit the release, they will call sync, and then point to this other task_team; make sure it is
// allocated and properly initialized. As threads spin in the barrier release phase, they will continue to use the
// previous task_team struct(above), until they receive the signal to stop checking for tasks (they can't safely
// reference the kmp_team_t struct, which could be reallocated by the master thread). No task teams are formed for
// serialized teams.
if (team->t.t_nproc > 1) {
int other_team = 1 - this_thr->th.th_task_state;
if (team->t.t_task_team[other_team] == NULL) { // setup other team as well
team->t.t_task_team[other_team] = __kmp_allocate_task_team( this_thr, team );
KA_TRACE(20, ("__kmp_task_team_setup: Master T#%d created second new task_team %p for team %d at parity=%d\n",
__kmp_gtid_from_thread( this_thr ), team->t.t_task_team[other_team],
((team != NULL) ? team->t.t_id : -1), other_team ));
}
else { // Leave the old task team struct in place for the upcoming region; adjust as needed
kmp_task_team_t *task_team = team->t.t_task_team[other_team];
if (!task_team->tt.tt_active || team->t.t_nproc != task_team->tt.tt_nproc) {
TCW_4(task_team->tt.tt_nproc, team->t.t_nproc);
TCW_4(task_team->tt.tt_found_tasks, FALSE);
#if OMP_45_ENABLED
TCW_4(task_team->tt.tt_found_proxy_tasks, FALSE);
#endif
TCW_4(task_team->tt.tt_unfinished_threads, team->t.t_nproc );
TCW_4(task_team->tt.tt_active, TRUE );
}
// if team size has changed, the first thread to enable tasking will realloc threads_data if necessary
KA_TRACE(20, ("__kmp_task_team_setup: Master T#%d reset next task_team %p for team %d at parity=%d\n",
__kmp_gtid_from_thread( this_thr ), team->t.t_task_team[other_team],
((team != NULL) ? team->t.t_id : -1), other_team ));
}
}
}
//------------------------------------------------------------------------------
// __kmp_task_team_sync: Propagation of task team data from team to threads
// which happens just after the release phase of a team barrier. This may be
// called by any thread, but only for teams with # threads > 1.
void
__kmp_task_team_sync( kmp_info_t *this_thr, kmp_team_t *team )
{
KMP_DEBUG_ASSERT( __kmp_tasking_mode != tskm_immediate_exec );
// Toggle the th_task_state field, to switch which task_team this thread refers to
this_thr->th.th_task_state = 1 - this_thr->th.th_task_state;
// It is now safe to propagate the task team pointer from the team struct to the current thread.
TCW_PTR(this_thr->th.th_task_team, team->t.t_task_team[this_thr->th.th_task_state]);
KA_TRACE(20, ("__kmp_task_team_sync: Thread T#%d task team switched to task_team %p from Team #%d (parity=%d)\n",
__kmp_gtid_from_thread( this_thr ), this_thr->th.th_task_team,
((team != NULL) ? team->t.t_id : -1), this_thr->th.th_task_state));
}
//--------------------------------------------------------------------------------------------
// __kmp_task_team_wait: Master thread waits for outstanding tasks after the barrier gather
// phase. Only called by master thread if #threads in team > 1 or if proxy tasks were created.
// wait is a flag that defaults to 1 (see kmp.h), but waiting can be turned off by passing in 0
// optionally as the last argument. When wait is zero, master thread does not wait for
// unfinished_threads to reach 0.
void
__kmp_task_team_wait( kmp_info_t *this_thr, kmp_team_t *team
USE_ITT_BUILD_ARG(void * itt_sync_obj)
, int wait)
{
kmp_task_team_t *task_team = team->t.t_task_team[this_thr->th.th_task_state];
KMP_DEBUG_ASSERT( __kmp_tasking_mode != tskm_immediate_exec );
KMP_DEBUG_ASSERT( task_team == this_thr->th.th_task_team );
if ( ( task_team != NULL ) && KMP_TASKING_ENABLED(task_team) ) {
if (wait) {
KA_TRACE(20, ("__kmp_task_team_wait: Master T#%d waiting for all tasks (for unfinished_threads to reach 0) on task_team = %p\n",
__kmp_gtid_from_thread(this_thr), task_team));
// Worker threads may have dropped through to release phase, but could still be executing tasks. Wait
// here for tasks to complete. To avoid memory contention, only master thread checks termination condition.
kmp_flag_32 flag(&task_team->tt.tt_unfinished_threads, 0U);
flag.wait(this_thr, TRUE
USE_ITT_BUILD_ARG(itt_sync_obj));
}
// Deactivate the old task team, so that the worker threads will stop referencing it while spinning.
KA_TRACE(20, ("__kmp_task_team_wait: Master T#%d deactivating task_team %p: "
"setting active to false, setting local and team's pointer to NULL\n",
__kmp_gtid_from_thread(this_thr), task_team));
#if OMP_45_ENABLED
KMP_DEBUG_ASSERT( task_team->tt.tt_nproc > 1 || task_team->tt.tt_found_proxy_tasks == TRUE );
TCW_SYNC_4( task_team->tt.tt_found_proxy_tasks, FALSE );
#else
KMP_DEBUG_ASSERT( task_team->tt.tt_nproc > 1 );
#endif
TCW_SYNC_4( task_team->tt.tt_active, FALSE );
KMP_MB();
TCW_PTR(this_thr->th.th_task_team, NULL);
}
}
//------------------------------------------------------------------------------
// __kmp_tasking_barrier:
// This routine may only called when __kmp_tasking_mode == tskm_extra_barrier.
// Internal function to execute all tasks prior to a regular barrier or a
// join barrier. It is a full barrier itself, which unfortunately turns
// regular barriers into double barriers and join barriers into 1 1/2
// barriers.
void
__kmp_tasking_barrier( kmp_team_t *team, kmp_info_t *thread, int gtid )
{
volatile kmp_uint32 *spin = &team->t.t_task_team[thread->th.th_task_state]->tt.tt_unfinished_threads;
int flag = FALSE;
KMP_DEBUG_ASSERT( __kmp_tasking_mode == tskm_extra_barrier );
#if USE_ITT_BUILD
KMP_FSYNC_SPIN_INIT( spin, (kmp_uint32*) NULL );
#endif /* USE_ITT_BUILD */
kmp_flag_32 spin_flag(spin, 0U);
while (! spin_flag.execute_tasks(thread, gtid, TRUE, &flag
USE_ITT_BUILD_ARG(NULL), 0 ) ) {
#if USE_ITT_BUILD
// TODO: What about itt_sync_obj??
KMP_FSYNC_SPIN_PREPARE( spin );
#endif /* USE_ITT_BUILD */
if( TCR_4(__kmp_global.g.g_done) ) {
if( __kmp_global.g.g_abort )
__kmp_abort_thread( );
break;
}
KMP_YIELD( TRUE ); // GH: We always yield here
}
#if USE_ITT_BUILD
KMP_FSYNC_SPIN_ACQUIRED( (void*) spin );
#endif /* USE_ITT_BUILD */
}
#if OMP_45_ENABLED
/* __kmp_give_task puts a task into a given thread queue if:
- the queue for that thread was created
- there's space in that queue
Because of this, __kmp_push_task needs to check if there's space after getting the lock
*/
static bool __kmp_give_task ( kmp_info_t *thread, kmp_int32 tid, kmp_task_t * task, kmp_int32 pass )
{
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(task);
kmp_task_team_t * task_team = taskdata->td_task_team;
KA_TRACE(20, ("__kmp_give_task: trying to give task %p to thread %d.\n", taskdata, tid ) );
// If task_team is NULL something went really bad...
KMP_DEBUG_ASSERT( task_team != NULL );
bool result = false;
kmp_thread_data_t * thread_data = & task_team -> tt.tt_threads_data[ tid ];
if (thread_data -> td.td_deque == NULL ) {
// There's no queue in this thread, go find another one
// We're guaranteed that at least one thread has a queue
KA_TRACE(30, ("__kmp_give_task: thread %d has no queue while giving task %p.\n", tid, taskdata ) );
return result;
}
if ( TCR_4(thread_data -> td.td_deque_ntasks) >= TASK_DEQUE_SIZE(thread_data->td) )
{
KA_TRACE(30, ("__kmp_give_task: queue is full while giving task %p to thread %d.\n", taskdata, tid ) );
// if this deque is bigger than the pass ratio give a chance to another thread
if ( TASK_DEQUE_SIZE(thread_data->td)/INITIAL_TASK_DEQUE_SIZE >= pass ) return result;
__kmp_acquire_bootstrap_lock( & thread_data-> td.td_deque_lock );
__kmp_realloc_task_deque(thread,thread_data);
} else {
__kmp_acquire_bootstrap_lock( & thread_data-> td.td_deque_lock );
if ( TCR_4(thread_data -> td.td_deque_ntasks) >= TASK_DEQUE_SIZE(thread_data->td) )
{
KA_TRACE(30, ("__kmp_give_task: queue is full while giving task %p to thread %d.\n", taskdata, tid ) );
// if this deque is bigger than the pass ratio give a chance to another thread
if ( TASK_DEQUE_SIZE(thread_data->td)/INITIAL_TASK_DEQUE_SIZE >= pass )
goto release_and_exit;
__kmp_realloc_task_deque(thread,thread_data);
}
}
// lock is held here, and there is space in the deque
thread_data -> td.td_deque[ thread_data -> td.td_deque_tail ] = taskdata;
// Wrap index.
thread_data -> td.td_deque_tail = ( thread_data -> td.td_deque_tail + 1 ) & TASK_DEQUE_MASK(thread_data->td);
TCW_4(thread_data -> td.td_deque_ntasks, TCR_4(thread_data -> td.td_deque_ntasks) + 1);
result = true;
KA_TRACE(30, ("__kmp_give_task: successfully gave task %p to thread %d.\n", taskdata, tid ) );
release_and_exit:
__kmp_release_bootstrap_lock( & thread_data-> td.td_deque_lock );
return result;
}
/* The finish of the a proxy tasks is divided in two pieces:
- the top half is the one that can be done from a thread outside the team
- the bottom half must be run from a them within the team
In order to run the bottom half the task gets queued back into one of the threads of the team.
Once the td_incomplete_child_task counter of the parent is decremented the threads can leave the barriers.
So, the bottom half needs to be queued before the counter is decremented. The top half is therefore divided in two parts:
- things that can be run before queuing the bottom half
- things that must be run after queuing the bottom half
This creates a second race as the bottom half can free the task before the second top half is executed. To avoid this
we use the td_incomplete_child_task of the proxy task to synchronize the top and bottom half.
*/
static void __kmp_first_top_half_finish_proxy( kmp_taskdata_t * taskdata )
{
KMP_DEBUG_ASSERT( taskdata -> td_flags.tasktype == TASK_EXPLICIT );
KMP_DEBUG_ASSERT( taskdata -> td_flags.proxy == TASK_PROXY );
KMP_DEBUG_ASSERT( taskdata -> td_flags.complete == 0 );
KMP_DEBUG_ASSERT( taskdata -> td_flags.freed == 0 );
taskdata -> td_flags.complete = 1; // mark the task as completed
if ( taskdata->td_taskgroup )
KMP_TEST_THEN_DEC32( (kmp_int32 *)(& taskdata->td_taskgroup->count) );
// Create an imaginary children for this task so the bottom half cannot release the task before we have completed the second top half
TCI_4(taskdata->td_incomplete_child_tasks);
}
static void __kmp_second_top_half_finish_proxy( kmp_taskdata_t * taskdata )
{
kmp_int32 children = 0;
// Predecrement simulated by "- 1" calculation
children = KMP_TEST_THEN_DEC32( (kmp_int32 *)(& taskdata -> td_parent -> td_incomplete_child_tasks) ) - 1;
KMP_DEBUG_ASSERT( children >= 0 );
// Remove the imaginary children
TCD_4(taskdata->td_incomplete_child_tasks);
}
static void __kmp_bottom_half_finish_proxy( kmp_int32 gtid, kmp_task_t * ptask )
{
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(ptask);
kmp_info_t * thread = __kmp_threads[ gtid ];
KMP_DEBUG_ASSERT( taskdata -> td_flags.proxy == TASK_PROXY );
KMP_DEBUG_ASSERT( taskdata -> td_flags.complete == 1 ); // top half must run before bottom half
// We need to wait to make sure the top half is finished
// Spinning here should be ok as this should happen quickly
while ( TCR_4(taskdata->td_incomplete_child_tasks) > 0 ) ;
__kmp_release_deps(gtid,taskdata);
__kmp_free_task_and_ancestors(gtid, taskdata, thread);
}
/*!
@ingroup TASKING
@param gtid Global Thread ID of encountering thread
@param ptask Task which execution is completed
Execute the completation of a proxy task from a thread of that is part of the team. Run first and bottom halves directly.
*/
void __kmpc_proxy_task_completed( kmp_int32 gtid, kmp_task_t *ptask )
{
KMP_DEBUG_ASSERT( ptask != NULL );
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(ptask);
KA_TRACE(10, ("__kmp_proxy_task_completed(enter): T#%d proxy task %p completing\n", gtid, taskdata ) );
KMP_DEBUG_ASSERT( taskdata->td_flags.proxy == TASK_PROXY );
__kmp_first_top_half_finish_proxy(taskdata);
__kmp_second_top_half_finish_proxy(taskdata);
__kmp_bottom_half_finish_proxy(gtid,ptask);
KA_TRACE(10, ("__kmp_proxy_task_completed(exit): T#%d proxy task %p completing\n", gtid, taskdata ) );
}
/*!
@ingroup TASKING
@param ptask Task which execution is completed
Execute the completation of a proxy task from a thread that could not belong to the team.
*/
void __kmpc_proxy_task_completed_ooo ( kmp_task_t *ptask )
{
KMP_DEBUG_ASSERT( ptask != NULL );
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(ptask);
KA_TRACE(10, ("__kmp_proxy_task_completed_ooo(enter): proxy task completing ooo %p\n", taskdata ) );
KMP_DEBUG_ASSERT( taskdata->td_flags.proxy == TASK_PROXY );
__kmp_first_top_half_finish_proxy(taskdata);
// Enqueue task to complete bottom half completion from a thread within the corresponding team
kmp_team_t * team = taskdata->td_team;
kmp_int32 nthreads = team->t.t_nproc;
kmp_info_t *thread;
//This should be similar to start_k = __kmp_get_random( thread ) % nthreads but we cannot use __kmp_get_random here
kmp_int32 start_k = 0;
kmp_int32 pass = 1;
kmp_int32 k = start_k;
do {
//For now we're just linearly trying to find a thread
thread = team->t.t_threads[k];
k = (k+1) % nthreads;
// we did a full pass through all the threads
if ( k == start_k ) pass = pass << 1;
} while ( !__kmp_give_task( thread, k, ptask, pass ) );
__kmp_second_top_half_finish_proxy(taskdata);
KA_TRACE(10, ("__kmp_proxy_task_completed_ooo(exit): proxy task completing ooo %p\n", taskdata ) );
}
//---------------------------------------------------------------------------------
// __kmp_task_dup_alloc: Allocate the taskdata and make a copy of source task for taskloop
//
// thread: allocating thread
// task_src: pointer to source task to be duplicated
// returns: a pointer to the allocated kmp_task_t structure (task).
kmp_task_t *
__kmp_task_dup_alloc( kmp_info_t *thread, kmp_task_t *task_src )
{
kmp_task_t *task;
kmp_taskdata_t *taskdata;
kmp_taskdata_t *taskdata_src;
kmp_taskdata_t *parent_task = thread->th.th_current_task;
size_t shareds_offset;
size_t task_size;
KA_TRACE(10, ("__kmp_task_dup_alloc(enter): Th %p, source task %p\n", thread, task_src) );
taskdata_src = KMP_TASK_TO_TASKDATA( task_src );
KMP_DEBUG_ASSERT( taskdata_src->td_flags.proxy == TASK_FULL ); // it should not be proxy task
KMP_DEBUG_ASSERT( taskdata_src->td_flags.tasktype == TASK_EXPLICIT );
task_size = taskdata_src->td_size_alloc;
// Allocate a kmp_taskdata_t block and a kmp_task_t block.
KA_TRACE(30, ("__kmp_task_dup_alloc: Th %p, malloc size %ld\n", thread, task_size) );
#if USE_FAST_MEMORY
taskdata = (kmp_taskdata_t *)__kmp_fast_allocate( thread, task_size );
#else
taskdata = (kmp_taskdata_t *)__kmp_thread_malloc( thread, task_size );
#endif /* USE_FAST_MEMORY */
KMP_MEMCPY(taskdata, taskdata_src, task_size);
task = KMP_TASKDATA_TO_TASK(taskdata);
// Initialize new task (only specific fields not affected by memcpy)
taskdata->td_task_id = KMP_GEN_TASK_ID();
if( task->shareds != NULL ) { // need setup shareds pointer
shareds_offset = (char*)task_src->shareds - (char*)taskdata_src;
task->shareds = &((char*)taskdata)[shareds_offset];
KMP_DEBUG_ASSERT( (((kmp_uintptr_t)task->shareds) & (sizeof(void*)-1)) == 0 );
}
taskdata->td_alloc_thread = thread;
taskdata->td_taskgroup = parent_task->td_taskgroup; // task inherits the taskgroup from the parent task
// Only need to keep track of child task counts if team parallel and tasking not serialized
if ( !( taskdata->td_flags.team_serial || taskdata->td_flags.tasking_ser ) ) {
KMP_TEST_THEN_INC32( (kmp_int32 *)(& parent_task->td_incomplete_child_tasks) );
if ( parent_task->td_taskgroup )
KMP_TEST_THEN_INC32( (kmp_int32 *)(& parent_task->td_taskgroup->count) );
// Only need to keep track of allocated child tasks for explicit tasks since implicit not deallocated
if ( taskdata->td_parent->td_flags.tasktype == TASK_EXPLICIT )
KMP_TEST_THEN_INC32( (kmp_int32 *)(& taskdata->td_parent->td_allocated_child_tasks) );
}
KA_TRACE(20, ("__kmp_task_dup_alloc(exit): Th %p, created task %p, parent=%p\n",
thread, taskdata, taskdata->td_parent) );
#if OMPT_SUPPORT
__kmp_task_init_ompt(taskdata, thread->th.th_info.ds.ds_gtid, (void*)task->routine);
#endif
return task;
}
// Routine optionally generated by th ecompiler for setting the lastprivate flag
// and calling needed constructors for private/firstprivate objects
// (used to form taskloop tasks from pattern task)
typedef void(*p_task_dup_t)(kmp_task_t *, kmp_task_t *, kmp_int32);
//---------------------------------------------------------------------------------
// __kmp_taskloop_linear: Start tasks of the taskloop linearly
//
// loc Source location information
// gtid Global thread ID
// task Task with whole loop iteration range
// lb Pointer to loop lower bound
// ub Pointer to loop upper bound
// st Loop stride
// sched Schedule specified 0/1/2 for none/grainsize/num_tasks
// grainsize Schedule value if specified
// task_dup Tasks duplication routine
void
__kmp_taskloop_linear(ident_t *loc, int gtid, kmp_task_t *task,
kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
int sched, kmp_uint64 grainsize, void *task_dup )
{
KMP_COUNT_BLOCK(OMP_TASKLOOP);
KMP_TIME_PARTITIONED_BLOCK(OMP_taskloop_scheduling);
p_task_dup_t ptask_dup = (p_task_dup_t)task_dup;
kmp_uint64 tc;
kmp_uint64 lower = *lb; // compiler provides global bounds here
kmp_uint64 upper = *ub;
kmp_uint64 i, num_tasks = 0, extras = 0;
kmp_info_t *thread = __kmp_threads[gtid];
kmp_taskdata_t *current_task = thread->th.th_current_task;
kmp_task_t *next_task;
kmp_int32 lastpriv = 0;
size_t lower_offset = (char*)lb - (char*)task; // remember offset of lb in the task structure
size_t upper_offset = (char*)ub - (char*)task; // remember offset of ub in the task structure
// compute trip count
if ( st == 1 ) { // most common case
tc = upper - lower + 1;
} else if ( st < 0 ) {
tc = (lower - upper) / (-st) + 1;
} else { // st > 0
tc = (upper - lower) / st + 1;
}
if(tc == 0) {
KA_TRACE(20, ("__kmpc_taskloop(exit): T#%d zero-trip loop\n", gtid));
// free the pattern task and exit
__kmp_task_start( gtid, task, current_task );
// do not execute anything for zero-trip loop
__kmp_task_finish( gtid, task, current_task );
return;
}
// compute num_tasks/grainsize based on the input provided
switch( sched ) {
case 0: // no schedule clause specified, we can choose the default
// let's try to schedule (team_size*10) tasks
grainsize = thread->th.th_team_nproc * 10;
case 2: // num_tasks provided
if( grainsize > tc ) {
num_tasks = tc; // too big num_tasks requested, adjust values
grainsize = 1;
extras = 0;
} else {
num_tasks = grainsize;
grainsize = tc / num_tasks;
extras = tc % num_tasks;
}
break;
case 1: // grainsize provided
if( grainsize > tc ) {
num_tasks = 1; // too big grainsize requested, adjust values
grainsize = tc;
extras = 0;
} else {
num_tasks = tc / grainsize;
grainsize = tc / num_tasks; // adjust grainsize for balanced distribution of iterations
extras = tc % num_tasks;
}
break;
default:
KMP_ASSERT2(0, "unknown scheduling of taskloop");
}
KMP_DEBUG_ASSERT(tc == num_tasks * grainsize + extras);
KMP_DEBUG_ASSERT(num_tasks > extras);
KMP_DEBUG_ASSERT(num_tasks > 0);
KA_TRACE(20, ("__kmpc_taskloop: T#%d will launch: num_tasks %lld, grainsize %lld, extras %lld\n",
gtid, num_tasks, grainsize, extras));
// Main loop, launch num_tasks tasks, assign grainsize iterations each task
for( i = 0; i < num_tasks; ++i ) {
kmp_uint64 chunk_minus_1;
if( extras == 0 ) {
chunk_minus_1 = grainsize - 1;
} else {
chunk_minus_1 = grainsize;
--extras; // first extras iterations get bigger chunk (grainsize+1)
}
upper = lower + st * chunk_minus_1;
if( i == num_tasks - 1 ) {
// schedule the last task, set lastprivate flag
lastpriv = 1;
#if KMP_DEBUG
if( st == 1 )
KMP_DEBUG_ASSERT(upper == *ub);
else if( st > 0 )
KMP_DEBUG_ASSERT(upper+st > *ub);
else
KMP_DEBUG_ASSERT(upper+st < *ub);
#endif
}
next_task = __kmp_task_dup_alloc(thread, task); // allocate new task
*(kmp_uint64*)((char*)next_task + lower_offset) = lower; // adjust task-specific bounds
*(kmp_uint64*)((char*)next_task + upper_offset) = upper;
if( ptask_dup != NULL )
ptask_dup(next_task, task, lastpriv); // set lastprivate flag, construct fistprivates, etc.
KA_TRACE(20, ("__kmpc_taskloop: T#%d schedule task %p: lower %lld, upper %lld (offsets %p %p)\n",
gtid, next_task, lower, upper, lower_offset, upper_offset));
__kmp_omp_task(gtid, next_task, true); // schedule new task
lower = upper + st; // adjust lower bound for the next iteration
}
// free the pattern task and exit
__kmp_task_start( gtid, task, current_task );
// do not execute the pattern task, just do bookkeeping
__kmp_task_finish( gtid, task, current_task );
}
/*!
@ingroup TASKING
@param loc Source location information
@param gtid Global thread ID
@param task Task structure
@param if_val Value of the if clause
@param lb Pointer to loop lower bound
@param ub Pointer to loop upper bound
@param st Loop stride
@param nogroup Flag, 1 if nogroup clause specified, 0 otherwise
@param sched Schedule specified 0/1/2 for none/grainsize/num_tasks
@param grainsize Schedule value if specified
@param task_dup Tasks duplication routine
Execute the taskloop construct.
*/
void
__kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int if_val,
kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
int nogroup, int sched, kmp_uint64 grainsize, void *task_dup )
{
kmp_taskdata_t * taskdata = KMP_TASK_TO_TASKDATA(task);
KMP_DEBUG_ASSERT( task != NULL );
KA_TRACE(10, ("__kmpc_taskloop(enter): T#%d, pattern task %p, lb %lld ub %lld st %lld, grain %llu(%d)\n",
gtid, taskdata, *lb, *ub, st, grainsize, sched));
// check if clause value first
if( if_val == 0 ) { // if(0) specified, mark task as serial
taskdata->td_flags.task_serial = 1;
taskdata->td_flags.tiedness = TASK_TIED; // AC: serial task cannot be untied
}
if( nogroup == 0 ) {
__kmpc_taskgroup( loc, gtid );
}
if( 1 /* AC: use some heuristic here to choose task scheduling method */ ) {
__kmp_taskloop_linear( loc, gtid, task, lb, ub, st, sched, grainsize, task_dup );
}
if( nogroup == 0 ) {
__kmpc_end_taskgroup( loc, gtid );
}
KA_TRACE(10, ("__kmpc_taskloop(exit): T#%d\n", gtid));
}
#endif
| 42.652622 | 153 | 0.635174 | [
"object",
"model"
] |
cd55113c5487d153cebdf719500bab388479971f | 2,820 | cc | C++ | chrome/browser/android/compositor/scene_layer/toolbar_swipe_scene_layer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/android/compositor/scene_layer/toolbar_swipe_scene_layer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/android/compositor/scene_layer/toolbar_swipe_scene_layer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 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/android/compositor/scene_layer/toolbar_swipe_scene_layer.h"
#include "chrome/android/chrome_jni_headers/ToolbarSwipeSceneLayer_jni.h"
#include "chrome/browser/android/compositor/layer/content_layer.h"
#include "chrome/browser/android/compositor/tab_content_manager.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/size.h"
using base::android::JavaParamRef;
using base::android::JavaRef;
namespace android {
ToolbarSwipeSceneLayer::ToolbarSwipeSceneLayer(JNIEnv* env,
const JavaRef<jobject>& jobj)
: SceneLayer(env, jobj),
left_content_layer_(nullptr),
right_content_layer_(nullptr),
tab_content_manager_(nullptr) {}
ToolbarSwipeSceneLayer::~ToolbarSwipeSceneLayer() {}
void ToolbarSwipeSceneLayer::UpdateLayer(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& jobj,
jint id,
jboolean left_tab,
jboolean can_use_live_layer,
jint default_background_color,
jfloat x,
jfloat y) {
background_color_ = default_background_color;
ContentLayer* content_layer =
left_tab ? left_content_layer_.get() : right_content_layer_.get();
if (!content_layer)
return;
// Update layer visibility based on whether there is a valid tab ID.
content_layer->layer()->SetHideLayerAndSubtree(id < 0);
if (id < 0)
return;
content_layer->SetProperties(id, can_use_live_layer,
can_use_live_layer ? 0.0f : 1.0f, false, 1.0f,
1.0f, false, gfx::Rect());
content_layer->layer()->SetPosition(gfx::PointF(x, y));
}
void ToolbarSwipeSceneLayer::SetTabContentManager(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& jobj,
const base::android::JavaParamRef<jobject>& jtab_content_manager) {
tab_content_manager_ =
TabContentManager::FromJavaObject(jtab_content_manager);
left_content_layer_ = ContentLayer::Create(tab_content_manager_);
layer()->AddChild(left_content_layer_->layer());
right_content_layer_ = ContentLayer::Create(tab_content_manager_);
layer()->AddChild(right_content_layer_->layer());
}
bool ToolbarSwipeSceneLayer::ShouldShowBackground() {
return true;
}
SkColor ToolbarSwipeSceneLayer::GetBackgroundColor() {
return background_color_;
}
static jlong JNI_ToolbarSwipeSceneLayer_Init(
JNIEnv* env,
const JavaParamRef<jobject>& jobj) {
// This will automatically bind to the Java object and pass ownership there.
ToolbarSwipeSceneLayer* scene_layer = new ToolbarSwipeSceneLayer(env, jobj);
return reinterpret_cast<intptr_t>(scene_layer);
}
} // namespace android
| 33.176471 | 84 | 0.732979 | [
"geometry",
"object"
] |
cd58d164e38d8f4381e6de1db80f6e627b38b732 | 13,267 | cpp | C++ | dev/Gems/LyShine/Code/Source/UiStateActionManager.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/LyShine/Code/Source/UiStateActionManager.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/LyShine/Code/Source/UiStateActionManager.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LyShine_precompiled.h"
#include "UiStateActionManager.h"
#include <LyShine/Bus/UiVisualBus.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
UiStateActionManager::UiStateActionManager()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
UiStateActionManager::~UiStateActionManager()
{
ClearStates();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::SetStateColor(int state, AZ::EntityId target, const AZ::Color& color)
{
UiInteractableStateColor* stateColor = GetStateAction<UiInteractableStateColor>(state, target);
if (stateColor)
{
stateColor->SetColor(color);
}
else
{
StateActions* stateActions = GetStateActions(state);
if (stateActions)
{
stateActions->push_back(new UiInteractableStateColor(target, color));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
AZ::Color UiStateActionManager::GetStateColor(int state, AZ::EntityId target)
{
AZ::Color color(0.0f, 0.0f, 0.0f, 1.0f);
UiInteractableStateColor* stateColor = GetStateAction<UiInteractableStateColor>(state, target);
if (stateColor)
{
color = stateColor->GetColor();
}
else
{
CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING,
"GetStateColor: Couldn't find color action for state/target combination");
}
return color;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool UiStateActionManager::HasStateColor(int state, AZ::EntityId target)
{
UiInteractableStateColor* stateColor = GetStateAction<UiInteractableStateColor>(state, target);
return stateColor ? true : false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::SetStateAlpha(int state, AZ::EntityId target, float alpha)
{
UiInteractableStateAlpha* stateAlpha = GetStateAction<UiInteractableStateAlpha>(state, target);
if (stateAlpha)
{
stateAlpha->SetAlpha(alpha);
}
else
{
StateActions* stateActions = GetStateActions(state);
if (stateActions)
{
stateActions->push_back(new UiInteractableStateAlpha(target, alpha));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
float UiStateActionManager::GetStateAlpha(int state, AZ::EntityId target)
{
float alpha = 1.0f;
UiInteractableStateAlpha* stateAlpha = GetStateAction<UiInteractableStateAlpha>(state, target);
if (stateAlpha)
{
alpha = stateAlpha->GetAlpha();
}
else
{
CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING,
"GetStateAlpha: Couldn't find alpha action for state/target combination");
}
return alpha;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool UiStateActionManager::HasStateAlpha(int state, AZ::EntityId target)
{
UiInteractableStateAlpha* stateAlpha = GetStateAction<UiInteractableStateAlpha>(state, target);
return stateAlpha ? true : false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::SetStateSprite(int state, AZ::EntityId target, ISprite* sprite)
{
UiInteractableStateSprite* stateSprite = GetStateAction<UiInteractableStateSprite>(state, target);
if (stateSprite)
{
stateSprite->SetSprite(sprite);
}
else
{
StateActions* stateActions = GetStateActions(state);
if (stateActions)
{
stateActions->push_back(new UiInteractableStateSprite(target, sprite));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
ISprite* UiStateActionManager::GetStateSprite(int state, AZ::EntityId target)
{
ISprite* sprite = nullptr;
UiInteractableStateSprite* stateSprite = GetStateAction<UiInteractableStateSprite>(state, target);
if (stateSprite)
{
sprite = stateSprite->GetSprite();
}
else
{
CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING,
"GetStateSprite: Couldn't find sprite action for state/target combination");
}
return sprite;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::SetStateSpritePathname(int state, AZ::EntityId target, const AZStd::string& spritePath)
{
UiInteractableStateSprite* stateSprite = GetStateAction<UiInteractableStateSprite>(state, target);
if (stateSprite)
{
stateSprite->SetSpritePathname(spritePath);
}
else
{
StateActions* stateActions = GetStateActions(state);
if (stateActions)
{
stateActions->push_back(new UiInteractableStateSprite(target, spritePath));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
AZStd::string UiStateActionManager::GetStateSpritePathname(int state, AZ::EntityId target)
{
AZStd::string spritePath;
UiInteractableStateSprite* stateSprite = GetStateAction<UiInteractableStateSprite>(state, target);
if (stateSprite)
{
spritePath = stateSprite->GetSpritePathname();
}
else
{
CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING,
"GetStateSpritePathname: Couldn't find sprite action for state/target combination");
}
return spritePath;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool UiStateActionManager::HasStateSprite(int state, AZ::EntityId target)
{
UiInteractableStateSprite* stateSprite = GetStateAction<UiInteractableStateSprite>(state, target);
return stateSprite ? true : false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::SetStateFont(
int state,
AZ::EntityId target,
const AZStd::string& fontPathname,
unsigned int fontEffectIndex)
{
UiInteractableStateFont* stateFont = GetStateAction<UiInteractableStateFont>(state, target);
if (stateFont)
{
stateFont->SetFontPathname(fontPathname);
stateFont->SetFontEffectIndex(fontEffectIndex);
}
else
{
StateActions* stateActions = GetStateActions(state);
if (stateActions)
{
stateActions->push_back(new UiInteractableStateFont(target, fontPathname, fontEffectIndex));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
AZStd::string UiStateActionManager::GetStateFontPathname(int state, AZ::EntityId target)
{
AZStd::string fontPath;
UiInteractableStateFont* stateFont = GetStateAction<UiInteractableStateFont>(state, target);
if (stateFont)
{
fontPath = stateFont->GetFontPathname();
}
else
{
CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING,
"GetStateFontPathname: Couldn't find font action for state/target combination");
}
return fontPath;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int UiStateActionManager::GetStateFontEffectIndex(int state, AZ::EntityId target)
{
unsigned int fontEffectIndex = 0;
UiInteractableStateFont* stateFont = GetStateAction<UiInteractableStateFont>(state, target);
if (stateFont)
{
fontEffectIndex = stateFont->GetFontEffectIndex();
}
else
{
CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING,
"GetStateFontEffectIndex: Couldn't find font action for state/target combination");
}
return fontEffectIndex;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool UiStateActionManager::HasStateFont(int state, AZ::EntityId target)
{
UiInteractableStateFont* stateFont = GetStateAction<UiInteractableStateFont>(state, target);
return stateFont ? true : false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::Init(AZ::EntityId entityId)
{
m_entityId = entityId;
InitStateActions();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::Activate()
{
UiInteractableStatesBus::Handler::BusConnect(m_entityId);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::Deactivate()
{
UiInteractableStatesBus::Handler::BusDisconnect();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::AddState(StateActions* stateActions)
{
m_states.push_back(stateActions);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::ResetAllOverrides()
{
AZStd::vector<AZ::EntityId> entityIdList = GetTargetEntitiesInAllStates();
for (auto targetEntityId : entityIdList)
{
EBUS_EVENT_ID(targetEntityId, UiVisualBus, ResetOverrides);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::ApplyStateActions(int state)
{
// Get the actions for the state (if any) and apply them
StateActions* stateActions = m_states[state];
if (stateActions)
{
for (UiInteractableStateAction* stateAction : (*stateActions))
{
stateAction->ApplyState();
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::InitInteractableEntityForStateActions(StateActions& stateActions)
{
for (auto stateAction : stateActions)
{
stateAction->SetInteractableEntity(m_entityId);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::ClearStates()
{
for (StateActions* stateActions : m_states)
{
if (stateActions)
{
for (UiInteractableStateAction* stateAction : * stateActions)
{
delete stateAction;
}
}
}
m_states.clear();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PUBLIC STATIC MEMBER FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// PROTECTED MEMBER FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
void UiStateActionManager::InitStateActions()
{
for (StateActions* stateActions : m_states)
{
if (stateActions)
{
for (UiInteractableStateAction* stateAction : * stateActions)
{
stateAction->Init(m_entityId);
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
AZStd::vector<AZ::EntityId> UiStateActionManager::GetTargetEntitiesInAllStates()
{
AZStd::vector<AZ::EntityId> result;
for (StateActions* stateActions : m_states)
{
if (stateActions)
{
for (auto stateAction : (*stateActions))
{
AZ::EntityId targetEntity = stateAction->GetTargetEntity();
// if this state action has a target entity and it is not already in the list then add it
if (targetEntity.IsValid() && AZStd::find(result.begin(), result.end(), targetEntity) == result.end())
{
result.push_back(targetEntity);
}
}
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
UiStateActionManager::StateActions* UiStateActionManager::GetStateActions(int state)
{
if (state >= 0 && state < m_states.size())
{
return m_states[state];
}
return nullptr;
}
| 33.1675 | 118 | 0.518128 | [
"vector"
] |
cd5bf1909896a58dd0f0a496e9104781801e6138 | 5,190 | hpp | C++ | source/String.hpp | acodcha/ti4-echelon | 7849a2e50262cebd915c3eb54de1230ccf8791a8 | [
"MIT"
] | null | null | null | source/String.hpp | acodcha/ti4-echelon | 7849a2e50262cebd915c3eb54de1230ccf8791a8 | [
"MIT"
] | null | null | null | source/String.hpp | acodcha/ti4-echelon | 7849a2e50262cebd915c3eb54de1230ccf8791a8 | [
"MIT"
] | null | null | null | #pragma once
#include "Include.hpp"
namespace TI4Echelon {
/// \brief Split a string into words using whitespace as a delimiter.
std::vector<std::string> split_by_whitespace(const std::string& text) noexcept {
std::istringstream stream{text};
std::vector<std::string> words{std::istream_iterator<std::string>{stream}, std::istream_iterator<std::string>{}};
return words;
}
/// \brief Split a string into lines using newlines as a delimiter.
std::vector<std::string> split_by_newline(const std::string& text) noexcept {
std::stringstream stream(text);
std::string line;
std::vector<std::string> lines;
while (std::getline(stream, line)) {
lines.push_back(line);
}
return lines;
}
/// \brief Split a string into words using a given delimiter. The delimiter character is removed.
std::vector<std::string> split_by_delimiter(const std::string& text, const char delimiter) noexcept {
std::stringstream stream(text);
std::string word;
std::vector<std::string> words;
while (std::getline(stream, word, delimiter)) {
words.push_back(word);
}
return words;
}
/// \brief Make each character in a string lowercase.
std::string lowercase(const std::string& text) noexcept {
std::string transformed_text{text};
std::transform(transformed_text.begin(), transformed_text.end(), transformed_text.begin(), [](const char character)->char{return std::tolower(character);});
return transformed_text;
}
/// \brief Remove whitespace in a string.
std::string remove_whitespace(const std::string& text) noexcept {
std::string new_text{text};
new_text.erase(remove_if(new_text.begin(), new_text.end(), ::isspace), new_text.end());
return new_text;
}
/// \brief Remove non-alphanumeric characters in a string.
std::string remove_non_alphanumeric_characters(const std::string& text) noexcept {
std::string new_text;
for (const char character : text) {
if (::isalnum(character)) {
new_text += character;
}
}
return new_text;
}
/// \brief Remove non-alphanumeric non-space characters in a string.
std::string remove_non_alphanumeric_non_space_characters(const std::string& text) noexcept {
std::string new_text;
for (const char character : text) {
if (::isalnum(character) || character == ' ') {
new_text += character;
}
}
return new_text;
}
/// \brief Remove non-alphabetic characters in a string.
std::string remove_non_alphabetic_characters(const std::string& text) noexcept {
std::string new_text;
for (const char character : text) {
if (::isalpha(character)) {
new_text += character;
}
}
return new_text;
}
/// \brief Remove non-numeric characters in a string.
std::string remove_non_numeric_characters(const std::string& text) noexcept {
std::string new_text;
for (const char character : text) {
if (::isdigit(character)) {
new_text += character;
}
}
return new_text;
}
/// \brief Replace all occurences of a given character with another character in a string.
std::string replace_character(const std::string& text, const char original, const char replacement) noexcept {
std::string transformed_text{text};
std::transform(transformed_text.begin(), transformed_text.end(), transformed_text.begin(), [original, replacement](const char character)->char{
if (character == original) {
return replacement;
} else {
return character;
}
});
return transformed_text;
}
/// \brief Pad a string to a given length using trailing spaces.
/// \details If the string is already longer than the given length, nothing is changed.
std::string pad_to_length(const std::string& text, const std::size_t length) noexcept {
std::string padded_text{text};
const std::size_t text_length{text.size()};
if (length > text_length) {
padded_text.append(length - text_length, ' ');
}
return padded_text;
}
/// \brief Write a boolean as a string.
std::string boolean_to_string(const bool value) noexcept {
if (value) {
return "true";
} else {
return "false";
}
}
/// \brief Print a real number as a string to a given number of decimals.
std::string real_number_to_string(const double value, const int8_t decimals = 2) noexcept {
std::ostringstream stream;
stream << std::fixed << std::setprecision(decimals) << value;
return stream.str();
}
/// \brief Parse a string as an integer number.
std::optional<int64_t> string_to_integer_number(const std::string& text) noexcept {
char* end = 0;
const long long int value = std::strtoll(text.c_str(), &end, 10);
if (end != text.c_str() && *end == '\0' && value != LLONG_MAX) {
return {static_cast<int64_t>(value)};
}
const std::optional<int64_t> no_value;
return no_value;
}
/// \brief Parse a string as a real number.
std::optional<double> string_to_real_number(const std::string& text) noexcept {
char* end = 0;
const double value = strtod(text.c_str(), &end);
if (end != text.c_str() && *end == '\0' && value != HUGE_VAL && value != -HUGE_VAL) {
return {value};
}
const std::optional<double> no_value;
return no_value;
}
std::string markdown_boldface(const std::string& text) noexcept {
return "**" + text + "**";
}
} // namespace TI4Echelon
| 32.236025 | 158 | 0.701349 | [
"vector",
"transform"
] |
cd60cdbece107b0f31ac79ceab666693ecbcaf95 | 4,493 | cxx | C++ | Brush.cxx | pajamapants3000/simple_pickets | 80a3c6f11823790232abfcd43e8cf1da18f663a2 | [
"MIT"
] | null | null | null | Brush.cxx | pajamapants3000/simple_pickets | 80a3c6f11823790232abfcd43e8cf1da18f663a2 | [
"MIT"
] | null | null | null | Brush.cxx | pajamapants3000/simple_pickets | 80a3c6f11823790232abfcd43e8cf1da18f663a2 | [
"MIT"
] | null | null | null | /*
* File : Brush.cxx
* Program: simple_pickets
* Purpose: produces brush according to shape and size desired - implementation
* Author : Tommy Lincoln <pajamapants3000@gmail.com>
* License: MIT; See LICENSE
* Created: 03/04/2016
* Updated: 03/04/2016
*/
#include "Brush.hxx"
void Brush::create(const int x, const int y, const enum brushGeom geom)/*{{{*/
{
curBrushX = x;
curBrushY = y;
curBrushGeom = geom;
setBrush(curBrushX, curBrushY, curBrushGeom);
}
/*}}}*/
void Brush::uncreate()/*{{{*/
{
delete curBrushShape;
}
/*}}}*/
void Brush::operator=(const Brush& lhs)/*{{{*/
{
if (*this != lhs)
{
uncreate();
create(lhs.curBrushX, lhs.curBrushY, lhs.curBrushGeom);
}
}
/*}}}*/
bool Brush::operator==(const Brush& lhs)/*{{{*/
{
return this->curBrushShape == lhs.curBrushShape;
}
/*}}}*/
bool Brush::operator!=(const Brush& lhs)/*{{{*/
{
if (!(*this == lhs))
return true;
else
return false;
}
/*}}}*/
void Brush::setBrush(const int x, const int y, const enum brushGeom geom)/*{{{*/
{
switch (geom)
{
case Ellipse:
curBrushShape = &genEllipse(x, y);
break;
case Ring:
curBrushShape = &genRing(x, y);
break;
case Rectangle:
curBrushShape = &genRectangle(x, y);
break;
case Block:
curBrushShape = &genBlock(x, y);
break;
default:
curBrushShape = &genBlock(x, y);
}
emit brushChanged(*curBrushShape);
}
/*}}}*/
void Brush::setBrushGeom(const enum brushGeom newBrushGeom)/*{{{*/
{
curBrushGeom = newBrushGeom;
setBrush(curBrushX, curBrushY, curBrushGeom);
}
/*}}}*/
void Brush::setBrushX(const int newBrushX)/*{{{*/
{
curBrushX = newBrushX;
setBrush(curBrushX, curBrushY, curBrushGeom);
}
/*}}}*/
void Brush::setBrushY(const int newBrushY)/*{{{*/
{
curBrushY = newBrushY;
setBrush(curBrushX, curBrushY, curBrushGeom);
}
/*}}}*/
const shape_t& Brush::genEllipse(const int x, const int y) const/*{{{*/
{
shape_t* result = new shape_t;
int R;
// y = (Y/2)*sqrt(1-4(x^2/X^2)) - filled in
if (x != 0)
for (int i = -x / 2; i <= x / 2; ++i)
{
R = (int)( (y / 2.0) * sqrt( 1.0 - ((4.0 * i * i) / (x * x)) ));
for (int j = -R; j <= R; ++j)
result->push_back(QPoint(i, j));
}
if (y != 0)
for (int i = -y / 2; i <= y / 2; ++i)
{
R = (int)( (x / 2.0) * sqrt( 1.0 - ((4.0 * i * i) / (y * y)) ));
for (int j = -R; j <= R; ++j)
result->push_back(QPoint(j, i));
}
if (x == 0 && y == 0)
result->push_back(QPoint(x, y));
return *result;
}
/*}}}*/
const shape_t& Brush::genRing(const int x, const int y) const /*{{{*/
{
shape_t* result = new shape_t;
int j;
// y = (Y/2)*sqrt(1-4(x^2/X^2))
if (x != 0)
for (int i = -x / 2; i <= x / 2; ++i)
{
j = (int)( (y / 2.0) * sqrt( 1.0 - ((4.0 * i * i) / (x * x)) ));
result->push_back(QPoint(i, j));
result->push_back(QPoint(i, -j));
}
if (y != 0)
for (int i = -y / 2; i <= y / 2; ++i)
{
j = (int)( (x / 2.0) * sqrt( 1.0 - ((4.0 * i * i) / (y * y)) ));
result->push_back(QPoint(j, i));
result->push_back(QPoint(-j, i));
}
if (x == 0 && y == 0)
result->push_back(QPoint(x, y));
return *result;
}
/*}}}*/
const shape_t& Brush::genRectangle(const int x, const int y) const/*{{{*/
{
shape_t* result = new shape_t;
for (int i = -x / 2; i <= x / 2; ++i)
{
result->push_back(QPoint(i, y/2));
result->push_back(QPoint(i, -y/2));
}
for (int i = -y / 2; i < y / 2; ++i)
{
result->push_back(QPoint(x/2, i));
result->push_back(QPoint(-x/2, i));
}
return *result;
}
/*}}}*/
const shape_t& Brush::genBlock(const int x, const int y) const/*{{{*/
{
shape_t* result = new shape_t;
for (int i = -x / 2; i <= x / 2; ++i)
for (int j = -y / 2; j <= y / 2; ++j)
result->push_back(QPoint(i, j));
return *result;
}
/*}}}*/
void Brush::ellipseBrush()/*{{{*/
{
setBrushGeom(Ellipse);
}
/*}}}*/
void Brush::ringBrush()/*{{{*/
{
setBrushGeom(Ring);
}
/*}}}*/
void Brush::blockBrush()/*{{{*/
{
setBrushGeom(Block);
}
/*}}}*/
void Brush::rectangleBrush()/*{{{*/
{
setBrushGeom(Rectangle);
}
/*}}}*/
| 24.551913 | 80 | 0.498108 | [
"shape"
] |
cd6106da559bd87133cbf718b9e7b041c9adc58b | 1,599 | cpp | C++ | c++/.leetcode/1463.cherry-pickup-ii.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | c++/.leetcode/1463.cherry-pickup-ii.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | c++/.leetcode/1463.cherry-pickup-ii.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | /*
* @lc app=leetcode id=1463 lang=cpp
*
* [1463] Cherry Pickup II
*/
// @lc code=start
class Solution {
public:
int dy[3] = {-1, 0, 1};
int cherryPickup(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int f[m][n][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
for(int k = 0; k < n; k++){
f[i][j][k] = -1;
}
}
}
f[0][0][n-1] = grid[0][0] + grid[0][n-1];
for(int i = 0; i < m - 1; i++){
for(int j = 0; j < n; j++){
for(int k = n - 1; k >= 0; k--){
if(f[i][j][k] >= 0){
int f_prev = f[i][j][k];
for(int y1 : dy){
int col1 = j + y1;
if(col1 < 0 || col1 >= n) continue;
for(int y2 : dy){
int col2 = k + y2;
if(col2 < 0 || col2 >= n) continue;
f[i + 1][col1][col2] = max(f[i + 1][col1][col2], f_prev + (col1 == col2 ? grid[i+1][col1] : grid[i+1][col1] + grid[i+1][col2]));
}
}
}
}
}
}
int res = 0;
for(int j = 0; j < n; j++){
for(int k = 0; k < n; k++){
res = max(res, f[m-1][j][k]);
}
}
return res;
}
};
// @lc code=end
| 31.352941 | 161 | 0.292058 | [
"vector"
] |
cd7101608df019136136b3848ea45ec8ba1a9d3f | 1,164 | cpp | C++ | 0380_InsertDeleteGetRandomO(1).cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | null | null | null | 0380_InsertDeleteGetRandomO(1).cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | null | null | null | 0380_InsertDeleteGetRandomO(1).cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | 1 | 2020-03-18T05:23:40.000Z | 2020-03-18T05:23:40.000Z | class RandomizedSet {
private:
std::random_device rnd;
std::unordered_map<int, int> mp;
public:
/** Initialize your data structure here. */
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
auto i = mp.find(val);
if(i == mp.end()){
mp[val] = val;
return true;
} else return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
auto i = mp.find(val);
if(i != mp.end()){
mp.erase(i);
return true;
} else return false;
}
/** Get a random element from the set. */
int getRandom() {
auto iter = mp.begin();
iter = std::next(iter, rnd() % mp.size());
return iter->first;
}
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
| 27.069767 | 109 | 0.565292 | [
"object"
] |
cd721ba86768b88ddfa3d0b4c1bcafd0872e53b3 | 430 | hpp | C++ | Overworld/LighthouseCoast.hpp | NoahKittleson/RPG-Engine | e7ce30973b5d1eed09e3d5acfd89f549c2feffd8 | [
"MIT",
"Unlicense"
] | 4 | 2016-06-30T19:55:40.000Z | 2020-01-10T21:03:00.000Z | Overworld/LighthouseCoast.hpp | NoahKittleson/RPG-Engine | e7ce30973b5d1eed09e3d5acfd89f549c2feffd8 | [
"MIT",
"Unlicense"
] | null | null | null | Overworld/LighthouseCoast.hpp | NoahKittleson/RPG-Engine | e7ce30973b5d1eed09e3d5acfd89f549c2feffd8 | [
"MIT",
"Unlicense"
] | null | null | null | //
// LighthouseCoast.hpp
// Overworld
//
// Created by Noah Kittleson on 7/8/18.
// Copyright © 2018 Noah. All rights reserved.
//
#pragma once
#include "MapSection.h"
#include "BattleState.h"
class LighthouseCoast: public MapSection
{
public:
LighthouseCoast(const ResourceHolder& resources, const std::vector<Condition>& activeConds);
~LighthouseCoast() { std::cout << "Lighthouse Coast deleted.\n"; }
private:
};
| 18.695652 | 93 | 0.713953 | [
"vector"
] |
cd73838f4ff6117d52db789718419e300eccdc39 | 784 | hpp | C++ | examples/eth/node.hpp | jmigual/metasim2.0 | f426aefde08fc216e6aa2428538caa59f7e4d08b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | examples/eth/node.hpp | jmigual/metasim2.0 | f426aefde08fc216e6aa2428538caa59f7e4d08b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | examples/eth/node.hpp | jmigual/metasim2.0 | f426aefde08fc216e6aa2428538caa59f7e4d08b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 8 | 2015-06-08T17:22:19.000Z | 2021-03-01T17:41:18.000Z | #ifndef __NODE_HPP__
#define __NODE_HPP__
#include <memory>
#include <vector>
#include <string>
using namespace std;
#include <metasim.hpp>
#define _NODE_DBG "Node"
class Message;
class NetInterface;
class Node : public MetaSim::Entity {
NetInterface* _net_interf;
std::unique_ptr<MetaSim::RandomVar> _interval;
std::vector<Node*> _nodes;
public:
MetaSim::GEvent<Node> _recv_evt;
MetaSim::GEvent<Node> _send_evt;
Node(string const &name);
NetInterface *getNetInterface();
void setNetInterface(NetInterface &n);
void addDestNode(Node &n);
void setInterval(std::unique_ptr<MetaSim::RandomVar> i);
void onMessageReceived(Message *m);
void onReceive(MetaSim::Event *e);
void onSend(MetaSim::Event *e);
void newRun();
void endRun();
};
#endif
| 17.043478 | 58 | 0.725765 | [
"vector"
] |
cd755c248c4cc92913ecdf40ccb9749345fdc9f9 | 6,513 | cpp | C++ | examples/tm_landmark_uint8.cpp | zzz197/Tengine | be9ffe3b18af92b538dcbfb36ee4be08d94c19d7 | [
"Apache-2.0"
] | null | null | null | examples/tm_landmark_uint8.cpp | zzz197/Tengine | be9ffe3b18af92b538dcbfb36ee4be08d94c19d7 | [
"Apache-2.0"
] | null | null | null | examples/tm_landmark_uint8.cpp | zzz197/Tengine | be9ffe3b18af92b538dcbfb36ee4be08d94c19d7 | [
"Apache-2.0"
] | 1 | 2020-10-27T15:12:26.000Z | 2020-10-27T15:12:26.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2020, OPEN AI LAB
* Author: qtang@openailab.com
*/
#include <iostream>
#include <functional>
#include "common.h"
#include "tengine/c_api.h"
#include "tengine_operations.h"
#define DEFAULT_REPEAT_COUNT 1
#define DEFAULT_THREAD_COUNT 1
void get_input_uint8_data(const char* image_file, uint8_t* input_data, int img_h, int img_w, float* mean, float* scale,
float input_scale, int zero_point)
{
image img = imread_process(image_file, img_w, img_h, mean, scale);
float* image_data = ( float* )img.data;
for (int i = 0; i < img_w * img_h * 3; i++)
{
int udata = (round)(image_data[i] / input_scale + (float )zero_point);
if (udata > 255)
udata = 255;
else if (udata < 0)
udata = 0;
input_data[i] = udata;
}
free_image(img);
}
void show_usage()
{
fprintf(stderr, "[Usage]: [-h]\n [-m model_file] [-i image_file] [-r repeat_count] [-t thread_count]\n");
}
int main(int argc, char* argv[])
{
int repeat_count = DEFAULT_REPEAT_COUNT;
int num_thread = DEFAULT_THREAD_COUNT;
char* model_file = nullptr;
char* image_file = nullptr;
int img_h = 144;
int img_w = 144;
float mean[3] = {128.f, 128.f, 128.f};
float scale[3] = {0.0039, 0.0039, 0.0039};
int res;
while ((res = getopt(argc, argv, "m:i:r:t:h:")) != -1)
{
switch (res)
{
case 'm':
model_file = optarg;
break;
case 'i':
image_file = optarg;
break;
case 'r':
repeat_count = atoi(optarg);
break;
case 't':
num_thread = atoi(optarg);
break;
case 'h':
show_usage();
return 0;
default:
break;
}
}
/* check files */
if (model_file == nullptr)
{
fprintf(stderr, "Error: Tengine model file not specified!\n");
show_usage();
return -1;
}
if (image_file == nullptr)
{
fprintf(stderr, "Error: Image file not specified!\n");
show_usage();
return -1;
}
if (!check_file_exist(model_file) || !check_file_exist(image_file))
return -1;
/* set runtime options */
struct options opt;
opt.num_thread = num_thread;
opt.cluster = TENGINE_CLUSTER_ALL;
opt.precision = TENGINE_MODE_UINT8;
opt.affinity = 0;
/* inital tengine */
init_tengine();
fprintf(stderr, "tengine-lite library version: %s\n", get_tengine_version());
/* create graph, load tengine model xxx.tmfile */
graph_t graph = create_graph(nullptr, "tengine", model_file);
if (graph == nullptr)
{
std::cout << "Create graph0 failed\n";
return -1;
}
/* set the input shape to initial the graph, and prerun graph to infer shape */
int img_size = img_h * img_w * 3;
int dims[] = {1, 3, img_h, img_w}; // nchw
uint8_t* input_data = ( uint8_t* )malloc(img_size);
tensor_t input_tensor = get_graph_input_tensor(graph, 0, 0);
if (input_tensor == nullptr)
{
fprintf(stderr, "Get input tensor failed\n");
return -1;
}
if (set_tensor_shape(input_tensor, dims, 4) < 0)
{
fprintf(stderr, "Set input tensor shape failed\n");
return -1;
}
if (set_tensor_buffer(input_tensor, input_data, img_size) < 0)
{
fprintf(stderr, "Set input tensor buffer failed\n");
return -1;
}
/* prerun graph, set work options(num_thread, cluster, precision) */
if (prerun_graph_multithread(graph, opt) < 0)
{
fprintf(stderr, "Prerun multithread graph failed.\n");
return -1;
}
/* prepare process input data, set the data mem to input tensor, quantize fp32 to uint8 */
float input_scale = 0.f;
int input_zero_point = 0;
get_tensor_quant_param(input_tensor, &input_scale, &input_zero_point, 1);
get_input_uint8_data(image_file, input_data, img_h, img_w, mean, scale, input_scale, input_zero_point);
/* run graph */
double min_time = DBL_MAX;
double max_time = DBL_MIN;
double total_time = 0.;
for (int i = 0; i < repeat_count; i++)
{
double start = get_current_time();
if (run_graph(graph, 1) < 0)
{
fprintf(stderr, "Run graph failed\n");
return -1;
}
double end = get_current_time();
double cur = end - start;
total_time += cur;
if (min_time > cur)
min_time = cur;
if (max_time < cur)
max_time = cur;
}
printf("Repeat [%d] min %.3f ms, max %.3f ms, avg %.3f ms\n", repeat_count, min_time, max_time,
total_time / repeat_count);
/* get output tensor */
tensor_t output_tensor = get_graph_output_tensor(graph, 0, 0);
float output_scale = 0.f;
int output_zp = 0;
get_tensor_quant_param(output_tensor, &output_scale, &output_zp, 1);
uint8_t* data = ( uint8_t* )(get_tensor_buffer(output_tensor));
int data_size = get_tensor_buffer_size(output_tensor) / sizeof(uint8_t);
image img_out = imread(image_file);
for (int i = 0; i < data_size / 2; i++)
{
int x = (int)(((float)data[2 * i ] - (float)output_zp) * output_scale * (float)img_out.w / 144.f);
int y = (int)(((float)data[2 * i + 1] - (float)output_zp) * output_scale * (float)img_out.h / 144.f);
draw_circle(img_out, x, y, 2, 0, 255, 0);
}
save_image(img_out, "landmarkout_uint8");
postrun_graph(graph);
destroy_graph(graph);
release_tengine();
return 0;
}
| 29.739726 | 119 | 0.601105 | [
"shape",
"model"
] |
cd7a4509a075939c2525f060463dc2ca22a88091 | 4,429 | cpp | C++ | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Operators/Containers/OperatorErase.cpp | BadDevCode/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | 2 | 2020-06-27T12:13:44.000Z | 2020-06-27T12:13:46.000Z | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Operators/Containers/OperatorErase.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | null | null | null | dev/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Operators/Containers/OperatorErase.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | null | null | null | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "OperatorErase.h"
#include <ScriptCanvas/Core/Contracts/SupportsMethodContract.h>
#include <ScriptCanvas/Libraries/Core/MethodUtility.h>
#include <ScriptCanvas/Core/Core.h>
namespace ScriptCanvas
{
namespace Nodes
{
namespace Operators
{
void OperatorErase::ConfigureContracts(SourceType sourceType, AZStd::vector<ContractDescriptor>& contractDescs)
{
if (sourceType == SourceType::SourceInput)
{
ContractDescriptor supportsMethodContract;
supportsMethodContract.m_createFunc = [this]() -> SupportsMethodContract* { return aznew SupportsMethodContract("Erase"); };
contractDescs.push_back(AZStd::move(supportsMethodContract));
}
}
void OperatorErase::OnSourceTypeChanged()
{
if (Data::IsVectorContainerType(GetSourceAZType()))
{
DataSlotConfiguration slotConfiguration;
slotConfiguration.m_name = "Index";
slotConfiguration.m_displayGroup = GetSourceDisplayGroup();
slotConfiguration.SetConnectionType(ConnectionType::Input);
slotConfiguration.SetType(Data::Type::Number());
// Add the INDEX as the INPUT slot
m_inputSlots.insert(AddSlot(slotConfiguration));
}
else if (Data::IsMapContainerType(GetSourceAZType()))
{
AZStd::vector<AZ::Uuid> types = ScriptCanvas::Data::GetContainedTypes(GetSourceAZType());
Data::Type type = Data::FromAZType(types[0]);
// Only add the KEY as INPUT slot
DataSlotConfiguration slotConfiguration;
slotConfiguration.m_name = Data::GetName(type);
slotConfiguration.m_displayGroup = GetSourceDisplayGroup();
slotConfiguration.SetConnectionType(ConnectionType::Input);
slotConfiguration.SetType(type);
m_inputSlots.insert(AddSlot(slotConfiguration));
}
}
void OperatorErase::InvokeOperator()
{
Slot* inputSlot = GetFirstInputSourceSlot();
Slot* outputSlot = GetFirstOutputSourceSlot();
if (inputSlot && outputSlot)
{
SlotId sourceSlotId = inputSlot->GetId();
const Datum* containerDatum = FindDatum(sourceSlotId);
if (Datum::IsValidDatum(containerDatum))
{
const Datum* inputKeyDatum = FindDatum(*m_inputSlots.begin());
AZ::Outcome<Datum, AZStd::string> valueOutcome = BehaviorContextMethodHelper::CallMethodOnDatum(*containerDatum, "Erase", *inputKeyDatum);
if (!valueOutcome.IsSuccess())
{
SCRIPTCANVAS_REPORT_ERROR((*this), "Failed to get key in container: %s", valueOutcome.GetError().c_str());
return;
}
// Push the source container as an output to support chaining
PushOutput(*containerDatum, (*outputSlot));
}
}
SignalOutput(GetSlotId("Out"));
}
void OperatorErase::OnInputSignal(const SlotId& slotId)
{
const SlotId inSlotId = OperatorBaseProperty::GetInSlotId(this);
if (slotId == inSlotId)
{
InvokeOperator();
}
}
}
}
}
#include <Include/ScriptCanvas/Libraries/Operators/Containers/OperatorErase.generated.cpp> | 41.392523 | 162 | 0.568977 | [
"vector"
] |
cd81086b88dba1f5d198d1c04c90b74cc6d20b86 | 9,850 | hpp | C++ | include/cppurses/painter/glyph_string.hpp | jktjkt/CPPurses | 652d702258db8fab55ae945f7bb38e0b7c29521b | [
"MIT"
] | null | null | null | include/cppurses/painter/glyph_string.hpp | jktjkt/CPPurses | 652d702258db8fab55ae945f7bb38e0b7c29521b | [
"MIT"
] | null | null | null | include/cppurses/painter/glyph_string.hpp | jktjkt/CPPurses | 652d702258db8fab55ae945f7bb38e0b7c29521b | [
"MIT"
] | null | null | null | #ifndef CPPURSES_PAINTER_GLYPH_STRING_HPP
#define CPPURSES_PAINTER_GLYPH_STRING_HPP
#include <codecvt>
#include <initializer_list>
#include <locale>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include <cppurses/painter/attribute.hpp>
#include <cppurses/painter/glyph.hpp>
namespace cppurses {
/// Holds a collection of Glyphs with a similar interface to std::string.
class Glyph_string : private std::vector<Glyph> {
public:
/// Default constructs an empty Glyph_string.
Glyph_string() = default;
/// Used to indicate 'Until the end of the string'.
static const std::size_t npos = -1;
/// Construct with iterators from any container providing Input Iterators.
template <typename InputIterator>
Glyph_string(InputIterator first, InputIterator last);
/// Construct with \p symbols, each having given Attributes applied to them.
template <typename... Attributes>
Glyph_string(const std::string& symbols, Attributes&&... attrs);
/// Construct with \p symbols, each having given Attributes applied to them.
template <typename... Attributes>
Glyph_string(const char* symbols, Attributes&&... attrs);
/// Construct with \p symbol, having given Attributes applied to it.
template <typename... Attributes>
Glyph_string(wchar_t symbol, Attributes&&... attrs);
/// Construct with \p symbols, each having given Attributes applied to them.
template <typename... Attributes>
Glyph_string(const wchar_t* symbols, Attributes&&... attrs);
/// Construct with \p symbols, each having given Attributes applied to them.
template <typename... Attributes>
Glyph_string(const std::wstring& symbols, Attributes&&... attrs);
/// Construct with \p glyph, adding given Attributes to it.
template <typename... Attributes>
Glyph_string(const Glyph& glyph, Attributes&&... attrs);
/// Construct with a std::initializer_list of Glyphs, with \p attrs applied.
template <typename... Attributes>
Glyph_string(const std::initializer_list<Glyph>& glyphs,
Attributes&&... attrs);
/// Convert to a std::string, each Glyph being a char.
std::string str() const;
/// Convert to a std::wstring, each Glyph being a wchar_t.
std::wstring w_str() const;
/// Returns the length in Glyphs of the Glyph_string.
size_type length() const;
/// Compound concatenation assignment operator to append a Glyph.
Glyph_string& operator+=(const Glyph& glyph);
/// Concatenation operator to append a Glyph_string.
Glyph_string operator+(const Glyph_string& gs) const;
/// Append single Glyph to the end of the Glyph_string w/given Attributes.
template <typename... Attributes>
Glyph_string& append(const Glyph& symbol, Attributes&&... attrs);
/// Append a c-string with given Attributes to the end of the Glyph_string.
template <typename... Attributes>
Glyph_string& append(const char* symbols, Attributes&&... attrs);
/// Append std::string with given Attributes to the end of the Glyph_string.
template <typename... Attributes>
Glyph_string& append(const std::string& symbols, Attributes&&... attrs);
/// Append a wide c-string with given Attributes to the end of Glyph_string.
template <typename... Attributes>
Glyph_string& append(const wchar_t* symbols, Attributes&&... attrs);
/// Append std::wstring with given Attributes to the end of Glyph_string.
template <typename... Attributes>
Glyph_string& append(const std::wstring& symbols, Attributes&&... attrs);
/// Append another Glyph_string with Attributes to the end of Glyph_string.
template <typename... Attributes>
Glyph_string& append(const Glyph_string& gs, Attributes&&... attrs);
/// Add a list of Attributes to every Glyph within the Glyph_string.
template <typename... Attributes>
void add_attributes(Attributes&&... attrs);
/// Remove a single Attribute from every Glyph within the Glyph_string.
void remove_attribute(Attribute attr);
// Import member functions from std::vector<Glyph>
using std::vector<Glyph>::value_type;
using std::vector<Glyph>::allocator_type;
using std::vector<Glyph>::size_type;
using std::vector<Glyph>::difference_type;
using std::vector<Glyph>::reference;
using std::vector<Glyph>::const_reference;
using std::vector<Glyph>::pointer;
using std::vector<Glyph>::const_pointer;
using std::vector<Glyph>::iterator;
using std::vector<Glyph>::const_iterator;
using std::vector<Glyph>::reverse_iterator;
using std::vector<Glyph>::const_reverse_iterator;
using std::vector<Glyph>::operator=;
using std::vector<Glyph>::operator[];
using std::vector<Glyph>::size;
using std::vector<Glyph>::assign;
using std::vector<Glyph>::get_allocator;
using std::vector<Glyph>::at;
using std::vector<Glyph>::front;
using std::vector<Glyph>::back;
using std::vector<Glyph>::data;
using std::vector<Glyph>::begin;
using std::vector<Glyph>::cbegin;
using std::vector<Glyph>::end;
using std::vector<Glyph>::cend;
using std::vector<Glyph>::rbegin;
using std::vector<Glyph>::crbegin;
using std::vector<Glyph>::rend;
using std::vector<Glyph>::crend;
using std::vector<Glyph>::empty;
using std::vector<Glyph>::max_size;
using std::vector<Glyph>::reserve;
using std::vector<Glyph>::capacity;
using std::vector<Glyph>::shrink_to_fit;
using std::vector<Glyph>::clear;
using std::vector<Glyph>::insert;
using std::vector<Glyph>::erase;
using std::vector<Glyph>::push_back;
using std::vector<Glyph>::pop_back;
using std::vector<Glyph>::resize;
using std::vector<Glyph>::swap;
};
/// Equality comparison on each Glyph in the Glyph_strings.
bool operator==(const Glyph_string& x, const Glyph_string& y);
/// Inequality comparison on each Glyph in the Glyph_strings.
bool operator!=(const Glyph_string& x, const Glyph_string& y);
/// stream output operator for Glyph_string, outputs the Glyphs as chars to os.
std::ostream& operator<<(std::ostream& os, const Glyph_string& gs);
// TEMPLATE IMPLEMENTATIONS
template <typename InputIterator>
Glyph_string::Glyph_string(InputIterator first, InputIterator last)
: vector<Glyph>::vector(first, last) {}
template <typename... Attributes>
Glyph_string::Glyph_string(const std::string& symbols, Attributes&&... attrs)
: vector<Glyph>::vector() {
this->append(symbols, std::forward<Attributes>(attrs)...);
}
template <typename... Attributes>
Glyph_string::Glyph_string(const char* symbols, Attributes&&... attrs) {
this->append(symbols, std::forward<Attributes>(attrs)...);
}
template <typename... Attributes>
Glyph_string::Glyph_string(wchar_t symbol, Attributes&&... attrs) {
this->append(Glyph{symbol, std::forward<Attributes>(attrs)...});
}
template <typename... Attributes>
Glyph_string::Glyph_string(const wchar_t* symbols, Attributes&&... attrs) {
this->append(symbols, std::forward<Attributes>(attrs)...);
}
template <typename... Attributes>
Glyph_string::Glyph_string(const std::wstring& symbols, Attributes&&... attrs)
: vector<Glyph>::vector() {
this->append(symbols, std::forward<Attributes>(attrs)...);
}
template <typename... Attributes>
Glyph_string::Glyph_string(const Glyph& glyph, Attributes&&... attrs) {
this->append(glyph, std::forward<Attributes>(attrs)...);
}
template <typename... Attributes>
Glyph_string::Glyph_string(const std::initializer_list<Glyph>& glyphs,
Attributes&&... attrs) {
this->reserve(glyphs.size());
for (const Glyph& g : glyphs) {
this->append(g, std::forward<Attributes>(attrs)...);
}
}
template <typename... Attributes>
Glyph_string& Glyph_string::append(const Glyph& symbol, Attributes&&... attrs) {
this->push_back(symbol);
this->back().brush.add_attributes(std::forward<Attributes>(attrs)...);
return *this;
}
template <typename... Attributes>
Glyph_string& Glyph_string::append(const char* symbols, Attributes&&... attrs) {
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::wstring wide_string{converter.from_bytes(symbols)};
this->reserve(this->size() + wide_string.size());
for (wchar_t sym : wide_string) {
this->append(Glyph{sym, std::forward<Attributes>(attrs)...});
}
return *this;
}
template <typename... Attributes>
Glyph_string& Glyph_string::append(const std::string& symbols,
Attributes&&... attrs) {
return this->append(symbols.c_str(), std::forward<Attributes>(attrs)...);
}
template <typename... Attributes>
Glyph_string& Glyph_string::append(const wchar_t* symbols,
Attributes&&... attrs) {
std::size_t i{0};
while (symbols[i] != L'\0') {
this->append(Glyph{symbols[i], std::forward<Attributes>(attrs)...});
++i;
}
return *this;
}
template <typename... Attributes>
Glyph_string& Glyph_string::append(const std::wstring& symbols,
Attributes&&... attrs) {
for (wchar_t sym : symbols) {
this->append(Glyph{sym, std::forward<Attributes>(attrs)...});
}
return *this;
}
template <typename... Attributes>
Glyph_string& Glyph_string::append(const Glyph_string& gs,
Attributes&&... attrs) {
for (const Glyph& glyph : gs) {
this->append(glyph, std::forward<Attributes>(attrs)...);
}
return *this;
}
template <typename... Attributes>
void Glyph_string::add_attributes(Attributes&&... attrs) {
for (auto& glyph : *this) {
glyph.brush.add_attributes(std::forward<Attributes>(attrs)...);
}
}
} // namespace cppurses
#endif // CPPURSES_PAINTER_GLYPH_STRING_HPP
| 36.891386 | 80 | 0.685482 | [
"vector"
] |
cd83fafc436e70ac4dbb984412112a104ecf7c55 | 237 | cpp | C++ | template5-OopsBasics1/main.cpp | sladewinter/Learn_CPP | 26ab606b838ae28b74b143b7c62371a84b197de6 | [
"Apache-2.0"
] | null | null | null | template5-OopsBasics1/main.cpp | sladewinter/Learn_CPP | 26ab606b838ae28b74b143b7c62371a84b197de6 | [
"Apache-2.0"
] | null | null | null | template5-OopsBasics1/main.cpp | sladewinter/Learn_CPP | 26ab606b838ae28b74b143b7c62371a84b197de6 | [
"Apache-2.0"
] | null | null | null | #include "Vector3d.h" // for creating Vector3d object
#include "Point3d.h" // for creating Point3d object
int main()
{
Point3d p(1.0, 2.0, 3.0);
Vector3d v(2.0, 2.0, -3.0);
p.print();
p.moveByVector(v);
p.print();
return 0;
} | 15.8 | 53 | 0.628692 | [
"object"
] |
cd8a4c4c059ae59e4e1a80a0e54a23af31afa1ea | 747 | cc | C++ | solutions/cpp/22-generate-parentheses.cc | PW486/leetcode | c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9 | [
"Unlicense"
] | null | null | null | solutions/cpp/22-generate-parentheses.cc | PW486/leetcode | c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9 | [
"Unlicense"
] | null | null | null | solutions/cpp/22-generate-parentheses.cc | PW486/leetcode | c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
backtrack(result, "", 0, 0, n);
return result;
}
void backtrack(vector<string> &result, string s, int open, int close,
int max) {
if (s.length() == max * 2) {
result.push_back(s);
return;
}
if (open < max) {
backtrack(result, s + "(", open + 1, close, max);
}
if (close < open) {
backtrack(result, s + ")", open, close + 1, max);
}
}
};
int main() {
vector<string> result = Solution().generateParenthesis(3);
for (int i = 0; i < result.size(); i++) {
cout << result[i] << endl;
}
return 0;
}
| 19.153846 | 71 | 0.554217 | [
"vector"
] |
cd8bc6e06bd77af30cc4c9c7f31d87b361162c85 | 3,445 | cpp | C++ | source/Bit/Graphics/ModelMaterial.cpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | source/Bit/Graphics/ModelMaterial.cpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | source/Bit/Graphics/ModelMaterial.cpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | // ///////////////////////////////////////////////////////////////////////////
// Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com
//
// This software is provided 'as-is', without any express or
// implied warranty. In no event will the authors be held
// liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute
// it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but
// is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any
// source distribution.
// ///////////////////////////////////////////////////////////////////////////
#include <Bit/Graphics/ModelMaterial.hpp>
#include <Bit/System/MemoryLeak.hpp>
namespace Bit
{
// Static declarations of the model material class
const ModelMaterial ModelMaterial::ErrorMaterial;
// Model material class.
ModelMaterial::ModelMaterial( ) :
m_DiffuseColor( 1.0f, 1.0f, 1.0f, 1.0f ),
m_pColorTexture( NULL ),
m_pNormalTexture( NULL ),
m_pSpecularTexture( NULL ),
m_Flags( 0 )
{
}
void ModelMaterial::SetDiffuseColor(const Vector4f32 & p_Color)
{
m_DiffuseColor = p_Color;
}
void ModelMaterial::SetColorTexture( Texture * p_pTexture )
{
m_pColorTexture = p_pTexture;
}
void ModelMaterial::SetNormalTexture( Texture * p_pTexture )
{
m_pNormalTexture = p_pTexture;
}
void ModelMaterial::SetSpecularTexture( Texture * p_pTexture )
{
m_pSpecularTexture = p_pTexture;
}
Texture * ModelMaterial::GetColorTexture( ) const
{
return m_pColorTexture;
}
const Vector4f32 & ModelMaterial::GetDiffuseColor() const
{
return m_DiffuseColor;
}
Texture * ModelMaterial::GetNormalTexture( ) const
{
return m_pNormalTexture;
}
Texture * ModelMaterial::GetSpecularTexture( ) const
{
return m_pSpecularTexture;
}
Bool ModelMaterial::AddExtendedTexture( Texture * p_pTexture, const SizeType p_FlagIndex )
{
// Make sure that we don't have too many textures.
if( m_ExtendedTextures.size( ) == 16 )
{
return false;
}
// Error check the flag index
if( p_FlagIndex >= 16 )
{
return false;
}
// Create the bitmask out of the flag index.
Uint16 bitmask = 1;
bitmask <<= static_cast<SizeType>( p_FlagIndex );
// Check if the texture type already exists
if( m_Flags & bitmask )
{
return false;
}
// Now, everything is fine, so let's add the texture and apply the bitmask.
m_ExtendedTextures.push_back( p_pTexture );
m_Flags |= bitmask;
return true;
}
SizeType ModelMaterial::GetExtendedTextureCount( ) const
{
return static_cast<SizeType>( m_ExtendedTextures.size( ) );
}
Texture * ModelMaterial::GetExtendedTexture( const SizeType p_Index ) const
{
// Error check the index.
if( p_Index >= static_cast<SizeType>( m_ExtendedTextures.size( ) ) )
{
return NULL;
}
// Return the texture pointer
return m_ExtendedTextures[ p_Index ];
}
Uint16 ModelMaterial::GetTextureFlags( ) const
{
return m_Flags;
}
} | 25.145985 | 91 | 0.687373 | [
"model"
] |
cd8c017686ef2e7dbbf4d8a3180fb6dce2251426 | 3,134 | cpp | C++ | Engine/Source/Runtime/CoreUObject/Private/Serialization/ArchiveObjectCrc32.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/CoreUObject/Private/Serialization/ArchiveObjectCrc32.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/CoreUObject/Private/Serialization/ArchiveObjectCrc32.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "CoreUObjectPrivate.h"
DEFINE_LOG_CATEGORY_STATIC(LogArchiveObjectCrc32, Log, All);
//#define DEBUG_ARCHIVE_OBJECT_CRC32
/*----------------------------------------------------------------------------
FArchiveObjectCrc32
----------------------------------------------------------------------------*/
FArchiveObjectCrc32::FArchiveObjectCrc32()
: MemoryWriter(SerializedObjectData)
, ObjectBeingSerialized(NULL)
, RootObject(NULL)
{
ArIgnoreOuterRef = true;
}
void FArchiveObjectCrc32::Serialize(void* Data, int64 Length)
{
MemoryWriter.Serialize(Data, Length);
}
FArchive& FArchiveObjectCrc32::operator<<(class FName& Name)
{
checkSlow(ObjectBeingSerialized);
// Don't include the name of the object being serialized, since that isn't technically part of the object's state
if(Name != ObjectBeingSerialized->GetFName())
{
MemoryWriter << Name;
}
return *this;
}
FArchive& FArchiveObjectCrc32::operator<<(class UObject*& Object)
{
FArchive& Ar = *this;
if (!Object || !Object->IsIn(RootObject))
{
auto UniqueName = GetPathNameSafe(Object);
Ar << UniqueName;
}
else
{
ObjectsToSerialize.Enqueue(Object);
}
return Ar;
}
uint32 FArchiveObjectCrc32::Crc32(UObject* Object, uint32 CRC)
{
#ifdef DEBUG_ARCHIVE_OBJECT_CRC32
const double StartTime = FPlatformTime::Seconds();
UE_LOG(LogArchiveObjectCrc32, Log, TEXT("### Calculating CRC for object: %s with outer: %s"), *Object->GetName(), Object->GetOuter() ? *Object->GetOuter()->GetName() : TEXT("NULL"));
#endif
RootObject = Object;
if (Object)
{
TSet<UObject*> SerializedObjects;
// Start with the given object
ObjectsToSerialize.Enqueue(Object);
// Continue until we no longer have any objects to serialized
while (ObjectsToSerialize.Dequeue(Object))
{
bool bAlreadyProcessed = false;
SerializedObjects.Add(Object, &bAlreadyProcessed);
// If we haven't already serialized this object
if (!bAlreadyProcessed)
{
#ifdef DEBUG_ARCHIVE_OBJECT_CRC32
UE_LOG(LogArchiveObjectCrc32, Log, TEXT("- Serializing object: %s with outer: %s"), *Object->GetName(), Object->GetOuter() ? *Object->GetOuter()->GetName() : TEXT("NULL"));
#endif
// Serialize it
ObjectBeingSerialized = Object;
if (!CustomSerialize(Object))
{
Object->Serialize(*this);
}
ObjectBeingSerialized = NULL;
// Calculate the CRC, compounding it with the checksum calculated from the previous object
CRC = FCrc::MemCrc32(SerializedObjectData.GetData(), SerializedObjectData.Num(), CRC);
#ifdef DEBUG_ARCHIVE_OBJECT_CRC32
UE_LOG(LogArchiveObjectCrc32, Log, TEXT("=> object: '%s', total size: %d bytes, checksum: 0x%08x"), *GetPathNameSafe(Object), SerializedObjectData.Num(), CRC);
#endif
// Cleanup
MemoryWriter.Seek(0L);
SerializedObjectData.Empty();
}
}
// Cleanup
SerializedObjects.Empty();
RootObject = NULL;
}
#ifdef DEBUG_ARCHIVE_OBJECT_CRC32
UE_LOG(LogArchiveObjectCrc32, Log, TEXT("### Finished (%.02f ms), final checksum: 0x%08x"), (FPlatformTime::Seconds() - StartTime) * 1000.0f, CRC);
#endif
return CRC;
} | 28.752294 | 183 | 0.690172 | [
"object"
] |
cd91fef147d8bbcd39fe98e16373ea827a3dd874 | 7,290 | cpp | C++ | Code/Engine/RendererCore/Pipeline/Implementation/RenderPipeline.cpp | eltld/ezEngine | 3230235249dd2769f166872b753efd6bd8347c98 | [
"CC-BY-3.0"
] | null | null | null | Code/Engine/RendererCore/Pipeline/Implementation/RenderPipeline.cpp | eltld/ezEngine | 3230235249dd2769f166872b753efd6bd8347c98 | [
"CC-BY-3.0"
] | null | null | null | Code/Engine/RendererCore/Pipeline/Implementation/RenderPipeline.cpp | eltld/ezEngine | 3230235249dd2769f166872b753efd6bd8347c98 | [
"CC-BY-3.0"
] | 1 | 2020-03-08T04:55:16.000Z | 2020-03-08T04:55:16.000Z | #include <RendererCore/PCH.h>
#include <RendererCore/Pipeline/RenderPipeline.h>
#include <RendererCore/Pipeline/View.h>
#include <RendererCore/RenderContext/RenderContext.h>
#include <RendererCore/RenderLoop/RenderLoop.h>
#include <Foundation/Configuration/CVar.h>
#include <Core/World/World.h>
#include <RendererFoundation/Context/Profiling.h>
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezRenderData, ezReflectedClass, 1, ezRTTINoAllocator);
EZ_END_DYNAMIC_REFLECTED_TYPE();
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezRenderer, ezReflectedClass, 1, ezRTTINoAllocator);
EZ_END_DYNAMIC_REFLECTED_TYPE();
EZ_IMPLEMENT_MESSAGE_TYPE(ezExtractRenderDataMessage);
extern ezCVarBool CVarMultithreadedRendering;
ezRenderPassType ezRenderPipeline::s_uiNextPassType = 0;
ezRenderPipeline::PassTypeData ezRenderPipeline::s_PassTypeData[MAX_PASS_TYPES];
void ezRenderPipeline::PassData::SortRenderData()
{
struct RenderDataComparer
{
EZ_FORCE_INLINE bool Less(const ezRenderData* a, const ezRenderData* b) const
{
return a->GetSortingKey() < b->GetSortingKey();
}
};
m_RenderData.Sort(RenderDataComparer());
}
ezRenderPipeline::ezRenderPipeline()
{
m_CurrentExtractThread = (ezThreadID)0;
m_CurrentRenderThread = (ezThreadID)0;
m_uiLastExtractionFrame = -1;
m_uiLastRenderFrame = -1;
}
ezRenderPipeline::~ezRenderPipeline()
{
ClearPipelineData(&m_Data[0]);
ClearPipelineData(&m_Data[1]);
}
void ezRenderPipeline::ExtractData(const ezView& view)
{
EZ_ASSERT_DEV(m_CurrentExtractThread == (ezThreadID)0, "Extract must not be called from multiple threads.");
m_CurrentExtractThread = ezThreadUtils::GetCurrentThreadID();
// Is this view already extracted?
if (m_uiLastExtractionFrame == ezRenderLoop::GetFrameCounter())
return;
m_uiLastExtractionFrame = ezRenderLoop::GetFrameCounter();
PipelineData* pPipelineData = GetPipelineDataForExtraction();
// Usually clear is not needed, only if the multithreading flag is switched during runtime.
ClearPipelineData(pPipelineData);
// Store camera and viewdata
pPipelineData->m_Camera = *view.GetRenderCamera();
pPipelineData->m_ViewData = view.GetData();
// Extract object render data
{
ezExtractRenderDataMessage msg;
msg.m_pView = &view;
EZ_LOCK(view.GetWorld()->GetReadMarker());
/// \todo use spatial data to do visibility culling etc.
for (auto it = view.GetWorld()->GetObjects(); it.IsValid(); ++it)
{
const ezGameObject* pObject = it;
if (!view.m_ExcludeTags.IsEmpty() && view.m_ExcludeTags.IsAnySet(pObject->GetTags()))
continue;
if (!view.m_IncludeTags.IsEmpty() && !view.m_IncludeTags.IsAnySet(pObject->GetTags()))
continue;
pObject->SendMessage(msg);
}
}
for (ezUInt32 uiPassIndex = 0; uiPassIndex < pPipelineData->m_PassData.GetCount(); ++uiPassIndex)
{
PassData& data = pPipelineData->m_PassData[uiPassIndex];
data.SortRenderData();
}
m_CurrentExtractThread = (ezThreadID)0;
}
void ezRenderPipeline::Render(ezRenderContext* pRendererContext)
{
EZ_PROFILE_AND_MARKER(pRendererContext->GetGALContext(), m_RenderProfilingID);
EZ_ASSERT_DEV(m_CurrentRenderThread == (ezThreadID)0, "Render must not be called from multiple threads.");
m_CurrentRenderThread = ezThreadUtils::GetCurrentThreadID();
EZ_ASSERT_DEV(m_uiLastRenderFrame != ezRenderLoop::GetFrameCounter(), "Render must not be called multiple times per frame.");
m_uiLastRenderFrame = ezRenderLoop::GetFrameCounter();
const PipelineData* pPipelineData = GetPipelineDataForRendering();
const ezCamera* pCamera = &pPipelineData->m_Camera;
const ezViewData* pViewData = &pPipelineData->m_ViewData;
auto& gc = pRendererContext->WriteGlobalConstants();
gc.CameraPosition = pCamera->GetPosition();
gc.CameraDirForwards = pCamera->GetDirForwards();
gc.CameraDirRight = pCamera->GetDirRight();
gc.CameraDirUp = pCamera->GetDirUp();
gc.CameraToScreenMatrix = pViewData->m_ProjectionMatrix;
gc.ScreenToCameraMatrix = pViewData->m_InverseProjectionMatrix;
gc.WorldToCameraMatrix = pViewData->m_ViewMatrix;
gc.CameraToWorldMatrix = pViewData->m_InverseViewMatrix;
gc.WorldToScreenMatrix = pViewData->m_ViewProjectionMatrix;
gc.ScreenToWorldMatrix = pViewData->m_InverseViewProjectionMatrix;
gc.Viewport = ezVec4(pViewData->m_ViewPortRect.x, pViewData->m_ViewPortRect.y, pViewData->m_ViewPortRect.width, pViewData->m_ViewPortRect.height);
ezRenderViewContext renderViewContext;
renderViewContext.m_pCamera = pCamera;
renderViewContext.m_pViewData = pViewData;
renderViewContext.m_pRenderContext = pRendererContext;
for (ezUInt32 i = 0; i < m_Passes.GetCount(); ++i)
{
{
EZ_PROFILE_AND_MARKER(pRendererContext->GetGALContext(), m_Passes[i]->m_ProfilingID);
m_Passes[i]->Execute(renderViewContext);
}
}
ClearPipelineData(GetPipelineDataForRendering());
m_CurrentRenderThread = (ezThreadID)0;
}
void ezRenderPipeline::AddPass(ezUniquePtr<ezRenderPipelinePass>&& pPass)
{
pPass->m_pPipeline = this;
pPass->InitializePins();
m_Passes.PushBack(std::move(pPass));
}
void ezRenderPipeline::RemovePass(ezUniquePtr<ezRenderPipelinePass>&& pPass)
{
m_Passes.Remove(pPass);
pPass->m_pPipeline = nullptr;
}
ezRenderPipeline::PipelineData* ezRenderPipeline::GetPipelineDataForExtraction()
{
return &m_Data[ezRenderLoop::GetFrameCounter() & 1];
}
ezRenderPipeline::PipelineData* ezRenderPipeline::GetPipelineDataForRendering()
{
const ezUInt32 uiFrameCounter = ezRenderLoop::GetFrameCounter() + (CVarMultithreadedRendering ? 1 : 0);
return &m_Data[uiFrameCounter & 1];
}
const ezRenderPipeline::PipelineData* ezRenderPipeline::GetPipelineDataForRendering() const
{
const ezUInt32 uiFrameCounter = ezRenderLoop::GetFrameCounter() + (CVarMultithreadedRendering ? 1 : 0);
return &m_Data[uiFrameCounter & 1];
}
// static
void ezRenderPipeline::ClearPipelineData(PipelineData* pPipeLineData)
{
for (ezUInt32 uiPassIndex = 0; uiPassIndex < pPipeLineData->m_PassData.GetCount(); ++uiPassIndex)
{
PassData& data = pPipeLineData->m_PassData[uiPassIndex];
data.m_RenderData.Clear();
}
}
//static
ezRenderPassType ezRenderPipeline::FindOrRegisterPassType(const char* szPassTypeName)
{
EZ_ASSERT_RELEASE(MAX_PASS_TYPES > s_uiNextPassType, "Reached the maximum of %d pass types.", MAX_PASS_TYPES);
ezTempHashedString passTypeName(szPassTypeName);
for (ezRenderPassType type = 0; type < MAX_PASS_TYPES; ++type)
{
if (s_PassTypeData[type].m_sName == passTypeName)
return type;
}
ezRenderPassType newType = s_uiNextPassType;
s_PassTypeData[newType].m_sName.Assign(szPassTypeName);
s_PassTypeData[newType].m_ProfilingID = ezProfilingSystem::CreateId(szPassTypeName);
++s_uiNextPassType;
return newType;
}
ezRenderPassType ezDefaultPassTypes::Opaque = ezRenderPipeline::FindOrRegisterPassType("Opaque");
ezRenderPassType ezDefaultPassTypes::Masked = ezRenderPipeline::FindOrRegisterPassType("Masked");
ezRenderPassType ezDefaultPassTypes::Transparent = ezRenderPipeline::FindOrRegisterPassType("Transparent");
ezRenderPassType ezDefaultPassTypes::Foreground = ezRenderPipeline::FindOrRegisterPassType("Foreground");
EZ_STATICLINK_FILE(RendererCore, RendererCore_Pipeline_Implementation_RenderPipeline);
| 32.544643 | 148 | 0.773663 | [
"render",
"object"
] |
cd98d3ed839eb1af813dd0cdecf8c16439f0ed15 | 6,162 | cc | C++ | exegesis/util/instruction_syntax.cc | the-eager-ghosts/EXEgesis | ca6ab91c0e1f617881a34c8e794ea37466229590 | [
"Apache-2.0"
] | 201 | 2017-05-12T05:04:55.000Z | 2022-03-14T15:49:37.000Z | exegesis/util/instruction_syntax.cc | the-eager-ghosts/EXEgesis | ca6ab91c0e1f617881a34c8e794ea37466229590 | [
"Apache-2.0"
] | 7 | 2017-05-22T11:52:06.000Z | 2022-02-26T16:30:46.000Z | exegesis/util/instruction_syntax.cc | the-eager-ghosts/EXEgesis | ca6ab91c0e1f617881a34c8e794ea37466229590 | [
"Apache-2.0"
] | 35 | 2017-05-16T04:00:06.000Z | 2022-02-27T03:37:16.000Z | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "exegesis/util/instruction_syntax.h"
#include <stddef.h>
#include <algorithm>
#include <vector>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "exegesis/proto/instructions.pb.h"
#include "glog/logging.h"
#include "re2/re2.h"
namespace exegesis {
namespace {
template <typename PrefixCollection>
bool ContainsPrefix(const std::string& str, const PrefixCollection& prefixes) {
for (const auto& prefix : prefixes) {
if (absl::StartsWith(str, prefix)) {
return true;
}
}
return false;
}
std::vector<std::string> SeparateOperandsWithCommas(const std::string& s) {
std::vector<std::string> result;
bool in_parenthesis = false;
int start = 0;
for (int i = 0; i < s.size(); ++i) {
const char& c = s[i];
if (c == '(') {
in_parenthesis = true;
} else if (c == ')') {
in_parenthesis = false;
} else if (c == ',' && !in_parenthesis) {
result.push_back(s.substr(start, i - start));
start = i + 1;
}
}
result.push_back(s.substr(start, s.size() - start));
return result;
}
InstructionOperand ParseOperand(absl::string_view source) {
absl::string_view original_source = source;
static const LazyRE2 kOperandNameRegexp = {R"( *([^{}]*[^{} ]) *)"};
static const LazyRE2 kTagRegexp = {R"( *\{([^}]+)\} *)"};
InstructionOperand operand;
// In the assembly syntax for AVX-512 features introduced in the Intel SDM,
// some tags ({*-sae} and {sae}) are separated from the other operands by a
// comma, even though there is no "real" operand. We parse this as an
// InstructionOperand with a list of tags and an empty name.
// Later, we CHECK() that at least one of the following holds:
// 1. The operand has a non-empty name.
// 2. The operand has one or more tags.
RE2::Consume(&source, *kOperandNameRegexp, operand.mutable_name());
while (!source.empty()) {
CHECK(
RE2::Consume(&source, *kTagRegexp, operand.add_tags()->mutable_name()))
<< "Remaining source: \"" << source << "\"";
}
CHECK(!operand.name().empty() || operand.tags_size() > 0)
<< "Neither operand name nor any tags were found, source = \""
<< original_source << "\"";
return operand;
}
} // namespace
InstructionFormat ParseAssemblyStringOrDie(const std::string& code) {
// The syntax always has the format [prefix] mnemonic op1, op2[, op3].
// We parse it by first splitting the string by commas; this will separate the
// mnemonic and the first operand from the other operands. Then we split the
// mnemonic and the first operand by spaces.
InstructionFormat proto;
std::vector<std::string> parts = SeparateOperandsWithCommas(code);
CHECK(!parts.empty());
// Parse the mnemonic and the optional first operand.
std::string mnemonic_and_first_operand = parts[0];
absl::StripAsciiWhitespace(&mnemonic_and_first_operand);
std::replace(mnemonic_and_first_operand.begin(),
mnemonic_and_first_operand.end(), '\t', ' ');
CHECK(!mnemonic_and_first_operand.empty());
constexpr const char* kX86Prefixes[] = {"LOCK", "REP"};
size_t delimiting_space = mnemonic_and_first_operand.find_first_of(' ');
if (delimiting_space != std::string::npos &&
ContainsPrefix(mnemonic_and_first_operand, kX86Prefixes)) {
delimiting_space =
mnemonic_and_first_operand.find_first_of(' ', delimiting_space + 1);
}
if (delimiting_space == std::string::npos) {
proto.set_mnemonic(mnemonic_and_first_operand);
} else {
proto.set_mnemonic(mnemonic_and_first_operand.substr(0, delimiting_space));
*proto.add_operands() =
ParseOperand(mnemonic_and_first_operand.substr(delimiting_space + 1));
}
// Copy the remaining operands.
for (int i = 1; i < parts.size(); ++i) {
*proto.add_operands() = ParseOperand(parts[i]);
}
return proto;
}
std::string ConvertToCodeString(const InstructionFormat& instruction) {
std::string result = instruction.mnemonic();
bool run_once = false;
for (const auto& operand : instruction.operands()) {
absl::StrAppend(&result, run_once ? ", " : " ", operand.name());
for (const InstructionOperand::Tag& tag : operand.tags()) {
if (!result.empty() && result.back() != ' ') result += ' ';
absl::StrAppend(&result, "{", tag.name(), "}");
}
run_once = true;
}
return result;
}
InstructionFormat* GetOrAddUniqueVendorSyntaxOrDie(
InstructionProto* instruction) {
CHECK(instruction != nullptr);
const int num_vendor_syntaxes = instruction->vendor_syntax_size();
CHECK_LE(num_vendor_syntaxes, 1);
return num_vendor_syntaxes == 0 ? instruction->add_vendor_syntax()
: instruction->mutable_vendor_syntax(0);
}
const InstructionFormat& GetVendorSyntaxWithMostOperandsOrDie(
const InstructionProto& instruction) {
CHECK_GT(instruction.vendor_syntax_size(), 0);
const InstructionFormat* best_syntax = nullptr;
int best_num_operands = -1;
for (const InstructionFormat& syntax : instruction.vendor_syntax()) {
if (syntax.operands_size() > best_num_operands) {
best_syntax = &syntax;
best_num_operands = syntax.operands_size();
}
}
return *best_syntax;
}
bool HasMnemonicInVendorSyntax(const InstructionProto& instruction,
absl::string_view mnemonic) {
for (const InstructionFormat& vendor_syntax : instruction.vendor_syntax()) {
if (vendor_syntax.mnemonic() == mnemonic) return true;
}
return false;
}
} // namespace exegesis
| 36.035088 | 80 | 0.687926 | [
"vector"
] |
cd9d8209147172ac341dfb9655b69fd210c73aad | 7,881 | cpp | C++ | src/spatial_index.cpp | mmicek/kaacore | 2d64543a04358353a0bc2aad3665450a7ea71e7e | [
"MIT"
] | 7 | 2019-10-12T14:07:04.000Z | 2021-12-23T17:53:39.000Z | src/spatial_index.cpp | mmicek/kaacore | 2d64543a04358353a0bc2aad3665450a7ea71e7e | [
"MIT"
] | 1 | 2021-12-23T12:48:19.000Z | 2021-12-23T12:48:19.000Z | src/spatial_index.cpp | mmicek/kaacore | 2d64543a04358353a0bc2aad3665450a7ea71e7e | [
"MIT"
] | 6 | 2019-03-26T23:09:03.000Z | 2021-12-23T12:36:00.000Z | #include <functional>
#include <vector>
#include <chipmunk/chipmunk.h>
#include "kaacore/exceptions.h"
#include "kaacore/log.h"
#include "kaacore/nodes.h"
#include "kaacore/shapes.h"
#include "kaacore/spatial_index.h"
namespace kaacore {
constexpr int circle_shape_generated_points_count = 24;
inline cpBB
convert_bounding_box(const BoundingBox<double>& bounding_box)
{
return cpBBNew(
bounding_box.min_x, bounding_box.min_y, bounding_box.max_x,
bounding_box.max_y);
}
cpBB
_node_wrapper_bbfunc(void* node_wrapper_obj)
{
auto* wrapper = reinterpret_cast<NodeSpatialData*>(node_wrapper_obj);
wrapper->refresh();
KAACORE_ASSERT(
not wrapper->bounding_box.is_nan(),
"Node wrapper is missing bounding box.");
return convert_bounding_box(wrapper->bounding_box);
}
inline constexpr Node*
container_node(const NodeSpatialData* spatial_data)
{
return container_of(spatial_data, &Node::_spatial_data);
}
void
NodeSpatialData::refresh()
{
Node* node = container_node(this);
if (node->query_dirty_flags(Node::DIRTY_SPATIAL_INDEX)) {
KAACORE_LOG_TRACE(
"Trigerred refresh of NodeSpatialData of node: {}", fmt::ptr(node));
const auto node_transformation = node->absolute_transformation();
const auto shape = node->_shape;
if (shape) {
const auto shape_transformation =
Transformation::translate(calculate_realignment_vector(
node->_origin_alignment, shape.vertices_bbox)) |
node_transformation;
this->bounding_points_transformed.resize(
shape.bounding_points.size());
std::transform(
shape.bounding_points.begin(), shape.bounding_points.end(),
this->bounding_points_transformed.begin(),
[&shape_transformation](glm::dvec2 pt) -> glm::dvec2 {
return pt | shape_transformation;
});
this->bounding_box = BoundingBox<double>::from_points(
this->bounding_points_transformed);
} else {
this->bounding_points_transformed.clear();
this->bounding_box = BoundingBox<double>::single_point(
node->_position | node_transformation);
}
KAACORE_LOG_TRACE(
" -> Resulting bbox x:({:.2f}, {:.2f}) y:({:.2f}, {:.2f})",
this->bounding_box.min_x, this->bounding_box.max_x,
this->bounding_box.min_y, this->bounding_box.max_y);
node->clear_dirty_flags(Node::DIRTY_SPATIAL_INDEX_RECURSIVE);
}
}
bool
NodeSpatialData::contains_point(const glm::dvec2 point) const
{
return check_point_in_polygon(this->bounding_points_transformed, point);
}
SpatialIndex::SpatialIndex() : _index_counter(0)
{
this->_cp_index = cpBBTreeNew(_node_wrapper_bbfunc, nullptr);
}
SpatialIndex::~SpatialIndex()
{
cpSpatialIndexFree(this->_cp_index);
}
void
SpatialIndex::start_tracking(Node* node)
{
KAACORE_ASSERT(
not node->_spatial_data.is_indexed, "Node is already indexed.");
KAACORE_LOG_DEBUG("Starting to track node: {}", fmt::ptr(node));
if (node->_indexable) {
this->_add_to_cp_index(node);
} else {
this->_add_to_phony_index(node);
}
node->_spatial_data.is_indexed = true;
}
void
SpatialIndex::stop_tracking(Node* node)
{
KAACORE_ASSERT(node->_spatial_data.is_indexed, "Node is not indexed.");
KAACORE_LOG_DEBUG("Stopping to track node: {}", fmt::ptr(node));
if (node->_indexable) {
this->_remove_from_cp_index(node);
} else {
this->_remove_from_phony_index(node);
}
node->_spatial_data.is_indexed = false;
node->clear_dirty_flags(Node::DIRTY_SPATIAL_INDEX_RECURSIVE);
}
void
SpatialIndex::update_single(Node* node)
{
KAACORE_ASSERT(node->_spatial_data.is_indexed, "Node is not indexed.");
// check if `indexable` state hash been changed
if (node->_indexable == node->_spatial_data.is_phony_indexed) {
if (node->_indexable) {
// state change: non-indexable -> indexable
KAACORE_LOG_DEBUG(
"Node {} switched indexable flag to: true", fmt::ptr(node));
this->_remove_from_phony_index(node);
this->_add_to_cp_index(node);
} else {
// state change: indexable -> non-indexable
KAACORE_LOG_DEBUG(
"Node {} switched indexable flag to: false", fmt::ptr(node));
this->_remove_from_cp_index(node);
this->_add_to_phony_index(node);
}
}
if (not node->_spatial_data.is_phony_indexed) {
cpSpatialIndexReindexObject(
this->_cp_index, &node->_spatial_data,
node->_spatial_data.index_uid);
} else {
// phony index needs no updates
node->clear_dirty_flags(Node::DIRTY_SPATIAL_INDEX_RECURSIVE);
}
}
void
SpatialIndex::refresh_all()
{
cpSpatialIndexReindex(this->_cp_index);
}
std::vector<NodePtr>
SpatialIndex::query_bounding_box(
const BoundingBox<double>& bbox, bool include_shapeless)
{
auto wrapper_results = this->_query_wrappers(bbox);
std::vector<NodePtr> results;
results.reserve(wrapper_results.size());
for (auto wrapper : wrapper_results) {
if (include_shapeless or
wrapper->bounding_points_transformed.size() > 1) {
results.push_back(container_node(wrapper));
}
}
return results;
}
std::vector<NodePtr>
SpatialIndex::query_bounding_box_for_drawing(const BoundingBox<double>& bbox)
{
auto results = this->query_bounding_box(bbox, false);
results.insert(
results.end(), this->_phony_index.begin(), this->_phony_index.end());
return results;
}
std::vector<NodePtr>
SpatialIndex::query_point(const glm::dvec2 point)
{
auto wrapper_results =
this->_query_wrappers(BoundingBox{point.x, point.y, point.x, point.y});
std::vector<NodePtr> results;
for (auto wrapper : wrapper_results) {
if (wrapper->bounding_points_transformed.size() > 1 and
wrapper->contains_point(point)) {
results.push_back(container_node(wrapper));
}
}
return results;
}
cpCollisionID
_cp_spatial_index_query(
void* obj, void* subtree_obj, cpCollisionID cid, void* data)
{
auto wrapper_results =
reinterpret_cast<std::vector<NodeSpatialData*>*>(obj);
auto wrapper = reinterpret_cast<NodeSpatialData*>(subtree_obj);
wrapper_results->push_back(wrapper);
return cid;
}
std::vector<NodeSpatialData*>
SpatialIndex::_query_wrappers(const BoundingBox<double>& bbox)
{
std::vector<NodeSpatialData*> wrapper_results;
auto cp_bbox = convert_bounding_box(bbox);
cpSpatialIndexQuery(
this->_cp_index, reinterpret_cast<void*>(&wrapper_results), cp_bbox,
_cp_spatial_index_query, nullptr);
return wrapper_results;
}
void
SpatialIndex::_add_to_cp_index(Node* node)
{
node->_spatial_data.index_uid = ++this->_index_counter;
node->set_dirty_flags(Node::DIRTY_SPATIAL_INDEX);
cpSpatialIndexInsert(
this->_cp_index, &node->_spatial_data, node->_spatial_data.index_uid);
node->_spatial_data.is_phony_indexed = false;
}
void
SpatialIndex::_remove_from_cp_index(Node* node)
{
KAACORE_ASSERT(
not node->_spatial_data.is_phony_indexed,
"Node is marked as not indexable.");
cpSpatialIndexRemove(
this->_cp_index, &node->_spatial_data, node->_spatial_data.index_uid);
}
void
SpatialIndex::_add_to_phony_index(Node* node)
{
this->_phony_index.insert(node);
node->_spatial_data.is_phony_indexed = true;
}
void
SpatialIndex::_remove_from_phony_index(Node* node)
{
KAACORE_ASSERT(
node->_spatial_data.is_phony_indexed, "Node is marked as indexable.");
this->_phony_index.erase(node);
}
} // namespace kaacore
| 29.852273 | 80 | 0.67631 | [
"shape",
"vector",
"transform"
] |
cd9f292fb937f56fc3be58830fef8fa0a61a2942 | 16,462 | cpp | C++ | tests/testVioBackEnd.cpp | berndpfrommer/Kimera-VIO | bceed7203f824c1bcffc0c195a186d13c5ea2b22 | [
"BSD-2-Clause"
] | 1 | 2020-06-04T20:12:58.000Z | 2020-06-04T20:12:58.000Z | tests/testVioBackEnd.cpp | omarosamahu/Kimera-VIO | a652739af937200a2b82da86c217fec28334f146 | [
"BSD-2-Clause"
] | null | null | null | tests/testVioBackEnd.cpp | omarosamahu/Kimera-VIO | a652739af937200a2b82da86c217fec28334f146 | [
"BSD-2-Clause"
] | null | null | null | /* ----------------------------------------------------------------------------
* Copyright 2017, Massachusetts Institute of Technology,
* Cambridge, MA 02139
* All Rights Reserved
* Authors: Luca Carlone, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file testVioBackEnd.h
* @brief test VioBackEnd
* @author Antoni Rosinol
* @author Luca Carlone
*/
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <random>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <gtsam/base/Vector.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/navigation/ImuBias.h>
#include "kimera-vio/backend/VioBackEnd.h"
#include "kimera-vio/common/vio_types.h"
// only for gtNavState...
#include "kimera-vio/dataprovider/DataProviderInterface-definitions.h"
#include "kimera-vio/imu-frontend/ImuFrontEnd-definitions.h"
#include "kimera-vio/imu-frontend/ImuFrontEndParams.h"
#include "kimera-vio/initial/InitializationBackEnd.h"
#include "kimera-vio/utils/ThreadsafeImuBuffer.h"
DECLARE_string(test_data_path);
namespace VIO {
static const double tol = 1e-7;
/* ************************************************************************* */
// Parameters
static const int num_key_frames =
10; // number of frames of the synthetic scene
static const gtsam::Vector3 p0(0, 0, 0); // initial pose of the robot camera
static const gtsam::Vector3 v(1.0,
0,
0); // velocity of the robot, per time_step
static const int time_step =
1e9; // elapsed time between two consecutive frames is 1 second (1e9 nsecs)
static const Timestamp t_start = 1e9; // ImuBuffer does not allow t = 0;
static const double baseline = 0.5;
static const gtsam::imuBias::ConstantBias imu_bias(
gtsam::Vector3(0.1, -0.1, 0.3),
gtsam::Vector3(0.1, 0.3, -0.2));
using StereoPoses = std::vector<std::pair<gtsam::Pose3, gtsam::Pose3>>;
/* ************************************************************************* */
// Helper functions!
std::vector<Point3> CreateScene() {
std::vector<Point3> points;
// a scene with 8 points
points.push_back(Point3(0, 0, 20));
points.push_back(Point3(0, 20, 20));
points.push_back(Point3(20, 20, 20));
points.push_back(Point3(20, 0, 20));
points.push_back(Point3(5, 5, 25));
points.push_back(Point3(5, 15, 25));
points.push_back(Point3(15, 15, 25));
points.push_back(Point3(15, 5, 25));
return points;
}
/* ------------------------------------------------------------------------- */
StereoPoses CreateCameraPoses(const int num_keyframes,
const double baseline,
const gtsam::Vector3 p0,
const gtsam::Vector3 v) {
StereoPoses poses;
poses.reserve(num_keyframes);
Pose3 L_pose_R(Rot3::identity(), gtsam::Point3(baseline, 0, 0));
// The camera is assumed to face (0, 0, 1): z-forward, y down and x to the
// right
for (int f_id = 0; f_id < num_keyframes; f_id++) {
// constant velocity model along x: the robot moves to the right, keeping
// the point in front of the camera
gtsam::Vector3 p_offset = v * f_id * (time_step / ((double)1e9));
Pose3 pose_left(Rot3::identity(), p0 + p_offset);
Pose3 pose_right = pose_left.compose(L_pose_R);
poses.push_back(std::make_pair(pose_left, pose_right));
}
return poses;
}
/* ------------------------------------------------------------------------- */
void CreateImuBuffer(VIO::utils::ThreadsafeImuBuffer& imu_buf,
const int num_frames,
const gtsam::Vector3 v,
const ImuBias imu_bias,
const gtsam::Vector3 n_gravity,
const Timestamp time_step,
const Timestamp t_start) {
// Synthesize IMU measurements
for (int f_id = 0; f_id < num_frames; f_id++) {
Vector6 acc_gyr;
// constant speed, no acceleration
acc_gyr.head(3) = -n_gravity + imu_bias.accelerometer();
// Camera axis aligned with the world axis in this example
acc_gyr.tail(3) = imu_bias.gyroscope();
Timestamp t = int64_t(f_id) * time_step + t_start;
imu_buf.addMeasurement(t, acc_gyr);
LOG(INFO) << "Timestamp: " << t;
LOG(INFO) << "Accgyr: " << acc_gyr;
}
}
/* ************************************************************************* */
TEST(testVio, robotMovingWithConstantVelocity) {
// Additional parameters
VioBackEndParams vioParams;
vioParams.landmarkDistanceThreshold_ = 30; // we simulate points 20m away
vioParams.horizon_ = 100;
ImuParams imu_params;
imu_params.gyro_noise_ = 0.00016968;
imu_params.acc_noise_ = 0.002;
imu_params.gyro_walk_ = 1.9393e-05;
imu_params.acc_walk_ = 0.003;
imu_params.n_gravity_ = gtsam::Vector3(0.0, 0.0, -9.81);
imu_params.imu_integration_sigma_ = 1.0;
imu_params.nominal_rate_ = 200.0;
// TODO(Toni): test with Combined, I think it actually fails now...
imu_params.imu_preintegration_type_ =
ImuPreintegrationType::kPreintegratedImuMeasurements;
// Create 3D points
std::vector<Point3> pts = CreateScene();
const int num_pts = pts.size();
// Create cameras
double fov = M_PI / 3 * 2;
// Create image size to initiate meaningful intrinsic camera matrix
double img_height = 600;
double img_width = 800;
double fx = img_width / 2 / tan(fov / 2);
double fy = fx;
double s = 0;
double u0 = img_width / 2;
double v0 = img_height / 2;
Cal3_S2 cam_params(fx, fy, s, u0, v0);
// Create camera poses and IMU data
StereoPoses poses;
VIO::utils::ThreadsafeImuBuffer imu_buf(-1);
poses = CreateCameraPoses(num_key_frames, baseline, p0, v);
CreateImuBuffer(imu_buf,
num_key_frames,
v,
imu_bias,
imu_params.n_gravity_,
time_step,
t_start);
// Create measurements
// using SmartStereoMeasurement = pair<LandmarkId,StereoPoint2>;
// using SmartStereoMeasurements = vector<SmartStereoMeasurement>;
// using StatusSmartStereoMeasurements =
// pair<TrackerStatusSummary,SmartStereoMeasurements>;
TrackerStatusSummary tracker_status_valid;
tracker_status_valid.kfTrackingStatus_mono_ = TrackingStatus::VALID;
tracker_status_valid.kfTrackingStatus_stereo_ = TrackingStatus::VALID;
std::vector<StatusStereoMeasurementsPtr> all_measurements;
for (int i = 0; i < num_key_frames; i++) {
gtsam::PinholeCamera<Cal3_S2> cam_left(poses[i].first, cam_params);
gtsam::PinholeCamera<Cal3_S2> cam_right(poses[i].second, cam_params);
SmartStereoMeasurements measurement_frame;
for (int l_id = 0; l_id < num_pts; l_id++) {
Point2 pt_left = cam_left.project2(pts[l_id]);
Point2 pt_right = cam_right.project2(pts[l_id]);
StereoPoint2 pt_lr(pt_left.x(), pt_right.x(), pt_left.y());
EXPECT_DOUBLE_EQ(pt_left.y(), pt_right.y());
measurement_frame.push_back(std::make_pair(l_id, pt_lr));
}
all_measurements.push_back(std::make_shared<StatusStereoMeasurements>(
std::make_pair(tracker_status_valid, measurement_frame)));
}
// create vio
Pose3 B_pose_camLrect;
VioNavState initial_state = VioNavState(poses[0].first, v, imu_bias);
StereoCalibPtr stereo_calibration =
boost::make_shared<gtsam::Cal3_S2Stereo>(cam_params.fx(),
cam_params.fy(),
cam_params.skew(),
cam_params.px(),
cam_params.py(),
baseline);
// Create frontend.
ImuFrontEnd imu_frontend(imu_params, imu_bias);
// Create backend.
std::shared_ptr<VioBackEnd> vio =
std::make_shared<VioBackEnd>(B_pose_camLrect,
stereo_calibration,
vioParams,
imu_params,
BackendOutputParams(false, 0, false),
false);
vio->registerImuBiasUpdateCallback(std::bind(
&ImuFrontEnd::updateBias, std::ref(imu_frontend), std::placeholders::_1));
vio->initStateAndSetPriors(VioNavStateTimestamped(t_start, initial_state));
// For each frame, add landmarks and optimize.
for (FrameId k = 1; k < num_key_frames; k++) {
// Time stamp for the current keyframe and the next frame.
Timestamp timestamp_lkf = (k - 1) * time_step + t_start;
Timestamp timestamp_k = k * time_step + t_start;
// Get the IMU data
ImuStampS imu_stamps;
ImuAccGyrS imu_accgyr;
CHECK(imu_buf.getImuDataInterpolatedUpperBorder(
timestamp_lkf, timestamp_k, &imu_stamps, &imu_accgyr) ==
VIO::utils::ThreadsafeImuBuffer::QueryResult::kDataAvailable);
const auto& pim =
imu_frontend.preintegrateImuMeasurements(imu_stamps, imu_accgyr);
// process data with VIO
vio->spinOnce(BackendInput(timestamp_k,
all_measurements[k],
tracker_status_valid.kfTrackingStatus_stereo_,
pim));
// At this point the update imu bias callback should be triggered which
// will update the imu_frontend imu bias.
imu_frontend.resetIntegrationWithCachedBias();
const gtsam::NonlinearFactorGraph& nlfg = vio->getFactorsUnsafe();
size_t nrFactorsInSmoother = 0;
for (const auto& f : nlfg) { // count the number of nonempty factors
if (f) nrFactorsInSmoother++;
}
LOG(INFO) << "at frame " << k << " nr factors: " << nrFactorsInSmoother;
if (imu_params.imu_preintegration_type_ ==
ImuPreintegrationType::kPreintegratedCombinedMeasurements) {
EXPECT_EQ(nrFactorsInSmoother,
3 + k + 8); // 3 priors, 1 imu per time stamp, 8 smart factors
} else {
if (k == 1) {
EXPECT_EQ(nrFactorsInSmoother,
3 + 2 * k); // 3 priors, 1 imu + 1 between per time stamp: we
// do not include smart factors of length 1
} else {
EXPECT_EQ(nrFactorsInSmoother,
3 + 2 * k + 8); // 3 priors, 1 imu + 1 between per time
// stamp, 8 smart factors
}
}
// Check the results!
const gtsam::Values& results = vio->getState();
for (FrameId f_id = 0; f_id <= k; f_id++) {
Pose3 W_Pose_Blkf = results.at<gtsam::Pose3>(gtsam::Symbol('x', f_id));
gtsam::Vector3 W_Vel_Blkf =
results.at<gtsam::Vector3>(gtsam::Symbol('v', f_id));
ImuBias imu_bias_lkf = results.at<ImuBias>(gtsam::Symbol('b', f_id));
EXPECT_TRUE(assert_equal(poses[f_id].first, W_Pose_Blkf, tol));
EXPECT_LT((W_Vel_Blkf - v).norm(), tol);
EXPECT_LT((imu_bias_lkf - imu_bias).vector().norm(), tol);
}
}
}
/* ************************************************************************* */
// TODO(Sandro): Move this test to separate file!
TEST(testVio, robotMovingWithConstantVelocityBundleAdjustment) {
// Additional parameters
VioBackEndParams vioParams;
vioParams.landmarkDistanceThreshold_ = 100; // we simulate points 30-40m away
vioParams.horizon_ = 100;
vioParams.smartNoiseSigma_ = 0.001;
vioParams.outlierRejection_ = 100;
vioParams.betweenTranslationPrecision_ = 1;
ImuParams imu_params;
imu_params.gyro_noise_ = 0.00016968;
imu_params.acc_noise_ = 0.002;
imu_params.gyro_walk_ = 1.9393e-05;
imu_params.acc_walk_ = 0.003;
imu_params.n_gravity_ = gtsam::Vector3(0.0, 0.0, -9.81);
imu_params.imu_integration_sigma_ = 1.0;
imu_params.nominal_rate_ = 200.0;
// Create 3D points
std::vector<Point3> pts = CreateScene();
const int num_pts = pts.size();
// Create cameras
double fov = M_PI / 3 * 2;
// Create image size to initiate meaningful intrinsic camera matrix
double img_height = 600;
double img_width = 800;
double fx = img_width / 2 / tan(fov / 2);
double fy = fx;
double s = 0;
double u0 = img_width / 2;
double v0 = img_height / 2;
// Random noise generator for ransac pose (concatenated!)
double rad_sigma = 0.005;
double pos_sigma = 0.01;
Cal3_S2 cam_params(fx, fy, s, u0, v0);
// Create camera poses and IMU data
StereoPoses poses;
VIO::utils::ThreadsafeImuBuffer imu_buf(-1);
poses = CreateCameraPoses(num_key_frames, baseline, p0, v);
CreateImuBuffer(imu_buf,
num_key_frames,
v,
imu_bias,
imu_params.n_gravity_,
time_step,
t_start);
// Create measurements
TrackerStatusSummary tracker_status_valid;
tracker_status_valid.kfTrackingStatus_mono_ = TrackingStatus::VALID;
tracker_status_valid.kfTrackingStatus_stereo_ = TrackingStatus::VALID;
std::vector<StatusStereoMeasurementsPtr> all_measurements;
for (int i = 0; i < num_key_frames; i++) {
gtsam::PinholeCamera<Cal3_S2> cam_left(poses[i].first, cam_params);
gtsam::PinholeCamera<Cal3_S2> cam_right(poses[i].second, cam_params);
SmartStereoMeasurements measurement_frame;
for (int l_id = 0; l_id < num_pts; l_id++) {
Point2 pt_left = cam_left.project2(pts[l_id]);
Point2 pt_right = cam_right.project2(pts[l_id]);
StereoPoint2 pt_lr(pt_left.x(), pt_right.x(), pt_left.y());
EXPECT_DOUBLE_EQ(pt_left.y(), pt_right.y());
measurement_frame.push_back(std::make_pair(l_id, pt_lr));
}
all_measurements.push_back(std::make_shared<StatusStereoMeasurements>(
std::make_pair(tracker_status_valid, measurement_frame)));
}
// create vio
Pose3 B_pose_camLrect;
StereoCalibPtr stereo_calibration =
boost::make_shared<gtsam::Cal3_S2Stereo>(cam_params.fx(),
cam_params.fy(),
cam_params.skew(),
cam_params.px(),
cam_params.py(),
baseline);
std::shared_ptr<InitializationBackEnd> vio =
std::make_shared<InitializationBackEnd>(
B_pose_camLrect,
stereo_calibration,
vioParams,
imu_params,
BackendOutputParams(false, 0, false));
ImuFrontEnd imu_frontend(imu_params, imu_bias);
// Create vector of input payloads
std::vector<BackendInput::UniquePtr> input_vector;
input_vector.clear();
// For each frame, add landmarks.
for (int64_t k = 1; k < num_key_frames; k++) {
// Time stamp for the current keyframe and the next frame.
Timestamp timestamp_lkf = (k - 1) * time_step + t_start;
Timestamp timestamp_k = k * time_step + t_start;
// Get the IMU data
ImuStampS imu_stamps;
ImuAccGyrS imu_accgyr;
CHECK(imu_buf.getImuDataInterpolatedUpperBorder(
timestamp_lkf, timestamp_k, &imu_stamps, &imu_accgyr) ==
VIO::utils::ThreadsafeImuBuffer::QueryResult::kDataAvailable);
const auto& pim =
imu_frontend.preintegrateImuMeasurements(imu_stamps, imu_accgyr);
// Push input payload into queue
BackendInput::UniquePtr input = VIO::make_unique<BackendInput>(
timestamp_k,
all_measurements[k],
tracker_status_valid.kfTrackingStatus_stereo_,
pim);
// Create artificially noisy "RANSAC" pose measurements
gtsam::Pose3 random_pose = (poses[k - 1].first).between(poses[k].first) *
UtilsOpenCV::RandomPose3(rad_sigma, pos_sigma);
input->stereo_ransac_body_pose_ = random_pose;
// Create input vector for backend
input_vector.push_back(std::move(input));
}
// Perform Bundle Adjustment
std::vector<gtsam::Pose3> results =
vio->addInitialVisualStatesAndOptimize(input_vector);
CHECK_EQ(results.size(), num_key_frames - 1);
// Check error (BA results start at origin, as convention)
// The tolerance is on compounded error!! Not relative.
for (int f_id = 0; f_id < (num_key_frames - 1); f_id++) {
Pose3 W_Pose_Blkf = poses[1].first.compose(results.at(f_id));
EXPECT_TRUE(assert_equal(
poses[f_id + 1].first, W_Pose_Blkf, vioParams.smartNoiseSigma_));
}
}
} // namespace VIO
| 38.194896 | 80 | 0.623922 | [
"geometry",
"vector",
"model",
"3d"
] |
cdaab62257682da5b88edc032ae118e0fa8f6220 | 15,507 | cpp | C++ | src/gui/src/grid_window.cpp | pierre-dejoue/picross-solver | c4d85d66b7537e4651d411cb6480a34bb4fcf51b | [
"MIT"
] | null | null | null | src/gui/src/grid_window.cpp | pierre-dejoue/picross-solver | c4d85d66b7537e4651d411cb6480a34bb4fcf51b | [
"MIT"
] | null | null | null | src/gui/src/grid_window.cpp | pierre-dejoue/picross-solver | c4d85d66b7537e4651d411cb6480a34bb4fcf51b | [
"MIT"
] | null | null | null | #include "grid_window.h"
#include "err_window.h"
#include "settings.h"
#include <picross/picross_io.h>
#include <utils/bitmap_io.h>
#include <utils/picross_file_io.h>
#include <utils/strings.h>
#include "portable-file-dialogs.h"
#include <iostream>
#include <sstream>
#include <utility>
namespace
{
constexpr ImU32 ColorGridBack = IM_COL32(255, 255, 255, 255);
constexpr ImU32 ColorGridOutline = IM_COL32(224, 224, 224, 255);
// Default tile colors (branching depth = 0)
constexpr ImU32 ColorTileBorder = IM_COL32(20, 90, 116, 255);
constexpr ImU32 ColorTileFilled = IM_COL32(91, 94, 137, 255);
constexpr ImU32 ColorTileEmpty = IM_COL32(216, 216, 224, 255);
// Branching colors
constexpr unsigned int DepthColors = 3;
constexpr ImU32 ColorTileDepth1Border = IM_COL32(116, 20, 90, 255);
constexpr ImU32 ColorTileDepth1Filled = IM_COL32(137, 91, 94, 255);
constexpr ImU32 ColorTileDepth1Empty = IM_COL32(224, 216, 216, 255);
constexpr ImU32 ColorTileDepth2Border = IM_COL32(90, 116, 20, 255);
constexpr ImU32 ColorTileDepth2Filled = IM_COL32(94, 137, 91, 255);
constexpr ImU32 ColorTileDepth2Empty = IM_COL32(216, 224, 216, 255);
const ImU32& get_color_tile_border(unsigned int depth = 0)
{
static const ImU32 Colors[3] = { ColorTileBorder, ColorTileDepth1Border, ColorTileDepth2Border };
return Colors[depth % DepthColors];
}
const ImU32& get_color_tile_filled(unsigned int depth = 0)
{
static const ImU32 Colors[3] = { ColorTileFilled, ColorTileDepth1Filled, ColorTileDepth2Filled };
return Colors[depth % DepthColors];
}
const ImU32& get_color_tile_empty(unsigned int depth = 0)
{
static const ImU32 Colors[3] = { ColorTileEmpty, ColorTileDepth1Empty, ColorTileDepth2Empty };
return Colors[depth % DepthColors];
}
void draw_background_grid(ImDrawList* draw_list, ImVec2 tl_corner, size_t tile_size, size_t width, size_t height, bool outline = false)
{
const ImVec2 br_corner = ImVec2(tl_corner.x + static_cast<float>(width * tile_size), tl_corner.y + static_cast<float>(height * tile_size));
draw_list->AddRectFilled(tl_corner, br_corner, ColorGridBack);
if (outline)
{
for (size_t i = 0u; i <= width; ++i)
{
const float x = static_cast<float>(i * tile_size);
draw_list->AddLine(ImVec2(tl_corner.x + x, tl_corner.y), ImVec2(tl_corner.x + x, br_corner.y), ColorGridOutline);
}
for (size_t j = 0u; j <= height; ++j)
{
const float y = static_cast<float>(j * tile_size);
draw_list->AddLine(ImVec2(tl_corner.x, tl_corner.y + y), ImVec2(br_corner.x, tl_corner.y + y), ColorGridOutline);
}
}
}
void draw_tile(ImDrawList* draw_list, ImVec2 tl_corner, size_t tile_size, size_t i, size_t j, bool filled, unsigned int depth = 0, float size_ratio = 1.f, float rounding_ratio = 0.f)
{
assert(0.f < size_ratio && size_ratio <= 1.f);
assert(0.f <= rounding_ratio && rounding_ratio <= 1.f);
const float padding = static_cast<float>(tile_size - 1) * 0.5f * (1.f - size_ratio);
const float rounding = static_cast<float>(tile_size - 1) * 0.5f * rounding_ratio;
const ImVec2 tl_tile_corner = ImVec2(
tl_corner.x + static_cast<float>(i * tile_size + 1) + padding,
tl_corner.y + static_cast<float>(j * tile_size + 1) + padding);
const ImVec2 br_tile_corner = ImVec2(
tl_corner.x + static_cast<float>((i+1) * tile_size) - padding,
tl_corner.y + static_cast<float>((j+1) * tile_size) - padding);
draw_list->AddRectFilled(tl_tile_corner, br_tile_corner, filled ? get_color_tile_filled(depth) : get_color_tile_empty(depth), rounding);
draw_list->AddRect(tl_tile_corner, br_tile_corner, get_color_tile_border(depth), rounding);
}
} // Anonymous namespace
GridWindow::LineEvent::LineEvent(picross::Solver::Event event, const picross::Line* delta, const ObserverGrid& grid)
: event(event)
, delta()
, grid(grid)
{
if (delta)
{
this->delta = std::make_unique<picross::Line>(*delta);
}
}
GridWindow::GridWindow(picross::InputGrid&& grid, const std::string& source, bool start_thread)
: GridObserver(grid.cols.size(), grid.rows.size())
, grid(std::move(grid))
, title()
, solver_thread()
, solver_thread_start(start_thread)
, solver_thread_completed(false)
, solver_thread_abort(false)
, text_buffer_mutex()
, text_buffer()
, solutions()
, valid_solutions(0)
, allocate_new_solution(false)
, tabs()
, line_events()
, line_cv()
, line_mutex()
, max_nb_solutions(0u)
, speed(1u)
{
title = this->grid.name + " (" + source + ")";
}
GridWindow::~GridWindow()
{
solver_thread_abort = true;
line_cv.notify_all();
if (solver_thread.joinable())
{
std::cerr << "Aborting grid " << grid.name << "..." << std::endl;
solver_thread.join();
}
}
void GridWindow::visit(bool& canBeErased, Settings& settings)
{
const size_t width = grid.cols.size();
const size_t height = grid.rows.size();
const Settings::Tile& tile_settings = settings.read_tile_settings();
const Settings::Solver& solver_settings = settings.read_solver_settings();
const Settings::Animation& animation_settings = settings.read_animation_settings();
if (animation_settings.speed != speed)
{
speed = animation_settings.speed;
line_cv.notify_one();
}
bool tab_auto_select_last_solution = false;
max_nb_solutions = solver_settings.limit_solutions ? static_cast<unsigned int>(solver_settings.max_nb_solutions) : 0u;
static const std::vector<size_t> TileSizes = { 12, 18, 24 };
const size_t tile_size = TileSizes.at(static_cast<size_t>(tile_settings.size_enum));
ImGui::SetNextWindowSize(ImVec2(20 + static_cast<float>(width * tile_size), 100 + static_cast<float>(height * tile_size)));
bool isWindowOpen = true;
if (!ImGui::Begin(title.c_str(), &isWindowOpen))
{
// Collapsed
canBeErased = !isWindowOpen;
ImGui::End();
return;
}
canBeErased = !isWindowOpen;
// Solver thread state
const bool solver_thread_active = solver_thread.joinable();
// Trigger solver thread
if (solver_thread_start)
{
assert(!solver_thread_active);
reset_solutions();
solver_thread_completed = false;
std::swap(solver_thread, std::thread(&GridWindow::solve_picross_grid, this));
solver_thread_start = false;
}
// If solver thread is active
else if (solver_thread_active)
{
if (solver_thread_completed)
{
// The solver thread being over does not mean that all observer events have been processed
solver_thread.join();
std::swap(solver_thread, std::thread());
assert(!solver_thread.joinable());
std::cerr << "End of solver thread for grid " << grid.name << std::endl;
}
// Fetch the latest observer events
std::vector<LineEvent> local_events;
{
std::lock_guard<std::mutex> lock(line_mutex);
if (!line_events.empty())
{
local_events.reserve(speed);
std::swap(local_events, line_events);
}
}
if (!local_events.empty())
{
// Unblock the waiting solver thread
line_cv.notify_one();
// Process observer event
const unsigned int added_solutions = process_line_events(local_events);
// If we opened a new solution tab, make sure it is auto-selected once
tab_auto_select_last_solution = added_solutions > 0;
}
}
// Remove the last solution if not valid
else if (valid_solutions < solutions.size())
{
assert(solver_thread_completed);
assert(line_events.empty());
solutions.erase(solutions.end() - 1);
tabs.erase(tabs.end() - 1);
}
// Reset button
if (!solver_thread_active && ImGui::Button("Solve"))
{
solver_thread_start = true; // Triggered for next frame
}
else if (solver_thread_active && ImGui::Button("Stop"))
{
solver_thread_abort = true; // Flag to signal the solver thread to stop its current processing
}
// Save button
ImGui::SameLine();
if (ImGui::Button("Save as"))
{
save_grid();
}
// Text
{
std::lock_guard<std::mutex> lock(text_buffer_mutex);
ImGui::TextUnformatted(text_buffer.begin(), text_buffer.end());
}
// Solutions tabs
{
if (solutions.empty())
{
// No solutions, or not yet computed
ImGui::End();
return;
}
}
// Solutions vector was swapped once, therefore can now being accessed without lock
if (ImGui::BeginTabBar("##TabBar"))
{
for (unsigned int idx = 0u; idx < solutions.size(); ++idx)
{
const auto last_idx = idx == solutions.size() - 1;
const ImGuiTabItemFlags tab_flags = (tab_auto_select_last_solution && last_idx) ? ImGuiTabItemFlags_SetSelected : ImGuiTabItemFlags_None;
if (ImGui::BeginTabItem(tabs.at(idx).c_str(), nullptr, tab_flags))
{
const auto& solution = solutions.at(idx);
assert(idx + 1 == solutions.size() || solution.is_solved());
ImDrawList* draw_list = ImGui::GetWindowDrawList();
assert(draw_list);
ImVec2 grid_tl_corner = ImGui::GetCursorScreenPos();
draw_background_grid(draw_list, grid_tl_corner, tile_size, width, height, true);
for (size_t i = 0u; i < width; ++i)
for (size_t j = 0u; j < height; ++j)
{
const auto tile = solution.get(i, j);
const auto depth = animation_settings.show_branching && solver_thread_active && idx + 1 == solutions.size()
? solution.get_depth(i, j)
: 0;
if (tile == picross::Tile::UNKNOWN)
continue;
draw_tile(draw_list, grid_tl_corner, tile_size, i, j, tile == picross::Tile::ONE, depth, tile_settings.size_ratio, tile_settings.rounding_ratio);
}
ImGui::EndTabItem();
}
}
ImGui::EndTabBar();
}
ImGui::End();
}
bool GridWindow::abort_solver_thread() const
{
return solver_thread_abort;
}
void GridWindow::reset_solutions()
{
assert(!solver_thread.joinable());
solver_thread_abort = false;
allocate_new_solution = false;
valid_solutions = 0;
solutions.clear();
tabs.clear();
observer_clear();
line_events.clear();
// Clear text buffer and print out the grid size
const size_t width = grid.cols.size();
const size_t height = grid.rows.size();
text_buffer.clear();
text_buffer.appendf("Grid %s\n", grid_size_str(grid).c_str());
}
void GridWindow::observer_callback(picross::Solver::Event event, const picross::Line* delta, unsigned int depth, const ObserverGrid& grid)
{
std::unique_lock<std::mutex> lock(line_mutex);
if (line_events.size() >= speed)
{
// Wait until the previous line events have been consumed
line_cv.wait(lock, [this]() -> bool {
return (this->speed > 0u && this->line_events.empty())
|| this->abort_solver_thread();
});
}
line_events.emplace_back(event, delta, grid);
}
unsigned int GridWindow::process_line_events(std::vector<LineEvent>& events)
{
assert(!events.empty());
unsigned int count_allocated = 0u;
for (auto& event : events)
{
if (allocate_new_solution || solutions.empty())
{
allocate_new_solution = false;
count_allocated++;
solutions.emplace_back(std::move(event.grid));
}
else
{
solutions.back() = std::move(event.grid);
}
switch (event.event)
{
case picross::Solver::Event::BRANCHING:
break;
case picross::Solver::Event::DELTA_LINE:
break;
case picross::Solver::Event::SOLVED_GRID:
valid_solutions++;
allocate_new_solution = true; // Allocate new solution on next event
break;
default:
throw std::invalid_argument("Unknown Solver::Event");
}
// Adjust number of tabs
if (tabs.size() < solutions.size())
{
tabs.emplace_back("Solution " + std::to_string(tabs.size() + 1));
}
assert(tabs.size() == solutions.size());
}
return count_allocated;
}
// Solver thread
void GridWindow::solve_picross_grid()
{
assert(!solver_thread_completed);
const auto solver = picross::get_ref_solver();
unsigned count_grids = 0u;
// Sanity check of the input data
bool check;
std::string check_msg;
std::tie(check, check_msg) = picross::check_grid_input(grid);
if (check)
{
solver->set_observer(std::reference_wrapper<GridObserver>(*this));
solver->set_abort_function([this]() { return this->abort_solver_thread(); });
picross::Solver::Status status;
std::vector<picross::OutputGrid> local_solutions;
std::tie (status, local_solutions) = solver->solve(grid, max_nb_solutions);
if (status == picross::Solver::Status::ABORTED)
{
std::lock_guard<std::mutex> lock(text_buffer_mutex);
text_buffer.appendf("Processing aborted\n");
}
else if (status == picross::Solver::Status::CONTRADICTORY_GRID)
{
std::lock_guard<std::mutex> lock(text_buffer_mutex);
text_buffer.appendf("Could not solve that grid :-(\n");
}
else if (local_solutions.empty())
{
std::lock_guard<std::mutex> lock(text_buffer_mutex);
text_buffer.appendf("No solution could be found\n");
}
else
{
// Solutions are filled by the observer
}
}
else
{
std::lock_guard<std::mutex> lock(text_buffer_mutex);
text_buffer.appendf("Invalid grid. Error message: %s\n", check_msg.c_str());
}
solver_thread_completed = true;
}
void GridWindow::save_grid()
{
const auto file_path = pfd::save_file(
"Select a file", "",
{ "Picross file", "*.txt",
"NON file", "*.non",
"Bitmap (*.pbm)", "*.pbm" },
pfd::opt::force_overwrite).result();
if (!file_path.empty())
{
const auto err_handler = [this](const std::string& msg, picross::io::ExitCode)
{
std::lock_guard<std::mutex> lock(this->text_buffer_mutex);
this->text_buffer.appendf("%s\n", msg);
};
const std::string ext = str_tolower(file_extension(file_path));
if (ext == "pbm")
{
if (!solutions.empty())
{
export_bitmap_pbm(file_path, solutions[0], err_handler);
}
}
else
{
save_picross_file(file_path, grid, err_handler);
}
}
}
| 33.71087 | 186 | 0.609531 | [
"vector"
] |
cdad97d56110b6866a7f96d4ea65a1cc935cf9f9 | 15,847 | cpp | C++ | SOURCES/graphics/objects/objlist.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/graphics/objects/objlist.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/graphics/objects/objlist.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | /***************************************************************************\
ObjList.cpp
Scott Randolph
April 22, 1996
Manage the list of active objects to be drawn each frame for a given
renderer.
\***************************************************************************/
#include <math.h>
#include "grTypes.h"
#include "Matrix.h"
#include "ObjList.h"
#include "RenderOW.h"
#include "Falclib\Include\IsBad.h"
#include "FalcLib\include\dispopts.h" //JAM 04Oct03
#include "Graphics\DXEngine\DXEngine.h"
#include "Graphics\DXEngine\DXVBManager.h"
#include "DrawBsp.h"
#define _USE_OLD_SORT_ 1 // turn this off to make the sort 10 times slower...
/***************************************************************************\
Clean up the object display list
\***************************************************************************/
ObjectDisplayList::ObjectDisplayList()
{
head = NULL;
tail = NULL;
nextToDraw = NULL;
updateCBlist = NULL;
sortCBlist = NULL;
}
/***************************************************************************\
Clean up the object display list
\***************************************************************************/
ObjectDisplayList::~ObjectDisplayList()
{
// Commented out because it doesn't crash and we're desperate
// ShiAssert ( !head );
// KCK: This is kept around for shits and grins (and release, I guess)
while (head) {
RemoveObject( head );
}
// Commented out because it doesn't crash and we're desperate
// ShiAssert ( !head ); ShiAssert( !head );
// ShiAssert( !tail );
}
/***************************************************************************\
Add an instance of an object to the active display list
\***************************************************************************/
void ObjectDisplayList::InsertObject( DrawableObject *object )
{
ShiAssert( object );
ShiAssert( !object->InDisplayList() );
#ifdef _SANITY_CHECK_
if(object->InDisplayList())
return;
if(object == head)
return;
#endif
// Set up the links in the object
object->prev = NULL;
object->next = head;
object->SetParentList( this );
// Add the new entry at the head of this list
if (head) {
head->prev = object;
} else {
tail = object;
}
head = object;
#ifdef _SANITY_CHECK_
if(head->prev != NULL)
head->prev=NULL;
#endif
}
/***************************************************************************\
Remove an instance of an object from this display list
\***************************************************************************/
void ObjectDisplayList::RemoveObject( DrawableObject* object )
{
// sfr: @todo remove JB checks
if (F4IsBadReadPtr(this, sizeof(ObjectDisplayList))) // JB 010307 CTD
return; // JB 010307 CTD
if (F4IsBadReadPtr(object, sizeof(DrawableObject))) // JB 010221 CTD
return; // JB 010221 CTD
#ifdef _SANITY_CHECK_
if ( !object->parentList )
return;
if ( object->parentList != this )
return;
#endif
// If we're removing the "nextToDraw" object, step to the next one
if (object == nextToDraw) {
nextToDraw = object->next;
}
// Take the given object out of the active list
if (object->prev) {
if (!F4IsBadWritePtr(object->prev, sizeof (DrawableObject))) // JB 010221 CTD
object->prev->next = object->next;
} else {
ShiAssert( head == object );
head = object->next;
}
if (object->next) {
if (!F4IsBadWritePtr(object->next, sizeof (DrawableObject))) // JB 010221 CTD
object->next->prev = object->prev;
} else {
ShiAssert( tail == object );
tail = object->prev;
}
// Remove this objects links into the display list
object->prev = object->next = NULL;
object->SetParentList( NULL );
}
/*****************************************************************************\
Compute the distance metrics for each entry in the display list
given the new view point. Entries below the bottom Z value given will
be removed from the list and placed into the "lowList" chain. Entries
which are too high will go into the "highList" chain.
this version ONLY calculates the distance for the objects in it's list
\*****************************************************************************/
void ObjectDisplayList::UpdateMetrics(const Tpoint *pos)
{
register float x = pos->x;
register float y = pos->y;
// register float z = pos->z;
DrawableObject *p;
// Quit now if we don't have at least one list entry
if ( !head ) return;
// Run through the whole list and compute the sorting metrics for each entry
p = head;
//while ( p )
while ( p && !F4IsBadReadPtr(p, sizeof(DrawableObject))) // JB 010318 CTD
{
// Update the distance metric (not less than 0)
p->distance = max( (float)fabs(x - p->position.x), (float)fabs(y - p->position.y) );
ShiAssert(!_isnan(p->distance));
if(_isnan(p->distance))
{
p->distance = 0.0f;
}
else if (p->distance > p->Radius())
{
p->distance = p->distance - p->Radius();
}
else
{
p->distance = 0.0f;
}
p=p->next;
}
}
/*****************************************************************************\
Compute the distance metrics for each entry in the display list
given the new view point. Entries below the bottom Z value given will
be removed from the list and placed into the "lowList" chain. Entries
which are too high will go into the "highList" chain.
\*****************************************************************************/
void ObjectDisplayList::UpdateMetrics( long listNo, const Tpoint *pos, TransportStr *transList )
{
register float x = pos->x;
register float y = pos->y;
// register float z = pos->z;
DrawableObject *p;
DrawableObject *q;
long i;
// Quit now if we don't have at least one list entry
if ( !head ) return;
#ifdef _SANITY_CHECK_
if ( head )
{
DrawableObject *_cur_;
long count=0;
// Sanity checks
if (head->parentList != this)
return;
if(head->prev)
{
head->prev=NULL;
}
_cur_=head;
while(_cur_ && count < 10000)
{
if (_cur_->parentList != this)
return;
_cur_=_cur_->next;
count++;
}
if(_cur_)
{
head->prev=NULL; // painless breakpoint
}
}
#endif
// Run through the whole list and compute the sorting metrics for each entry
q = head;
while ( q ) {
p=q;
q=q->next;
// Update the distance metric (not less than 0)
p->distance = max( (float)fabs(x - p->position.x), (float)fabs(y - p->position.y) );
ShiAssert(!_isnan(p->distance));
if(_isnan(p->distance))
{
p->distance = 0.0f;
}
else if (p->distance > p->Radius())
{
p->distance = p->distance - p->Radius();
}
else
{
p->distance = 0.0f;
}
if (transList)
{
if (p->position.z >= transList->bottom[listNo] && listNo)
{
i=listNo-1;
while(i > 0 && p->position.z >= transList->bottom[i])
i--;
// remove object from objectList
RemoveObject(p);
// head insert object into transport list
p->next=transList->list[i];
transList->list[i]=p;
}
else if(p->position.z < transList->top[listNo] && listNo < (_NUM_OBJECT_LISTS_-1))
{
i=listNo+1;
while(i < (_NUM_OBJECT_LISTS_-1) && p->position.z < transList->top[i])
i++;
// remove object from objectList
RemoveObject(p);
// head insert object into transport list
p->next=transList->list[i];
transList->list[i]=p;
}
}
}
#ifdef _SANITY_CHECK_
if ( head )
{
DrawableObject *_cur_;
long count=0;
// Sanity checks
if(head->prev)
{
head->prev=NULL;
}
_cur_=head;
while(_cur_ && count < 10000)
{
_cur_=_cur_->next;
count++;
}
if(_cur_)
{
head->prev=NULL; // painless breakpoint
}
}
#endif
// Now call anyone who has registered for a callback
for (UpdateCallBack *nextCall = updateCBlist; nextCall; nextCall = nextCall->next) {
nextCall->fn( nextCall->self, listNo, pos, transList );
}
}
void ObjectDisplayList::InsertionSortLink(DrawableObject **listhead, DrawableObject *listend)
{
DrawableObject *newlist;
DrawableObject *walk,*save;
newlist = listend;
walk=*listhead;
for(; walk != listend; walk=save)
{
DrawableObject **pnewlink;
for(pnewlink=&newlist;*pnewlink != listend && walk->distance <= (*pnewlink)->distance; pnewlink=&((*pnewlink)->next) );
save=walk->next;
walk->next=*pnewlink;
*pnewlink=walk;
}
*listhead=newlist;
}
void ObjectDisplayList::QuickSortLink(DrawableObject **head, DrawableObject *end)
{
int left_count, right_count, count;
DrawableObject **left_walk, *pivot, *old;
DrawableObject **right_walk, *right;
if(*head != end)
{
do
{
pivot=*head;
left_walk=head;
right_walk=&right;
left_count=right_count=0;
for(old=(*head)->next; old != end; old=old->next)
{
if(old->distance > pivot->distance)
{
left_count++;
*left_walk=old;
left_walk=&(old->next);
}
else
{
right_count++;
*right_walk=old;
right_walk=&(old->next);
}
}
*right_walk=end;
*left_walk=pivot;
pivot->next=right;
if(left_count > right_count)
{
if(right_count >= 9)
QuickSortLink(&(pivot->next),end);
else
InsertionSortLink(&(pivot->next),end);
end=pivot;
count=left_count;
}
else
{
if(left_count >= 9)
QuickSortLink(head,pivot);
else
InsertionSortLink(head,pivot);
head=&(pivot->next);
count=right_count;
}
}
while(count > 1);
}
}
#ifndef _USE_OLD_SORT_
/*****************************************************************************\
Sort the display list in far to near order. It is assumed that
the distances have already been computed through a call to
UpdateMetrics.
\*****************************************************************************/
void ObjectDisplayList::SortForViewpoint( void )
{
DrawableObject *_cur_;
#ifdef _SANITY_CHECK_
DrawableObject *_prev_;
long count=0;
#endif
// Quit now if we don't have at least one list entry
if ( !head ) return;
#ifdef _SANITY_CHECK_
// Sanity checks
if(head->prev)
{
head->prev=NULL;
}
_cur_=head;
while(_cur_ && count < 10000)
{
_cur_=_cur_->next;
count++;
}
if(_cur_)
{
head->prev=NULL; // painless breakpoint
}
#endif
QuickSortLink(&head, NULL);
if(head)
{
_cur_=head->next;
tail=head;
head->prev=NULL;
while(_cur_)
{
_cur_->prev=tail;
tail=_cur_;
_cur_=_cur_->next;
}
#ifdef _SANITY_CHECK_
if(_cur_)
{
head->prev=NULL; // painless breakpoint
}
#endif
}
#ifdef _SANITY_CHECK_
// Sanity checks
if(head->prev)
{
head->prev=NULL;
}
_cur_=head;
count=0;
while(_cur_ && count < 10000)
{
_cur_=_cur_->next;
count++;
}
if(_cur_)
{
head->prev=NULL; // painless breakpoint
}
#endif
// Now call anyone who has registered for a callback
for (SortCallBack *nextCall = sortCBlist; nextCall; nextCall = nextCall->next) {
nextCall->fn( nextCall->self );
}
}
#endif
#ifdef _USE_OLD_SORT_ // replacing this routine
/*****************************************************************************\
Sort the display list in far to near order. It is assumed that
the distances have already been computed through a call to
UpdateMetrics.
\*****************************************************************************/
void ObjectDisplayList::SortForViewpoint( void )
{
DrawableObject *p;
DrawableObject *q;
// Quit now if we don't have at least one list entry
if ( !head ) return;
// Now sort the list laterally from far to near
for (p = head->next; p!=NULL; p=p->next) {
// Decide where to place this element in the list
q = p;
while ((q->prev) && (q->prev->distance < p->distance)) // JB 010306 CTD
//while ((q->prev) && (!F4IsBadReadPtr(q->prev, sizeof(DrawableObject))) && (q->prev->distance < p->distance)) // JB 010306 CTD (too much CPU)
{
q = q->prev;
}
// Only adjust the list if we need to
if ( q != p )
{
// Remove the element under consideration (p) from its current location
if (p->prev)
{
p->prev->next = p->next;
}
else
{
head = p->next;
}
if (p->next)
{
p->next->prev = p->prev;
}
else
{
tail = p->prev;
}
// Insert the element under consideration in front of the identified element
p->next = q;
p->prev = q->prev;
if (q->prev)
{
q->prev->next = p;
}
else
{
head = p;
}
q->prev = p;
}
}
// Now call anyone who has registered for a callback
for (SortCallBack *nextCall = sortCBlist; nextCall; nextCall = nextCall->next) {
nextCall->fn( nextCall->self );
}
}
#endif
// This function just preloads all objects in the List withing a range
// it exits when the list of ojects is fully loaded
void ObjectDisplayList::PreLoad(class RenderOTW *renderer)
{
// for each object in list
while(nextToDraw )
{
// do the object
nextToDraw->Draw(renderer, -1);
nextToDraw = nextToDraw->next;
}
}
/*****************************************************************************\
Draw all the objects in the display list which lie beyond the given ring
Returns TRUE if any objects were actually drawn, FALSE otherwise.
\*****************************************************************************/
void ObjectDisplayList::DrawBeyond(float ringDistance, int LOD, class RenderOTW *renderer)
{
//START_PROFILE("-->DRAW LIST");
while(nextToDraw && (nextToDraw->distance >= ringDistance))
{
//COUNT_PROFILE("DRAW OBJECTS");
// setup the object remove as false
KillTheObject=RemoveTheObject=false;
// do the object
nextToDraw->Draw(renderer,LOD);
// List self management... if an object requests to be killed
if(RemoveTheObject){
// keep the new item to draw
DrawableObject *LastDrawn=nextToDraw->next;
// remove the actual from list
RemoveObject(nextToDraw);
// if requests a deallocation, do it
if(KillTheObject) delete nextToDraw;
// get the pointer back
nextToDraw=LastDrawn;
}
else {
nextToDraw = nextToDraw->next;
}
}
//STOP_PROFILE("-->DRAW LIST");
}
/*****************************************************************************\
Draw all the objects in the display list which lie beyond the given ring
Returns TRUE if any objects were actually drawn, FALSE otherwise.
\*****************************************************************************/
void ObjectDisplayList::DrawBeyond(float ringDistance, class Render3D *renderer)
{
while(nextToDraw && (nextToDraw->distance >= ringDistance))
{
nextToDraw->Draw(renderer);
nextToDraw = nextToDraw->next;
}
}
/*****************************************************************************\
Add a pair of functions to be called at UpdateMetrics and SortForViewpoint
time.
\*****************************************************************************/
void ObjectDisplayList::InsertUpdateCallbacks( UpdateCallBack *up, SortCallBack *sort, void *self )
{
ShiAssert( up );
ShiAssert( sort );
ShiAssert( self );
up->prev = NULL;
up->next = updateCBlist;
updateCBlist = up;
sort->prev = NULL;
sort->next = sortCBlist;
sortCBlist = sort;
if (updateCBlist->next) {
ShiAssert( sortCBlist->next );
updateCBlist->next->prev = updateCBlist;
sortCBlist->next->prev = sortCBlist;
}
}
/*****************************************************************************\
Remove a pair of functions to be called at UpdateMetrics and
SortForViewpoint time.
\*****************************************************************************/
void ObjectDisplayList::RemoveUpdateCallbacks( UpdateCallBack *up, SortCallBack *sort, void *self )
{
ShiAssert( up );
ShiAssert( sort );
ShiAssert( self );
if (up->prev) {
ShiAssert(sort->prev);
up->prev->next = up->next;
sort->prev->next = sort->next;
} else {
ShiAssert(up == updateCBlist);
ShiAssert(sort == sortCBlist);
updateCBlist = up->next;
sortCBlist = sort->next;
}
if (up->next) {
ShiAssert(sort->next);
up->next->prev = up->prev;
sort->next->prev = sort->prev;
}
}
| 24.193893 | 144 | 0.578217 | [
"object"
] |
cdb7cbf07305b215d74c5ec13f661050b66d21d5 | 5,434 | cpp | C++ | src/tensors/cpu/sharp/int_gemm.cpp | hieuhoang/marian-dev | f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2 | [
"MIT"
] | 4 | 2020-04-29T05:07:48.000Z | 2020-12-21T04:31:53.000Z | src/tensors/cpu/sharp/int_gemm.cpp | hieuhoang/marian-dev | f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2 | [
"MIT"
] | 2 | 2020-10-21T23:38:48.000Z | 2021-03-25T05:40:35.000Z | src/tensors/cpu/sharp/int_gemm.cpp | hieuhoang/marian-dev | f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2 | [
"MIT"
] | 5 | 2020-06-05T13:10:40.000Z | 2021-01-19T07:37:23.000Z | #include "int_gemm.h"
#include "tensors/tensor_allocator.h"
#include "tensors/tensor_operators.h"
#include <emmintrin.h>
#include <immintrin.h>
#include <tmmintrin.h>
#include <xmmintrin.h>
#include <cassert>
#include <cstddef>
namespace marian {
namespace cpu {
namespace int16 {
#ifdef __AVX512F__
void AVX_Quantize16(const float* input,
int16_t* output,
float quant_mult,
std::size_t size);
void AVX_Quantize8(const float* input,
int8_t* output,
float quant_mult,
std::size_t size);
void AVX_MatrixMult16(const __m512i* A,
const __m512i* B,
float* C,
float unquant_mult,
int num_A_rows,
int num_B_rows,
int width);
void AVX_MatrixMult8(const __m512i* A,
const __m512i* B,
float* C,
float unquant_mult,
int num_A_rows,
int num_B_rows,
int width);
#endif
void SSE_Quantize16(const float* input,
__m128i* output,
float quant_mult,
int num_rows,
int width);
void SSE_MatrixMult16(const __m128i* A,
const __m128i* B,
float* C,
float unquant_mult,
int num_A_rows,
int num_B_rows,
int width);
void Quantize16(marian::Tensor out,
const marian::Tensor in,
float /*clipValue*/) {
float quant_mult = (float)pow(2.0, BITS);
#ifdef __AVX512F__
AVX_Quantize16(
in->data(), out->data<int16_t>(), quant_mult, in->shape().elements());
#else
int num_rows = in->shape().elements() / in->shape()[-1];
int width = in->shape()[-1];
SSE_Quantize16(in->data(), out->data<__m128i>(), quant_mult, num_rows, width);
#endif
}
void Quantize8(marian::Tensor out,
const marian::Tensor in,
float clipValue) {
#ifdef __AVX512F__
float quant_mult = 127.0f / clipValue;
AVX_Quantize8(
in->data(), out->data<int8_t>(), quant_mult, in->shape().elements());
#else
out; in; clipValue;
ABORT("8-bit is currently only AVX512");
#endif
}
// This operates on floats after processing so doesn't care about int8_t vs
// int16_t.
void AddBias(marian::Tensor C, const marian::Tensor Bias) {
float* y = C->data();
const float* x = C->data();
const float* bias = Bias->data();
const int m = C->shape().elements() / C->shape()[-1];
const int n = C->shape()[-1];
for(int j = 0; j < m; ++j) {
int i = 0;
#ifdef __AVX512F__
int n16 = n & ~15;
for(; i < n16; i += 16) {
__m512 ai = _mm512_loadu_ps(x + j * n + i);
__m512 bi = _mm512_loadu_ps(bias + i);
__m512 yi = _mm512_add_ps(ai, bi);
_mm512_storeu_ps(y + j * n + i, yi);
}
#else
int n4 = (n / 4) * 4;
for(; i < n4; i += 4) {
__m128 ai = _mm_loadu_ps(x + j * n + i);
__m128 bi = _mm_loadu_ps(bias + i);
__m128 yi = _mm_add_ps(ai, bi);
_mm_storeu_ps(y + j * n + i, yi);
}
#endif
for(; i < n; i++) {
y[j * n + i] = x[j * n + i] + bias[i];
}
}
}
void ProdInt16(marian::Tensor C,
const marian::Tensor A,
const marian::Tensor B,
float scale) {
ABORT_IF(scale != 1, "Scale other than 1 not supported");
// @TODO: make this a parameter
float quant_mult = (float)pow(2.0, BITS);
// If we quantize to n bits and then multiple the values together, the result
// will be quantized to n^2 bits. So we must divide by 1.0/(n^2) to get back
// the original value.
float unquant_mult = 1.0f / (quant_mult * quant_mult);
float* fC = C->data();
int num_A_rows = A->shape().elements() / A->shape()[-1];
int num_B_rows = B->shape().elements() / B->shape()[-1];
int width = B->shape()[-1];
#ifdef __AVX512F__
AVX_MatrixMult16(A->data<__m512i>(),
B->data<__m512i>(),
fC,
unquant_mult,
num_A_rows,
num_B_rows,
width);
#else
SSE_MatrixMult16(A->data<__m128i>(),
B->data<__m128i>(),
fC,
unquant_mult,
num_A_rows,
num_B_rows,
width);
#endif
}
void ProdInt8(marian::Tensor C,
const marian::Tensor A,
const marian::Tensor B,
float scale,
float clipValue) {
#ifdef __AVX512F__
// This would be easy...
ABORT_IF(scale != 1, "Scale other than 1 not supported");
float quant_mult = 127.0f / clipValue;
float unquant_mult = 1.0f / (quant_mult * quant_mult);
float* fC = C->data();
int num_A_rows = A->shape().elements() / A->shape()[-1];
int num_B_rows = B->shape().elements() / B->shape()[-1];
int width = B->shape()[-1];
AVX_MatrixMult8(A->data<__m512i>(),
B->data<__m512i>(),
fC,
unquant_mult,
num_A_rows,
num_B_rows,
width);
#else
C; A; B; scale; clipValue;
ABORT("8-bit is currently only AVX512");
#endif
}
} // namespace int16
} // namespace cpu
} // namespace marian
| 28.904255 | 80 | 0.527788 | [
"shape"
] |
cdb8cd000821074a11b627bf26102fd41f248824 | 831 | cpp | C++ | LeetCode/Problems/0049_Group_Anagrams/group_anagrams.cpp | jocodoma/coding-interview-prep | f7f06be0bc5687c376b753ba3fa46b07412eeb80 | [
"MIT"
] | null | null | null | LeetCode/Problems/0049_Group_Anagrams/group_anagrams.cpp | jocodoma/coding-interview-prep | f7f06be0bc5687c376b753ba3fa46b07412eeb80 | [
"MIT"
] | null | null | null | LeetCode/Problems/0049_Group_Anagrams/group_anagrams.cpp | jocodoma/coding-interview-prep | f7f06be0bc5687c376b753ba3fa46b07412eeb80 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
return sortedStringHashMap(strs);
}
// time complexity: O(nklogk), where n is the length of arrary and k is the maximum length of string
// space complexity: O(nk)
vector<vector<string>> sortedStringHashMap(vector<string>& strs){
if(strs.empty()) return {{}};
unordered_map<std::string, std::vector<std::string>> map;
for(const auto& str : strs){
std::string sortedStr = str;
std::sort(sortedStr.begin(), sortedStr.end()); // O(klogk)
map[sortedStr].push_back(str);
}
std::vector<std::vector<std::string>> anagrams;
for(const auto& it : map){
anagrams.push_back(it.second);
}
return anagrams;
}
};
| 33.24 | 104 | 0.596871 | [
"vector"
] |
cdbb5bd9cb82f589255eff5eab7d7596cdd30be5 | 2,250 | cpp | C++ | xiablo/Plugins/SketchFabPlugin/Source/SketchfabGLTF/Private/GLTFPrimResolver.cpp | jing-interactive/ucd | 8fc8722291f086a0c0037a94d11c14562375e862 | [
"MIT"
] | 1 | 2022-02-02T23:36:07.000Z | 2022-02-02T23:36:07.000Z | xiablo/Plugins/SketchFabPlugin/Source/SketchfabGLTF/Private/GLTFPrimResolver.cpp | jing-interactive/ucd | 8fc8722291f086a0c0037a94d11c14562375e862 | [
"MIT"
] | null | null | null | xiablo/Plugins/SketchFabPlugin/Source/SketchfabGLTF/Private/GLTFPrimResolver.cpp | jing-interactive/ucd | 8fc8722291f086a0c0037a94d11c14562375e862 | [
"MIT"
] | null | null | null | // Copyright 2018 Sketchfab, Inc. All Rights Reserved.
#include "SKGLTFPrimResolver.h"
#include "SKGLTFImporter.h"
#include "SKGLTFConversionUtils.h"
#include "AssetData.h"
#include "Modules/ModuleManager.h"
#include "AssetRegistryModule.h"
#include "AssetSelection.h"
#include "IGLTFImporterModule.h"
#include "ObjectTools.h"
#include "PackageTools.h"
#include "ActorFactories/ActorFactory.h"
#define LOCTEXT_NAMESPACE "GLTFImportPlugin"
void USKGLTFPrimResolver::Init()
{
AssetRegistry = &FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry")).Get();
}
void USKGLTFPrimResolver::FindPrimsToImport(FGLTFImportContext& ImportContext, TArray<FGLTFPrimToImport>& OutPrimsToImport)
{
if (ImportContext.Model->scenes.size() == 0)
return;
FMatrix scaleMat = FScaleMatrix(FVector(-100, 100, 100)); //Scale everything up and flip in the X axis
auto &sceneNodes = ImportContext.Model->scenes[0].nodes;
auto &nodes = ImportContext.Model->nodes;
for (int32 i = 0; i < sceneNodes.size(); i++)
{
FindPrimsToImport_Recursive(ImportContext, &nodes[sceneNodes[i]], OutPrimsToImport, scaleMat);
}
}
void USKGLTFPrimResolver::FindPrimsToImport_Recursive(FGLTFImportContext& ImportContext, tinygltf::Node* Prim, TArray<FGLTFPrimToImport>& OutTopLevelPrims, FMatrix ParentMat)
{
const FString PrimName = GLTFToUnreal::ConvertString(Prim->name);
FMatrix local = GLTFToUnreal::ConvertMatrix(*Prim);
ParentMat = local * ParentMat;
if (Prim->mesh >= 0 && Prim->mesh < ImportContext.Model->meshes.size())
{
FGLTFPrimToImport NewPrim;
NewPrim.NumLODs = 0;
NewPrim.Prim = Prim;
NewPrim.LocalPrimTransform = local;
NewPrim.WorldPrimTransform = ParentMat;
OutTopLevelPrims.Add(NewPrim);
}
int32 NumChildren = Prim->children.size();
for (int32 ChildIdx = 0; ChildIdx < NumChildren; ++ChildIdx)
{
int nodeIdx = Prim->children[ChildIdx];
if (nodeIdx >= 0 && nodeIdx < ImportContext.Model->nodes.size())
{
FindPrimsToImport_Recursive(ImportContext, &ImportContext.Model->nodes[nodeIdx], OutTopLevelPrims, ParentMat);
}
}
}
bool USKGLTFPrimResolver::IsValidPathForImporting(const FString& TestPath) const
{
return FPackageName::GetPackageMountPoint(TestPath) != NAME_None;
}
#undef LOCTEXT_NAMESPACE | 31.25 | 174 | 0.765333 | [
"mesh",
"model"
] |
02cbe67693c5beea93c134bb0161dea1b51112a6 | 5,882 | cc | C++ | Code/Components/Analysis/analysis/current/polarisation/StokesSpectrum.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 1 | 2020-06-18T08:37:43.000Z | 2020-06-18T08:37:43.000Z | Code/Components/Analysis/analysis/current/polarisation/StokesSpectrum.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | Code/Components/Analysis/analysis/current/polarisation/StokesSpectrum.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | /// @file
///
/// XXX Notes on program XXX
///
/// @copyright (c) 2014 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Matthew Whiting <Matthew.Whiting@csiro.au>
///
#include <polarisation/StokesSpectrum.h>
#include <askap_analysis.h>
#include <sourcefitting/RadioSource.h>
#include <catalogues/CasdaComponent.h>
#include <extraction/SourceSpectrumExtractor.h>
#include <extraction/NoiseSpectrumExtractor.h>
#include <utils/PolConverter.h>
#include <Common/ParameterSet.h>
#include <Common/KVpair.h>
using namespace LOFAR::TYPES;
#include <casacore/casa/Arrays/Vector.h>
#include <casacore/casa/Arrays/ArrayMath.h>
#include <casacore/casa/Arrays/ArrayLogical.h>
#include <casacore/measures/Measures/Stokes.h>
///@brief Where the log messages go.
ASKAP_LOGGER(logger, ".stokesspectrum");
namespace askap {
namespace analysis {
StokesSpectrum::StokesSpectrum(const LOFAR::ParameterSet &parset,
std::string pol):
itsParset(parset), itsPol(pol)
{
itsCubeName = parset.getString("cube", "");
ASKAPCHECK(itsCubeName != "", "No cube name given");
itsOutputBase = parset.getString("outputBase", "");
// ASKAPCHECK(itsOutputBase != "", "No output name given");
itsBeamLog = parset.getString("beamLog", "");
std::stringstream outputbase;
std::string objid = itsParset.getString("objid","");
std::string objectname = itsParset.getString("objectname","");
// Define the parset used to set up the source extractor
LOFAR::ParameterSet specParset;
specParset.add(LOFAR::KVpair("spectralCube", itsCubeName));
outputbase << itsOutputBase << "_spec_" << itsPol;
specParset.add(LOFAR::KVpair("spectralOutputBase", outputbase.str()));
specParset.add(LOFAR::KVpair("spectralBoxWidth",
itsParset.getInt("boxwidth", 5)));
specParset.add(LOFAR::KVpair("polarisation", itsPol));
specParset.add(LOFAR::KVpair("useDetectedPixels", false));
specParset.add(LOFAR::KVpair("scaleSpectraByBeam", true));
specParset.add(LOFAR::KVpair("beamLog", itsBeamLog));
specParset.add("imagetype",itsParset.getString("imagetype","fits"));
if (itsParset.isDefined("imageHistory")){
specParset.add("imageHistory", itsParset.getString("imageHistory"));
}
itsSpecExtractor = boost::shared_ptr<SourceSpectrumExtractor>(new SourceSpectrumExtractor(specParset));
itsSpecExtractor->setObjectIDs(objid,objectname);
// Define the parset used to set up the noise extractor
LOFAR::ParameterSet noiseParset;
noiseParset.add(LOFAR::KVpair("spectralCube", itsCubeName));
outputbase.str("");
outputbase << itsOutputBase << "_noise_" << itsPol;
noiseParset.add(LOFAR::KVpair("spectralOutputBase", outputbase.str()));
noiseParset.add(LOFAR::KVpair("noiseArea",
itsParset.getFloat("noiseArea", 50.)));
noiseParset.add(LOFAR::KVpair("robust",
itsParset.getBool("robust", true)));
noiseParset.add(LOFAR::KVpair("polarisation", itsPol));
noiseParset.add(LOFAR::KVpair("useDetectedPixels", false));
noiseParset.add(LOFAR::KVpair("scaleSpectraByBeam", true));
noiseParset.add("imagetype",itsParset.getString("imagetype","fits"));
if (itsParset.isDefined("imageHistory")){
noiseParset.add("imageHistory", itsParset.getString("imageHistory"));
}
itsNoiseExtractor = boost::shared_ptr<NoiseSpectrumExtractor>(new NoiseSpectrumExtractor(noiseParset));
itsNoiseExtractor->setObjectIDs(objid,objectname);
}
void StokesSpectrum::extract()
{
extractSpectrum();
extractNoise();
}
void StokesSpectrum::extractSpectrum()
{
itsSpecExtractor->setSource(itsComponent);
itsSpecExtractor->extract();
itsSpectrum = casa::Vector<float>(itsSpecExtractor->array());
// itsMedianValue = casa::median(itsSpectrum(!isNaN(itsSpectrum)).getArray());
std::vector<float> vec;
for(size_t i=0;i<itsSpectrum.size();i++){
if (!isNaN(itsSpectrum[i]) && !isInf(itsSpectrum[i])){
vec.push_back(i);
}
}
casa::Vector<float> newvec(vec);
itsMedianValue = casa::median(newvec);
itsFrequencies = itsSpecExtractor->frequencies();
}
void StokesSpectrum::extractNoise()
{
itsNoiseExtractor->setSource(itsComponent);
itsNoiseExtractor->extract();
itsNoiseSpectrum = casa::Vector<float>(itsNoiseExtractor->array());
//itsMedianNoise = casa::median(itsNoiseSpectrum(!isNaN(itsNoiseSpectrum)).getArray());
std::vector<float> vec = itsNoiseSpectrum.tovector();
for(std::vector<float>::iterator i=vec.begin();i<vec.end();i++){
if (isNaN(*i)){
vec.erase(i);
}
}
casa::Vector<float> newvec(vec);
itsMedianNoise = casa::median(newvec);
}
void StokesSpectrum::write()
{
itsSpecExtractor->writeImage();
itsNoiseExtractor->writeImage();
}
}
}
| 34.6 | 107 | 0.696192 | [
"vector"
] |
02ccc3ced81715a89d5f5379ebe46f64133d1126 | 2,830 | cpp | C++ | Source/Basic/Renderer.cpp | IppClub/Dorothy-SSR | 2fb74673e76e5cef0218788757ce2de3c588ed33 | [
"MIT"
] | 57 | 2016-12-08T07:29:44.000Z | 2019-12-25T13:15:50.000Z | Source/Basic/Renderer.cpp | IppClub/Dorothy-SSR | 2fb74673e76e5cef0218788757ce2de3c588ed33 | [
"MIT"
] | 3 | 2018-06-07T06:31:39.000Z | 2019-10-04T07:16:15.000Z | Source/Basic/Renderer.cpp | IppClub/Dorothy-SSR | 2fb74673e76e5cef0218788757ce2de3c588ed33 | [
"MIT"
] | 16 | 2016-12-08T07:39:15.000Z | 2020-01-03T06:54:25.000Z | /* Copyright (c) 2022 Jin Li, dragon-fly@qq.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include "Const/Header.h"
#include "Basic/Renderer.h"
#include "Node/Node.h"
NS_DOROTHY_BEGIN
void Renderer::render()
{
uint32_t stencilState = SharedRendererManager.getCurrentStencilState();
if (stencilState != BGFX_STENCIL_NONE)
{
bgfx::setStencil(stencilState);
}
}
RendererManager::RendererManager():
_currentRenderer(nullptr)
{ }
void RendererManager::setCurrent(Renderer* var)
{
if (_currentRenderer && _currentRenderer != var)
{
_currentRenderer->render();
}
_currentRenderer = var;
}
Renderer* RendererManager::getCurrent() const
{
return _currentRenderer;
}
uint32_t RendererManager::getCurrentStencilState() const
{
return _stencilStates.empty() ? BGFX_STENCIL_NONE : _stencilStates.top();
}
void RendererManager::flush()
{
if (_currentRenderer)
{
_currentRenderer->render();
_currentRenderer = nullptr;
}
}
void RendererManager::pushStencilState(uint32_t stencilState)
{
_stencilStates.push(stencilState);
}
void RendererManager::popStencilState()
{
_stencilStates.pop();
}
bool RendererManager::isGrouping() const
{
return !_renderGroups.empty();
}
void RendererManager::pushGroupItem(Node* item)
{
std::vector<Node*>* renderGroup = _renderGroups.top().get();
renderGroup->push_back(item);
}
void RendererManager::pushGroup(uint32_t capacity)
{
_renderGroups.push(New<std::vector<Node*>>());
_renderGroups.top()->reserve(s_cast<size_t>(capacity));
}
void RendererManager::popGroup()
{
std::vector<Node*>* renderGroup = _renderGroups.top().get();
std::stable_sort(renderGroup->begin(), renderGroup->end(), [](Node* nodeA, Node* nodeB)
{
return nodeA->getRenderOrder() < nodeB->getRenderOrder();
});
for (Node* node : *renderGroup)
{
node->render();
}
_renderGroups.pop();
}
NS_DOROTHY_END
| 28.877551 | 463 | 0.761484 | [
"render",
"vector"
] |
02cf395b3030e0b7a0c0a7aa862f67d5e52bda1d | 2,401 | cpp | C++ | src/tools.cpp | jnsagai/extended_kalman_filter | 6a50d86c0539c54c743278d2478de8fcfa8a5dec | [
"MIT"
] | null | null | null | src/tools.cpp | jnsagai/extended_kalman_filter | 6a50d86c0539c54c743278d2478de8fcfa8a5dec | [
"MIT"
] | null | null | null | src/tools.cpp | jnsagai/extended_kalman_filter | 6a50d86c0539c54c743278d2478de8fcfa8a5dec | [
"MIT"
] | null | null | null | #include "tools.h"
#include <iostream>
#include <cmath>
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
/**
* Calculate the RMSE here.
*/
// Create a local vector to calculate and return the rmse
VectorXd rmse(4);
rmse << 0, 0, 0, 0;
// The estimation vector size should not be zero
if (estimations.size() <= 0)
{
std::cout << "CalculareRMSE - Error - Estimation vector size is zero" << std::endl;
}
// The estimation vector size should equal ground truth vector size
else if (estimations.size() != ground_truth.size())
{
std::cout << "CalculareRMSE - Error - Estimation vector size is different from ground truth vector size" << std::endl;
}
else
{
VectorXd acc_res(4); // Accumulated squared residuals
VectorXd mean_res(4); // Residuals mean
VectorXd residual(4); // Residual
acc_res << 0, 0, 0, 0;
mean_res << 0, 0, 0, 0;
residual << 0, 0, 0, 0;
// Calculate the accumulate squared residuals
for (unsigned int i = 0; i < estimations.size(); ++i)
{
residual = estimations[i] - ground_truth[i];
residual = residual.array() * residual.array();
acc_res += residual;
}
// Calculate the mean
mean_res = acc_res.array() / estimations.size();
// Calculate the squared root
rmse = mean_res.array().sqrt();
}
// return the result
return rmse;
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
/**
* Calculate a Jacobian here.
*/
// Create the Jacobian Matrix to be returned
MatrixXd Hj(3, 4);
// Recover the state parameters
double px = x_state(0);
double py = x_state(1);
double vx = x_state(2);
double vy = x_state(3);
// Preprocess somve values
double c1 = px*px+py*py;
double c2 = sqrt(c1);
double c3 = (c1*c2);
// Safe check for division by zero
Hj = MatrixXd::Zero(3, 4);
if (fabs(c1) < 0.0001)
{
std::cout << "CalculateJacobian - Error - Division by Zero" << std::endl;
}
else
{
//compute the Jacobian matrix
Hj << (px/c2), (py/c2), 0, 0,
-(py/c1), (px/c1), 0, 0,
py*(vx*py - vy*px)/c3, px*(px*vy - py*vx)/c3, px/c2, py/c2;
}
return Hj;
}
| 25.273684 | 123 | 0.605165 | [
"vector"
] |
02cf7a05cac290fad587d2cee928195fe7fbc180 | 763 | cpp | C++ | p3iv_types/test/test_scene_model.cpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | 4 | 2021-07-27T06:56:22.000Z | 2022-03-22T11:21:30.000Z | p3iv_types/test/test_scene_model.cpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | null | null | null | p3iv_types/test/test_scene_model.cpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | 1 | 2021-10-10T01:56:44.000Z | 2021-10-10T01:56:44.000Z | /*
* This file is part of the Interpolated Polyline (https://github.com/fzi-forschungszentrum-informatik/P3IV),
* copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)
*/
#include <numeric>
#include <vector>
#include "scene_model.hpp"
#include "gtest/gtest.h"
using namespace p3iv_types;
TEST(SceneModel, SceneModelDefaultCtor) {
int id = 0;
SceneModel sceneModel(id);
}
TEST(SceneModel, SceneModeAddSceneObject) {
int id = 0;
SceneModel sceneModel(id);
SceneObject sceneObject(5, 2.3, 3.7);
MotionState m{};
m.position.setMean(6.0, 8.0);
m.position.setCovariance(9.0, 0.0, 0.0, 16.0);
sceneObject.state = m;
sceneModel.addSceneObject(sceneObject);
} | 25.433333 | 119 | 0.712975 | [
"vector"
] |
02d22dc5eb81d463cbd4d242fcae850e53799e46 | 2,291 | cpp | C++ | Contests/USACO Solutions/2013-14/Jan 2014/14 Jan G1.cpp | wanglawrence9990/USACO | 45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2 | [
"CC0-1.0"
] | null | null | null | Contests/USACO Solutions/2013-14/Jan 2014/14 Jan G1.cpp | wanglawrence9990/USACO | 45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2 | [
"CC0-1.0"
] | null | null | null | Contests/USACO Solutions/2013-14/Jan 2014/14 Jan G1.cpp | wanglawrence9990/USACO | 45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2 | [
"CC0-1.0"
] | null | null | null | // #include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
using namespace std;
//using namespace __gnu_pbds;
typedef long long ll;
typedef vector<int> vi;
typedef pair<ll,ll> pi;
//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
#define FOR(i, a, b) for (int i=a; i<b; i++)
#define F0R(i, a) for (int i=0; i<a; i++)
#define FORd(i,a,b) for (int i = (b)-1; i >= a; i--)
#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)
#define mp make_pair
#define pb push_back
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound
const int MOD = 1000000007;
ifstream cin ("curling.in");
ofstream cout ("curling.out");
vector<pi> lo, hi, a, b;
int N, a1, b1, cur1, cur2;
ll cross(pi O, pi A, pi B) {
return (A.f - O.f) * (B.s - O.s) - (A.s - O.s) * (B.f - O.f);
}
void convex_hull(vector<pi> P) { // correct
int n = P.size(), k = 0;
cur1 = 0, cur2 = 0;
vector<pi> H(2*n);
//lower
F0R(i,n) {
while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
int k1 = k;
// upper
for (int i = n-2, t = k+1; i >= 0; i--) {
while (k >= t && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
lo.clear(); hi.clear();;
F0R(i,k1) lo.pb(H[i]);
FOR(i,k1-1,k) hi.pb(H[i]);
reverse(hi.begin(),hi.end());
}
bool above(pi z, pi a, pi b) {
if (a.f == b.f) {
if (z.s >= min(a.s,b.s)) return 1;
return 0;
}
if ((z.f-a.f)*b.s+(b.f-z.f)*a.s <= (b.f-a.f)*z.s) return 1;
return 0;
}
bool below(pi z, pi a, pi b) {
if (a.f == b.f) {
if (z.s <= max(a.s,b.s)) return 1;
return 0;
}
if ((z.f-a.f)*b.s+(b.f-z.f)*a.s >= (b.f-a.f)*z.s) return 1;
return 0;
}
bool in (pi z) {
if (z.f < lo[0].f || z.f > lo[lo.size()-1].f) return 0;
while (cur1 < lo.size()-2 && lo[cur1+1].f <= z.f) cur1++;
if (!above(z,lo[cur1],lo[cur1+1])) return 0;
while (cur2 < hi.size()-2 && hi[cur2+1].f <= z.f) cur2++;
if (!below(z,hi[cur2],hi[cur2+1])) return 0;
return 1;
}
int main() {
cin >> N; a.resize(N), b.resize(N);
F0R(i,N) cin >> a[i].f >> a[i].s;
F0R(i,N) cin >> b[i].f >> b[i].s;
sort(a.begin(),a.end());
sort(b.begin(),b.end());
convex_hull(a);
for (pi z: b) if (in(z)) a1 ++;
convex_hull(b);
for (pi z: a) if (in(z)) b1 ++;
cout << a1 << " " << b1; // 4114 4120
}
| 22.683168 | 98 | 0.542994 | [
"vector"
] |
02d96129082474cc8b0297ea1cbd8db0fe19beec | 87,211 | cpp | C++ | GetPot.cpp | HydrArgs/getpot-cpp | 3aaf25c1bc8858462ac8c8d0ab7fba547b9dbd7f | [
"MIT"
] | 1 | 2020-07-30T16:24:15.000Z | 2020-07-30T16:24:15.000Z | GetPot.cpp | HydrArgs/getpot-cpp | 3aaf25c1bc8858462ac8c8d0ab7fba547b9dbd7f | [
"MIT"
] | 2 | 2021-04-09T09:07:42.000Z | 2021-08-17T19:09:47.000Z | GetPot.cpp | HydrArgs/getpot-cpp | 3aaf25c1bc8858462ac8c8d0ab7fba547b9dbd7f | [
"MIT"
] | 1 | 2021-08-16T18:40:00.000Z | 2021-08-16T18:40:00.000Z | // SPDX license identifier: MIT; Project 'GetPot'
// MIT License
//
// Copyright (C) 2001-2016 Frank-Rene Schaefer.
//
// While not directly linked to license requirements, the author would like
// this software not to be used for military purposes.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//=============================================================================
#ifndef __INCLUDE_GUARD_GETPOT_CPP__
#define __INCLUDE_GUARD_GETPOT_CPP__
#if defined(WIN32) || defined(SOLARIS_RAW) || (__GNUC__ == 2) || defined(__HP_aCC)
// WINDOWS or SOLARIS or gcc 2.* or HP aCC
# define GETPOT_STRTOK(a, b, c) strtok_r(a, b, c)
# define GETPOT_STRTOK_3_ARGS
#else
# define GETPOT_STRTOK(a, b, c) strtok(a, b)
#endif
#if defined(WIN32)
# define GETPOT_SNPRINTF(STR, SIZE, FORMAT_STR, ...) \
_snprintf(tmp, (size_t)SIZE, FORMAT_STR, __VA_ARGS__)
#else
# define GETPOT_SNPRINTF(STR, SIZE, FORMAT_STR, ...) \
snprintf(tmp, (int)SIZE, FORMAT_STR, __VA_ARGS__)
#endif
/* In case that a single header is intended, __GETPOT_INLINE is set to 'inline'
* otherwise, it is set to 'empty', so that normal object code is produced. */
#ifndef __GETPOT_INLINE
# define __GETPOT_INLINE /*empty*/
#endif
/* The default values for strings that represent 'true' and 'false' */
#include "GetPot.hpp"
#ifdef GETPOT_SETTING_NAMESPACE
namespace GETPOT_SETTING_NAMESPACE {
#endif
#define victorate(TYPE, VARIABLE, ITERATOR) \
for(std::vector<TYPE >::const_iterator ITERATOR = (VARIABLE).begin(); \
(ITERATOR) != (VARIABLE).end(); ++(ITERATOR))
template <class T> class TypeInfo;
template <> class TypeInfo<bool> {
public: static const char* name() { return "bool"; }
static bool default_value() { return false; }
typedef bool type;
static bool convert(bool& X) { return (bool)X; }
};
template <> class TypeInfo<const char*> {
public: static const char* name() { return "string"; }
static const char * default_value() { return ""; }
typedef const char* type;
static const char* convert(const char* X) { return (const char*)X; }
};
template <> class TypeInfo<int> {
public: static const char* name() { return "integer"; }
static int default_value() { return 0; }
typedef int type;
static int convert(int& X) { return (int)X; }
};
template <> class TypeInfo<std::string> : public TypeInfo<const char*>
{ public:
static const char* convert(std::string& X) { return (const char*)"inadmissible"; }
static std::string default_value() { return std::string(""); }
};
template <> class TypeInfo<unsigned int> : public TypeInfo<int>
{ public: static int convert(unsigned int& X) { return (int)X; } };
template <> class TypeInfo<char> : public TypeInfo<int>
{ public: static int convert(char& X) { return (int)X; } };
template <> class TypeInfo<unsigned char> : public TypeInfo<int>
{ public: static int convert(unsigned char& X) { return (int)X; } };
template <> class TypeInfo<short> : public TypeInfo<int>
{ public: static int convert(short& X) { return (int)X; } };
template <> class TypeInfo<unsigned short> : public TypeInfo<int>
{ public: static int convert(unsigned short& X) { return (int)X; } };
template <> class TypeInfo<long> : public TypeInfo<int>
{ public: static int convert(long& X) { return (int)X; } };
template <> class TypeInfo<unsigned long> : public TypeInfo<int>
{ public: static int convert(unsigned long& X) { return (int)X; } };
template <> class TypeInfo<double> {
public: static const char* name() { return "double"; }
static double default_value() { return 0.; }
typedef double type;
static double convert(double& X) { return (double)X; }
};
template <> class TypeInfo<float> : public TypeInfo<double>
{ public: static double convert(float& X) { return (double)X; } };
///////////////////////////////////////////////////////////////////////////////
// (*) constructors, destructor, assignment operator
//.............................................................................
//
__GETPOT_INLINE void
GetPot::__basic_initialization()
{
cursor = 0; nominus_cursor = -1;
search_failed_f = true; search_loop_f = true;
prefix = ""; section = "";
// automatic request recording for later ufo detection
__request_recording_f = true;
// comment start and end strings
_comment_start = std::string("#");
_comment_end = std::string("\n");
// default: separate vector elements by whitespaces
_field_separator = " \t\n";
// true and false strings
__split(GETPOT_SETTING_DEFAULT_TRUE_STRING_LIST, true_string_list);
__split(GETPOT_SETTING_DEFAULT_FALSE_STRING_LIST, false_string_list);
}
__GETPOT_INLINE
GetPot::GetPot():
built(false)
{
__basic_initialization();
STRING_VECTOR _apriori_argv;
_apriori_argv.push_back(std::string("Empty"));
__parse_argument_vector(_apriori_argv);
built = true;
}
__GETPOT_INLINE
GetPot::GetPot(const int argc_, char ** argv_,
const StringOrCharP FieldSeparator /* =0x0 */):
built(false)
// leave 'char**' non-const to honor less capable compilers ...
{
// TODO: Ponder over the problem when the argument list is of size = 0.
// This is 'sabotage', but it can still occur if the user specifies
// it himself.
assert(argc_ >= 1);
__basic_initialization();
// if specified -> overwrite default string
if( FieldSeparator.content.length() != 0 ) _field_separator = FieldSeparator.content;
// -- make an internal copy of the argument list:
STRING_VECTOR _apriori_argv;
// -- for the sake of clarity: we do want to include the first argument in the argument vector !
// it will not be a nominus argument, though. This gives us a minimun vector size of one
// which facilitates error checking in many functions. Also the user will be able to
// retrieve the name of his application by "get[0]"
_apriori_argv.push_back(std::string(argv_[0]));
int i=1;
for(; i<argc_; ++i) {
std::string tmp(argv_[i]); // recall the problem with temporaries,
_apriori_argv.push_back(tmp); // reference counting in arguement lists ...
}
__parse_argument_vector(_apriori_argv);
built = true;
}
__GETPOT_INLINE
GetPot::GetPot(StringOrCharP FileName,
const StringOrCharP CommentStart /* = 0x0 */,
const StringOrCharP CommentEnd /* = 0x0 */,
const StringOrCharP FieldSeparator/* = 0x0 */):
built(false)
{
__build(FileName.content, CommentStart.content, CommentEnd.content, FieldSeparator.content);
built = true;
}
__GETPOT_INLINE
GetPot::GetPot(const GetPot& That)
{ GetPot::operator=(That); }
__GETPOT_INLINE
GetPot::~GetPot()
{
// may be some return strings had to be created, delete now !
victorate(std::vector<char>*, __internal_string_container, it) {
delete *it;
}
}
__GETPOT_INLINE GetPot&
GetPot::operator=(const GetPot& That)
{
if (&That == this) return *this;
built = That.built;
filename = That.filename;
true_string_list = That.true_string_list;
false_string_list= That.false_string_list;
_comment_start = That._comment_start;
_comment_end = That._comment_end;
_field_separator= That. _field_separator;
argv = That.argv;
variables = That.variables;
prefix = That.prefix;
cursor = That.cursor;
nominus_cursor = That.nominus_cursor;
search_failed_f = That.search_failed_f;
idx_nominus = That.idx_nominus;
search_loop_f = That.search_loop_f;
return *this;
}
__GETPOT_INLINE void
GetPot::absorb(const GetPot& That)
{
if (&That == this) return;
STRING_VECTOR __tmp(That.argv);
__tmp.erase(__tmp.begin());
__parse_argument_vector(__tmp);
}
__GETPOT_INLINE void
GetPot::clear_requests()
{
_requested_arguments.erase(_requested_arguments.begin(), _requested_arguments.end());
_requested_variables.erase(_requested_variables.begin(), _requested_variables.end());
_requested_sections.erase(_requested_sections.begin(), _requested_sections.end());
}
__GETPOT_INLINE void
GetPot::__parse_argument_vector(const STRING_VECTOR& ARGV)
{
if( ARGV.size() == 0 ) return;
// build internal databases:
// 1) array with no-minus arguments (usually used as filenames)
// 2) variable assignments:
// 'variable name' '=' number | string
STRING_VECTOR section_stack;
STRING_VECTOR::const_iterator it = ARGV.begin();
section = "";
// -- do not parse the first argument, so that it is not interpreted a s a nominus or so.
argv.push_back(*it);
++it;
// -- loop over remaining arguments
unsigned i=1;
for(; it != ARGV.end(); ++it, ++i) {
std::string arg = *it;
if( arg.length() == 0 ) continue;
// -- [section] labels
if( arg.length() > 1 && arg[0] == '[' && arg[arg.length()-1] == ']' ) {
// (*) sections are considered 'requested arguments'
if( __request_recording_f ) _requested_arguments.push_back(arg);
const std::string Name = __DBE_expand_string(arg.substr(1, arg.length()-2));
section = __process_section_label(Name, section_stack);
// new section --> append to list of sections
if( find(section_list.begin(), section_list.end(), section) == section_list.end() )
if( section.length() != 0 ) section_list.push_back(section);
argv.push_back(arg);
}
else {
arg = section + __DBE_expand_string(arg);
argv.push_back(arg);
}
// -- separate array for nominus arguments
if( arg[0] != '-' ) idx_nominus.push_back(unsigned(i));
// -- variables: does arg contain a '=' operator ?
std::ptrdiff_t i = 0;
for(std::string::iterator it = arg.begin(); it != arg.end(); ++it, ++i) {
if( *it != '=' ) continue;
// (*) record for later ufo detection
// arguments carriying variables are always treated as 'requested' arguments.
// as a whole! That is 'x=4712' is considered a requested argument.
//
// unrequested variables have to be detected with the ufo-variable
// detection routine.
if( __request_recording_f ) _requested_arguments.push_back(arg);
const bool tmp = __request_recording_f;
__request_recording_f = false;
__set_variable(arg.substr(0, i), arg.substr(i+1));
__request_recording_f = tmp;
break;
}
}
}
__GETPOT_INLINE STRING_VECTOR
GetPot::__read_in_file(const std::string& FileName)
{
std::ifstream i(FileName.c_str());
if( ! i ) {
throw std::runtime_error(GETPOT_STR_FILE_NOT_FOUND(FileName));
return STRING_VECTOR();
}
// argv[0] == the filename of the file that was read in
return __read_in_stream(i);
}
__GETPOT_INLINE STRING_VECTOR
GetPot::__read_in_stream(std::istream& istr)
{
STRING_VECTOR brute_tokens;
while(istr) {
__skip_whitespace(istr);
const std::string Token = __get_next_token(istr);
if( Token.length() == 0 || Token[0] == EOF) break;
brute_tokens.push_back(Token);
}
// -- reduce expressions of token1'='token2 to a single
// string 'token1=token2'
// -- copy everything into 'argv'
// -- arguments preceded by something like '[' name ']' (section)
// produce a second copy of each argument with a prefix '[name]argument'
unsigned i1 = 0;
unsigned i2 = 1;
unsigned i3 = 2;
STRING_VECTOR arglist;
while( i1 < brute_tokens.size() ) {
const std::string& SRef = brute_tokens[i1];
// 1) concatinate 'abcdef' '=' 'efgasdef' to 'abcdef=efgasdef'
// note: java.lang.String: substring(a,b) = from a to b-1
// C++ string: substr(a,b) = from a to a + b
if( i2 < brute_tokens.size() && brute_tokens[i2] == "=" ) {
if( i3 >= brute_tokens.size() )
arglist.push_back(brute_tokens[i1] + brute_tokens[i2]);
else
arglist.push_back(brute_tokens[i1] + brute_tokens[i2] + brute_tokens[i3]);
i1 = i3+1; i2 = i3+2; i3 = i3+3;
continue;
}
else {
arglist.push_back(SRef);
i1=i2; i2=i3; i3++;
}
}
return arglist;
}
__GETPOT_INLINE void
GetPot::__skip_whitespace(std::istream& istr)
// find next non-whitespace while deleting comments
{
int tmp = istr.get();
do {
// -- search a non whitespace
while( isspace(tmp) ) {
tmp = istr.get();
if( ! istr ) return;
}
// -- look if characters match the comment starter string
unsigned i=0;
for(; i<_comment_start.length() ; ++i) {
if( tmp != _comment_start[i] ) {
// NOTE: Due to a 'strange behavior' in Microsoft's streaming lib we do
// a series of unget()s instead a quick seek. See
// http://sourceforge.net/tracker/index.php?func=detail&aid=1545239&group_id=31994&atid=403915
// for a detailed discussion.
// -- one step more backwards, since 'tmp' already at non-whitespace
do istr.unget(); while( i-- != 0 );
return;
}
tmp = istr.get();
if( ! istr ) { istr.unget(); return; }
}
// 'tmp' contains last character of _comment_starter
// -- comment starter found -> search for comment ender
unsigned match_no=0;
while(1+1 == 2) {
tmp = istr.get();
if( ! istr ) { istr.unget(); return; }
if( tmp == _comment_end[match_no] ) {
match_no++;
if( match_no == _comment_end.length() ) {
istr.unget();
break; // shuffle more whitespace, end of comment found
}
}
else
match_no = 0;
}
tmp = istr.get();
} while( istr );
istr.unget();
}
__GETPOT_INLINE const std::string
GetPot::__get_next_token(std::istream& istr)
// get next concatinates string token. consider quotes that embrace
// whitespaces
{
std::string token;
int tmp = 0;
int last_letter = 0;
while(1+1 == 2) {
last_letter = tmp; tmp = istr.get();
if( tmp == EOF
|| ((tmp == ' ' || tmp == '\t' || tmp == '\n') && last_letter != '\\') ) {
return token;
}
else if( tmp == '\'' && last_letter != '\\' ) {
// QUOTES: un-backslashed quotes => it's a string
token += __get_string(istr);
continue;
}
else if( tmp == '{' && last_letter == '$') {
token += '{' + __get_until_closing_bracket(istr);
continue;
}
else if( tmp == '$' && last_letter == '\\') {
token += tmp; tmp = 0; // so that last_letter will become = 0, not '$';
continue;
}
else if( tmp == '\\' && last_letter != '\\')
continue; // don't append un-backslashed backslashes
token += tmp;
}
}
__GETPOT_INLINE const std::string
GetPot::__get_string(std::istream& istr)
// parse input until next matching '
{
std::string str;
int tmp = 0;
int last_letter = 0;
while(1 + 1 == 2) {
last_letter = tmp; tmp = istr.get();
if( tmp == EOF) return str;
// un-backslashed quotes => it's the end of the string
else if( tmp == '\'' && last_letter != '\\') return str;
else if( tmp == '\\' && last_letter != '\\') continue; // don't append
str += tmp;
}
}
__GETPOT_INLINE const std::string
GetPot::__get_until_closing_bracket(std::istream& istr)
// parse input until next matching }
{
std::string str = "";
int tmp = 0;
int last_letter = 0;
int brackets = 1;
while(1 + 1 == 2) {
last_letter = tmp; tmp = istr.get();
if( tmp == EOF) return str;
else if( tmp == '{' && last_letter == '$') brackets += 1;
else if( tmp == '}') {
brackets -= 1;
// un-backslashed brackets => it's the end of the string
if( brackets == 0) return str + '}';
else if( tmp == '\\' && last_letter != '\\')
continue; // do not append an unbackslashed backslash
}
str += tmp;
}
}
__GETPOT_INLINE std::string
GetPot::__process_section_label(const std::string& Section,
STRING_VECTOR& section_stack)
{
std::string sname = Section;
// 1) subsection of actual section ('./' prefix)
if( sname.length() >= 2 && sname.substr(0, 2) == "./" ) {
sname = sname.substr(2);
}
// 2) subsection of parent section ('../' prefix)
else if( sname.length() >= 3 && sname.substr(0, 3) == "../" ) {
do {
if( section_stack.end() != section_stack.begin() )
section_stack.pop_back();
sname = sname.substr(3);
} while( sname.substr(0, 3) == "../" );
}
// 3) subsection of the root-section
else {
section_stack.erase(section_stack.begin(), section_stack.end());
// [] => back to root section
}
if( sname != "" ) {
// parse section name for 'slashes'
size_t i = 0;
size_t prev_slash_i = -1; // points to last slash
const size_t L = sname.length();
for(i = 0; i < L; ++i) {
if( sname[i] != '/' ) continue;
if( i - prev_slash_i > 1 ) {
const size_t Delta = i - (prev_slash_i + 1);
section_stack.push_back(sname.substr(prev_slash_i + 1, Delta));
}
prev_slash_i = i;
}
if( i - prev_slash_i > 1 ) {
const size_t Delta = i - (prev_slash_i + 1);
section_stack.push_back(sname.substr(prev_slash_i + 1, Delta));
}
}
std::string section = "";
if( section_stack.size() != 0 ) {
victorate(std::string, section_stack, it) {
section += *it + "/";
}
}
return section;
}
// convert string to BOOL, if not possible return Default
template <> __GETPOT_INLINE bool
GetPot::__convert_to_type<bool>(const std::string& String, bool Default,
bool ThrowExceptionF /* = GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT */) const
{
// No 'lower' or 'upper' unification. If someone wants that, he
// han specify the true-string or fals-strings as he likes.
victorate(std::string, true_string_list, it1) {
if( String == *it1 ) return true;
}
victorate(std::string, false_string_list, it2) {
if( String == *it2 ) return false;
}
if( ThrowExceptionF ) {
throw std::runtime_error(std::string(GETPOT_STR_FILE) + " \"" + filename + "\": " +
GETPOT_STR_CANNOT_CONVERT_TO(String, TypeInfo<bool>::name()));
}
else
return Default;
}
// convert string to DOUBLE, if not possible return Default
template <> __GETPOT_INLINE double
GetPot::__convert_to_type<double>(const std::string& String, double Default,
bool ThrowExceptionF /* = GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT */) const
{
double tmp;
if( sscanf(String.c_str(),"%lf", &tmp) == 1 ) return tmp;
if( ThrowExceptionF )
throw std::runtime_error(std::string(GETPOT_STR_FILE) + " \"" + filename + "\": " +
GETPOT_STR_CANNOT_CONVERT_TO(String, TypeInfo<double>::name()));
else
return Default;
}
// convert string to INT, if not possible return Default
template <> __GETPOT_INLINE int
GetPot::__convert_to_type<int>(const std::string& String, int Default,
bool ThrowExceptionF /* = GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT */) const
{
// NOTE: intermediate results may be floating points, so that the string
// may look like 2.0e1 (i.e. float format) => use float conversion
// in any case.
return (int)__convert_to_type(String, (double)Default, ThrowExceptionF);
}
// convert string to string, so that GetPot::read method can be generic (template).
template <> __GETPOT_INLINE const char*
GetPot::__convert_to_type<const char*>(const std::string& String, const char* Default,
bool ThrowExceptionF /* = GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT */) const
{
return __get_const_char(String);
}
__GETPOT_INLINE const char*
GetPot::__get_const_char(const std::string& String) const
{
std::vector<char>* c_str_copy = new std::vector<char>(String.length() + 1, '\0');
std::copy(String.begin(), String.end(), c_str_copy->begin());
((GetPot*)this)->__internal_string_container.push_back(c_str_copy);
return &(*c_str_copy)[0];
}
//////////////////////////////////////////////////////////////////////////////
// (*) cursor oriented functions
//.............................................................................
__GETPOT_INLINE const std::string
GetPot::__get_remaining_string(const std::string& String, const std::string& Start) const
// Checks if 'String' begins with 'Start' and returns the remaining String.
// Returns None if String does not begin with Start.
{
if( Start == "" ) return String;
// note: java.lang.String: substring(a,b) = from a to b-1
// C++ string: substr(a,b) = from a to a + b
if( String.find(Start) == 0 ) return String.substr(Start.length());
else return "";
}
// -- search for a certain argument and set cursor to position
__GETPOT_INLINE bool
GetPot::search(const char* Option)
{
unsigned OldCursor = cursor;
std::string search_term;
if( ! Option ) return false;
search_term = prefix + Option;
// (*) record requested arguments for later ufo detection
__record_argument_request(search_term);
if( OldCursor >= argv.size() ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
search_failed_f = true;
// (*) first loop from cursor position until end
unsigned c = cursor;
for(; c < argv.size(); c++) {
if( argv[c] == search_term )
{ cursor = c; search_failed_f = false; return true; }
}
if( ! search_loop_f ) return false;
// (*) second loop from 0 to old cursor position
for(c = 1; c < OldCursor; c++) {
if( argv[c] == search_term )
{ cursor = c; search_failed_f = false; return true; }
}
// in case nothing is found the cursor stays where it was
return false;
}
__GETPOT_INLINE bool
GetPot::search(unsigned No, const char* P, ...)
{
// (*) recording the requested arguments happens in subroutine 'search'
if( No == 0 ) return false;
// search for the first argument
if( search(P) == true ) return true;
// start interpreting variable argument list
va_list ap;
va_start(ap, P);
unsigned i = 1;
for(; i < No; ++i) {
char* Opt = va_arg(ap, char *);
if( search(Opt) == true ) break;
}
if( i < No ) {
++i;
// loop was left before end of array --> hit but
// make sure that the rest of the search terms is marked
// as requested.
for(; i < No; ++i) {
char* Opt = va_arg(ap, char *);
// (*) record requested arguments for later ufo detection
__record_argument_request(Opt);
}
va_end(ap);
return true;
}
va_end(ap);
// loop was left normally --> no hit
return false;
}
__GETPOT_INLINE void
GetPot::reset_cursor()
{ search_failed_f = false; cursor = 0; }
__GETPOT_INLINE void
GetPot::init_multiple_occurrence()
{ disable_loop(); reset_cursor(); }
__GETPOT_INLINE void
GetPot::set_true_string_list(unsigned N, const char* StringForTrue, ...)
{
true_string_list.clear();
if( N == 0 ) return;
va_list ap;
unsigned i = 1;
va_start(ap, StringForTrue);
for(; i < N ; ++i) {
char* Opt = va_arg(ap, char *);
true_string_list.push_back(std::string(Opt));
}
va_end(ap);
}
__GETPOT_INLINE void
GetPot::set_false_string_list(unsigned N, const char* StringForFalse, ...)
{
false_string_list.clear();
if( N == 0 ) return;
va_list ap;
unsigned i = 1;
va_start(ap, StringForFalse);
for(; i < N ; ++i) {
char* Opt = va_arg(ap, char *);
false_string_list.push_back(std::string(Opt));
}
va_end(ap);
}
///////////////////////////////////////////////////////////////////////////////
// (*) direct access to command line arguments
//
__GETPOT_INLINE const std::string
GetPot::operator[](unsigned idx) const
{ return idx < argv.size() ? argv[idx] : ""; }
template <class T> __GETPOT_INLINE T
GetPot::get(unsigned Idx, T Default) const
{
if( Idx >= argv.size() ) return Default;
return __convert_to_type(argv[Idx], (typename TypeInfo<T>::type)Default);
}
template <> __GETPOT_INLINE const char*
GetPot::get<const char*>(unsigned Idx, const char* Default) const
{
if( Idx >= argv.size() ) return Default;
else return __get_const_char(argv[Idx]);
}
template <class T> __GETPOT_INLINE T
GetPot::get(const StringOrCharP VarName)
{
return get<T>(VarName, (const char*)0x0);
}
template <class T> __GETPOT_INLINE T
GetPot::get(const StringOrCharP VarName, const char* Constraint)
{
return __get<T>(VarName, Constraint, /* ThrowExceptionF = */true);
}
template <class T> __GETPOT_INLINE T
GetPot::get(const StringOrCharP VarName, const char* Constraint, T Default)
{
return __get<T>(VarName, Constraint, Default, /* ThrowExceptionF = */GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT);
}
__GETPOT_INLINE unsigned
GetPot::size() const
{ return static_cast<unsigned int>(argv.size()); }
// -- next() function group
template <class T> __GETPOT_INLINE T
GetPot::next(T Default)
{
if( search_failed_f ) return Default;
cursor++;
if( cursor >= argv.size() )
{ cursor = static_cast<unsigned int>(argv.size()); return Default; }
// (*) record requested argument for later ufo detection
__record_argument_request(argv[cursor]);
const std::string Remain = __get_remaining_string(argv[cursor], prefix);
return Remain != "" ? __convert_to_type(Remain, (typename TypeInfo<T>::type)Default) : Default;
}
// -- follow() function group
// distinct option to be searched for
template <class T> __GETPOT_INLINE T
GetPot::follow(T Default, const char* Option)
{
// (*) record requested of argument is entirely handled in 'search()' and 'next()'
if( search(Option) == false ) return Default;
return next(Default);
}
// -- second follow() function group
// multiple option to be searched for
template <class T> __GETPOT_INLINE T
GetPot::follow(T Default, unsigned No, const char* P, ...)
{
// (*) record requested of argument is entirely handled in 'search()' and 'next()'
if( No == 0 ) return Default;
if( search(P) == true ) return next(Default);
va_list ap;
va_start(ap, P);
unsigned i=1;
for(; i<No; ++i) {
char* Opt = va_arg(ap, char *);
if( search(Opt) == true ) {
va_end(ap);
return next(Default);
}
}
va_end(ap);
return Default;
}
///////////////////////////////////////////////////////////////////////////////
// (*) directly connected options
//.............................................................................
//
template <class T> __GETPOT_INLINE T
GetPot::direct_follow(T Default, const char* Option)
{
const char* FollowStr = __match_starting_string(Option);
if( FollowStr == 0x0 ) return Default;
// (*) record requested of argument for later ufo-detection
__record_argument_request(std::string(Option) + FollowStr);
if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
return __convert_to_type(FollowStr, (typename TypeInfo<T>::type)Default);
}
__GETPOT_INLINE std::vector<std::string>
GetPot::string_tails(const char* StartString)
{
std::vector<std::string> result;
const unsigned N = static_cast<unsigned int>(strlen(StartString));
std::vector<std::string>::iterator it = argv.begin();
unsigned idx = 0;
while( it != argv.end() ) {
// (*) does start string match the given option?
// NO -> goto next option
if( (*it).compare(0, N, StartString) != 0 ) { ++it; ++idx; continue; }
// append the found tail to the result vector
result.push_back((*it).substr(N));
// adapt the nominus vector
std::vector<unsigned>::iterator nit = idx_nominus.begin();
for(; nit != idx_nominus.end(); ++nit) {
if( *nit == idx ) {
idx_nominus.erase(nit);
for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
break;
}
}
// erase the found option
argv.erase(it);
// 100% safe solution: set iterator back to the beginning.
// (normally, 'it--' would be enough, but who knows how the
// iterator is implemented and .erase() definitely invalidates
// the current iterator position.
if( argv.empty() ) break;
it = argv.begin();
}
cursor = 0;
nominus_cursor = -1;
return result;
}
__GETPOT_INLINE std::vector<int>
GetPot::int_tails(const char* StartString, const int Default /* = -1 */)
{
std::vector<int> result;
const unsigned N = static_cast<unsigned int>(strlen(StartString));
std::vector<std::string>::iterator it = argv.begin();
unsigned idx = 0;
while( it != argv.end() ) {
// (*) does start string match the given option?
// NO -> goto next option
if( (*it).compare(0, N, StartString) != 0 ) { ++it; ++idx; continue; }
// append the found tail to the result vector
result.push_back(__convert_to_type((*it).substr(N), Default));
// adapt the nominus vector
std::vector<unsigned>::iterator nit = idx_nominus.begin();
for(; nit != idx_nominus.end(); ++nit) {
if( *nit == idx ) {
idx_nominus.erase(nit);
for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
break;
}
}
// erase the found option
argv.erase(it);
// 100% safe solution: set iterator back to the beginning.
// (normally, 'it--' would be enough, but who knows how the
// iterator is implemented and .erase() definitely invalidates
// the current iterator position.
if( argv.empty() ) break;
it = argv.begin();
}
cursor = 0;
nominus_cursor = -1;
return result;
}
__GETPOT_INLINE std::vector<double>
GetPot::double_tails(const char* StartString,
const double Default /* = -1.0 */)
{
std::vector<double> result;
const unsigned N = static_cast<unsigned int>(strlen(StartString));
std::vector<std::string>::iterator it = argv.begin();
unsigned idx = 0;
while( it != argv.end() ) {
// (*) does start string match the given option?
// NO -> goto next option
if( (*it).compare(0, N, StartString) != 0 ) { ++it; ++idx; continue; }
// append the found tail to the result vector
result.push_back(__convert_to_type((*it).substr(N), Default));
// adapt the nominus vector
std::vector<unsigned>::iterator nit = idx_nominus.begin();
for(; nit != idx_nominus.end(); ++nit) {
if( *nit == idx ) {
idx_nominus.erase(nit);
for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
break;
}
}
// erase the found option
argv.erase(it);
// 100% safe solution: set iterator back to the beginning.
// (normally, 'it--' would be enough, but who knows how the
// iterator is implemented and .erase() definitely invalidates
// the current iterator position.
if( argv.empty() ) break;
it = argv.begin();
}
cursor = 0;
nominus_cursor = -1;
return result;
}
///////////////////////////////////////////////////////////////////////////////
// (*) lists of nominus following an option
//
__GETPOT_INLINE std::vector<std::string>
GetPot::nominus_followers(const char* Option)
{
std::vector<std::string> result_list;
if( search(Option) == false ) return result_list;
while( 1 + 1 == 2 ) {
++cursor;
if( cursor >= argv.size() ) {
cursor = argv.size() - 1;
return result_list;
}
if( argv[cursor].length() >= 1 ) {
if( argv[cursor][0] == '-' ) {
return result_list;
}
// -- record for later ufo-detection
__record_argument_request(argv[cursor]);
// -- append to the result list
result_list.push_back(argv[cursor]);
}
}
}
__GETPOT_INLINE std::vector<std::string>
GetPot::nominus_followers(unsigned No, ...)
{
std::vector<std::string> result_list;
// (*) record requested of argument is entirely handled in 'search()'
// and 'nominus_followers()'
if( No == 0 ) return result_list;
va_list ap;
va_start(ap, No);
for(unsigned i=0; i<No; ++i) {
char* Option = va_arg(ap, char *);
std::vector<std::string> tmp = nominus_followers(Option);
result_list.insert(result_list.end(), tmp.begin(), tmp.end());
// std::cerr << "option = '" << Option << "'" << std::endl;
// std::cerr << "length = " << tmp.size() << std::endl;
// std::cerr << "new result list = <";
// for(std::vector<std::string>::const_iterator it = result_list.begin();
// it != result_list.end(); ++it)
// std::cerr << *it << ", ";
// std::cerr << ">\n";
}
va_end(ap);
return result_list;
}
__GETPOT_INLINE const char*
GetPot::__match_starting_string(const char* StartString)
// pointer to the place where the string after
// the match inside the found argument starts.
// 0 no argument matches the starting string.
{
const unsigned N = static_cast<unsigned int>(strlen(StartString));
unsigned OldCursor = cursor;
if( OldCursor >= static_cast<unsigned int>(argv.size()) ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
search_failed_f = true;
// (*) first loop from cursor position until end
unsigned c = cursor;
for(; c < argv.size(); c++) {
if( argv[c].compare(0, N, StartString) == 0 ) {
cursor = c;
search_failed_f = false;
return __get_const_char(argv[c].substr(N));
}
}
if( ! search_loop_f ) return (const char*)0;
// (*) second loop from 0 to old cursor position
for(c = 1; c < OldCursor; c++) {
if( argv[c].compare(0, N, StartString) == 0 ) {
cursor = c;
search_failed_f = false;
return __get_const_char(argv[c].substr(N));
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// (*) search for flags
//.............................................................................
//
__GETPOT_INLINE bool
GetPot::options_contain(const char* FlagList) const
{
// go through all arguments that start with a '-' (but not '--')
std::string str;
STRING_VECTOR::const_iterator it = argv.begin();
for(; it != argv.end(); ++it) {
str = __get_remaining_string(*it, prefix);
if( str.length() >= 2 && str[0] == '-' && str[1] != '-' )
if( __check_flags(str, FlagList) ) return true;
}
return false;
}
__GETPOT_INLINE bool
GetPot::argument_contains(unsigned Idx, const char* FlagList) const
{
if( Idx >= argv.size() ) return false;
// (*) record requested of argument for later ufo-detection
// an argument that is checked for flags is considered to be 'requested'
((GetPot*)this)->__record_argument_request(argv[Idx]);
if( prefix == "" )
// search argument for any flag in flag list
return __check_flags(argv[Idx], FlagList);
// if a prefix is set, then the argument index is the index
// inside the 'namespace'
// => only check list of arguments that start with prefix
unsigned no_matches = 0;
unsigned i=0;
for(; i<argv.size(); ++i) {
const std::string Remain = __get_remaining_string(argv[i], prefix);
if( Remain != "") {
no_matches += 1;
if( no_matches == Idx)
return __check_flags(Remain, FlagList);
}
}
// no argument in this namespace
return false;
}
__GETPOT_INLINE bool
GetPot::__check_flags(const std::string& Str, const char* FlagList) const
{
const char* p=FlagList;
for(; *p != '\0' ; p++)
if( Str.find(*p) != std::string::npos ) return true; // found something
return false;
}
///////////////////////////////////////////////////////////////////////////////
// (*) nominus arguments
__GETPOT_INLINE STRING_VECTOR
GetPot::nominus_vector() const
// return vector of nominus arguments
{
STRING_VECTOR nv;
std::vector<unsigned>::const_iterator it = idx_nominus.begin();
for(; it != idx_nominus.end(); ++it) {
nv.push_back(argv[*it]);
// (*) record for later ufo-detection
// when a nominus vector is requested, the entire set of nominus arguments are
// tagged as 'requested'
((GetPot*)this)->__record_argument_request(argv[*it]);
}
return nv;
}
__GETPOT_INLINE std::string
GetPot::next_nominus()
{
if( nominus_cursor < int(idx_nominus.size()) - 1 ) {
const std::string Tmp = argv[idx_nominus[++nominus_cursor]];
__record_argument_request(Tmp);
return Tmp;
}
return std::string("");
}
///////////////////////////////////////////////////////////////////////////////
// (*) variables
//.............................................................................
//
template <class T> __GETPOT_INLINE T
GetPot::__get(const StringOrCharP VarName, const char* Constraint, bool ThrowExceptionF) const
{
T Default = TypeInfo<T>::default_value();
const variable* sv = __find_variable(VarName.content, TypeInfo<T>::name(), ThrowExceptionF);
if( sv == 0x0 )
return Default;
if( Constraint != 0x0 && ! __constraint_check(sv->original, Constraint, ThrowExceptionF) )
return Default;
return __convert_to_type<typename TypeInfo<T>::type>(sv->original, TypeInfo<T>::convert(Default), ThrowExceptionF);
}
template <class T> __GETPOT_INLINE T
GetPot::__get(const StringOrCharP VarName, const char* Constraint, T Default, bool ThrowExceptionF) const
{
const variable* sv = __find_variable(VarName.content, TypeInfo<T>::name(), false);
if( sv == 0x0 )
return Default;
if( Constraint != 0x0 && ! __constraint_check(sv->original, Constraint, ThrowExceptionF) )
return Default;
return __convert_to_type<typename TypeInfo<T>::type>(sv->original, TypeInfo<T>::convert(Default), ThrowExceptionF);
}
template <class T> __GETPOT_INLINE T
GetPot::__get_element(const StringOrCharP VarName, unsigned Idx, const char* Constraint,
bool ThrowExceptionF) const
{
T Default = TypeInfo<T>::default_value();
const variable* sv = __find_variable(VarName.content, TypeInfo<T>::name(), ThrowExceptionF);
if( sv == 0 )
return Default;
const std::string* element = sv->get_element(Idx, ThrowExceptionF);
if( element == 0 )
return Default;
if( Constraint != 0x0 && ! __constraint_check(*element, Constraint, ThrowExceptionF) )
return Default;
return __convert_to_type<typename TypeInfo<T>::type>(*element, TypeInfo<T>::convert(Default), ThrowExceptionF);
}
template <class T> __GETPOT_INLINE T
GetPot::__get_element(const StringOrCharP VarName, unsigned Idx, const char* Constraint,
T Default, bool ThrowExceptionF) const
{
const variable* sv = __find_variable(VarName.content, TypeInfo<T>::name(), false);
if( sv == 0 )
return Default;
const std::string* element = sv->get_element(Idx, ThrowExceptionF);
if( element == 0 )
return Default;
else if( Constraint != 0x0 && ! __constraint_check(*element, Constraint, ThrowExceptionF) )
return Default;
return __convert_to_type<typename TypeInfo<T>::type>(*element, TypeInfo<T>::convert(Default), ThrowExceptionF);
}
template<class T> __GETPOT_INLINE T
GetPot::operator()(const StringOrCharP VarName, T Default) const
{ return __get<T>(VarName, (const char*)0x0, Default, /* ThrowExceptionF = */GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT); }
template <class T> __GETPOT_INLINE T
GetPot::get_element(const StringOrCharP VarName, unsigned Idx, const char* Constraint)
{ return __get_element<T>(VarName, Idx, Constraint, /* ThrowExceptionF = */true); }
template <class T> __GETPOT_INLINE T
GetPot::get_element(const StringOrCharP VarName, unsigned Idx, const char* Constraint, T Default)
{ return __get_element<T>(VarName, Idx, Constraint, Default, /* ThrowExceptionF = */GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT); }
template <class T> __GETPOT_INLINE T
GetPot::operator()(const StringOrCharP VarName, unsigned Idx, T Default) const
{ return __get_element<T>(VarName, Idx, (const char*)0x0, Default, /* ThrowExceptionF = */GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT); }
__GETPOT_INLINE void
GetPot::__record_argument_request(const std::string& Name)
{
if( ! __request_recording_f ) return;
// (*) record requested variable for later ufo detection
_requested_arguments.push_back(Name);
// (*) record considered section for ufo detection
STRING_VECTOR STree = __get_section_tree(Name);
victorate(std::string, STree, it) {
if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() ) {
if( section.length() != 0 ) _requested_sections.push_back(*it);
}
}
}
__GETPOT_INLINE void
GetPot::__record_variable_request(const std::string& Name)
{
if( ! __request_recording_f ) return;
// (*) record requested variable for later ufo detection
_requested_variables.push_back(Name);
// (*) record considered section for ufo detection
STRING_VECTOR STree = __get_section_tree(Name);
victorate(std::string, STree, it) {
if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
if( section.length() != 0 ) _requested_sections.push_back(*it);
}
}
// To build a GetPot instance
__GETPOT_INLINE void
GetPot::__build(const std::string& FileName,
const std::string& CommentStart, const std::string& CommentEnd,
const std::string& FieldSeparator)
{
filename = FileName;
__basic_initialization();
// if specified -> overwrite default strings
if( CommentStart.length() != 0 ) _comment_start = std::string(CommentStart);
if( CommentEnd.length() != 0 ) _comment_end = std::string(CommentEnd);
if( FieldSeparator.length() != 0 ) _field_separator = FieldSeparator;
STRING_VECTOR _apriori_argv;
// -- file name is element of argument vector, however, it is not parsed for
// variable assignments or nominuses.
_apriori_argv.push_back(std::string(FileName));
STRING_VECTOR args = __read_in_file(FileName);
_apriori_argv.insert(_apriori_argv.begin()+1, args.begin(), args.end());
__parse_argument_vector(_apriori_argv);
}
// to split a string according to delimiters and elements are stored in a vector.
__GETPOT_INLINE
void GetPot::__split(std::string str, std::vector<std::string>& vect,
std::string delimiters /*= " \n\t"*/)
{
vect.clear();
std::string tmp;
std::string::size_type index_beg, index_end;
index_beg = str.find_first_not_of(delimiters);
while (index_beg != std::string::npos) {
index_end = str.find_first_of(delimiters, index_beg);
tmp = str.substr(index_beg, index_end == std::string::npos ?
std::string::npos : (index_end - index_beg));
vect.push_back(tmp);
index_beg = str.find_first_not_of(delimiters, index_end);
}
}
// (*) following functions are to be used from 'outside', after getpot has parsed its
// arguments => append an argument in the argument vector that reflects the addition
__GETPOT_INLINE void
GetPot::__set_variable(const std::string& VarName, const std::string& Value)
{
const GetPot::variable* Var;
const std::string EmptyString("");
if ( !built )
Var = __find_variable(VarName, EmptyString, false);
else
Var = __find_variable(VarName, EmptyString);
if( Var == 0 ) variables.push_back(variable(VarName, Value, _field_separator));
else ((GetPot::variable*)Var)->take(Value, _field_separator);
}
template <>__GETPOT_INLINE void
GetPot::set_variable<const char*>(const StringOrCharP VarName, const char* Value, const bool Requested /* = true*/)
{
const std::string Arg = prefix + VarName.content + std::string("=") + std::string(Value);
argv.push_back(Arg);
__set_variable(VarName.content, Value);
// if user does not specify the variable as 'not being requested' it will be
// considered amongst the requested variables
if( Requested ) __record_variable_request(Arg);
}
template <> __GETPOT_INLINE void
GetPot::set_variable<double>(const StringOrCharP VarName, double Value, const bool Requested /* = true*/)
{ __set_variable(VarName.content, __double2string(Value)); }
template <> __GETPOT_INLINE void
GetPot::set_variable<int>(const StringOrCharP VarName, int Value, const bool Requested /* = true*/)
{ __set_variable(VarName.content, __int2string(Value)); }
template <> __GETPOT_INLINE void
GetPot::set_variable<bool>(const StringOrCharP VarName, bool Value, const bool Requested /* = true*/)
{
if( true_string_list.size() == 0 || false_string_list.size() == 0 ) {
throw std::runtime_error(GETPOT_STR_TRUE_FALSE_UNDEFINED);
}
__set_variable(VarName.content,
Value ? true_string_list[0] : false_string_list[0]);
}
template <class T>
__GETPOT_INLINE void
GetPot::set(const StringOrCharP VarName, T& Value)
{
Value = get<T>(VarName);
}
template <class T>
__GETPOT_INLINE void
GetPot::set(const StringOrCharP VarName, T& Value, const char* Constraint)
{
Value = get<T>(VarName, Constraint);
}
template <class T, class U>
__GETPOT_INLINE void
GetPot::set(const StringOrCharP VarName, T& Value, const char* Constraint, U Default)
{
Value = get<U>(VarName, Constraint, Default);
}
__GETPOT_INLINE unsigned
GetPot::vector_variable_size(StringOrCharP VarName) const
{
const std::string EmptyString("");
const variable* sv = __find_variable(VarName.content, EmptyString);
if( sv == 0 ) return 0;
return static_cast<unsigned int>(sv->value.size());
}
__GETPOT_INLINE STRING_VECTOR
GetPot::get_variable_names() const
{
STRING_VECTOR result;
std::vector<GetPot::variable>::const_iterator it = variables.begin();
for(; it != variables.end(); ++it) {
const std::string Tmp = __get_remaining_string((*it).name, prefix);
if( Tmp != "" ) result.push_back(Tmp);
}
return result;
}
__GETPOT_INLINE STRING_VECTOR
GetPot::get_section_names() const
{ return section_list; }
__GETPOT_INLINE const GetPot::variable*
GetPot::__find_variable(const std::string& VarName, const std::string& TypeName,
bool ThrowExceptionF/*=GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT*/) const
{
const std::string Name = prefix + VarName;
// (*) record requested variable for later ufo detection
((GetPot*)this)->__record_variable_request(Name);
/* Linear search (?)... maybe we can do something better ... */
std::vector<variable>::const_iterator it = variables.begin();
for(; it != variables.end(); ++it) {
if( (*it).name == Name ) return &(*it);
}
if( ThrowExceptionF ) {
std::string msg(GETPOT_STR_FILE " ");
msg += std::string("\"") + filename + "\": ";
msg += std::string(GETPOT_STR_MISSING_VARIABLE) + " \'";
msg += VarName + "\' ";
if( TypeName.length() != 0 ) msg += std::string(GETPOT_STR_WITH_TYPE " ") + TypeName;
if( ! prefix.empty() ) msg += std::string(" " GETPOT_STR_IN_SECTION " \"") + prefix + "\"";
msg += ".";
throw std::runtime_error(msg);
}
else {
return 0x0;
}
}
///////////////////////////////////////////////////////////////////////////////
// (*) ouput (basically for debugging reasons
//.............................................................................
//
__GETPOT_INLINE int
GetPot::print() const
{
std::cout << "argc = " << static_cast<unsigned int>(argv.size()) << std::endl;
STRING_VECTOR::const_iterator it = argv.begin();
for(; it != argv.end(); ++it)
std::cout << *it << std::endl;
std::cout << std::endl;
return 1;
}
// (*) dollar bracket expressions (DBEs) ------------------------------------
//
// 1) Entry Function: __DBE_expand_string()
// Takes a string such as
//
// "${+ ${x} ${y}} Subject-${& ${section} ${subsection}}: ${title}"
//
// calls __DBE_expand() for each of the expressions
//
// ${+ ${x} ${y}}
// ${& ${section} ${subsection}}
// ${Title}
//
// and returns the string
//
// "4711 Subject-1.01: Mit den Clowns kamen die Schwaene"
//
// assuming that
// x = "4699"
// y = "12"
// section = "1."
// subsection = "01"
// title = "Mit den Clowns kamen die Schwaene"
//
// 2) __DBE_expand():
//
// checks for the command, i.e. the 'sign' that follows '${'
// divides the argument list into sub-expressions using
// __DBE_get_expr_list()
//
// ${+ ${x} ${y}} -> "${x}" "${y}"
// ${& ${section} ${subsection}} -> "${section}" "${subsection}"
// ${Title} -> Nothing, variable expansion
//
// 3) __DBE_expression_list():
//
// builds a vector of unbracketed whitespace separated strings, i.e.
//
// " ${Number}.a ${: Das Marmorbild} AB-${& Author= ${Eichendorf}-1870}"
//
// is split into a vector
//
// [0] ${Number}.a
// [1] ${: Das Marmorbild}
// [2] AB-${& Author= ${Eichendorf}}-1870
//
// Each sub-expression is expanded using expand().
//---------------------------------------------------------------------------
__GETPOT_INLINE std::string
GetPot::__DBE_expand_string(const std::string str)
{
// Parses for closing operators '${ }' and expands them letting
// white spaces and other letters as they are.
std::string new_string = "";
unsigned open_brackets = 0;
unsigned first = 0;
unsigned i = 0;
for(; i<str.size(); ++i) {
if( i < str.size() - 2 && str.substr(i, 2) == "${" ) {
if( open_brackets == 0 ) first = i+2;
open_brackets++;
}
else if( str[i] == '}' && open_brackets > 0) {
open_brackets -= 1;
if( open_brackets == 0 ) {
const std::string Replacement = __DBE_expand(str.substr(first, i - first));
new_string += Replacement;
}
}
else if( open_brackets == 0 )
new_string += str[i];
}
return new_string;
}
__GETPOT_INLINE STRING_VECTOR
GetPot::__DBE_get_expr_list(const std::string str_, const unsigned ExpectedNumber)
// ensures that the resulting vector has the expected number
// of arguments, but they may contain an error message
{
std::string str = str_;
// Separates expressions by non-bracketed whitespaces, expands them
// and puts them into a list.
unsigned i=0;
// (1) eat initial whitespaces
for(; i < str.size(); ++i)
if( ! isspace(str[i]) ) break;
STRING_VECTOR expr_list;
unsigned open_brackets = 0;
std::vector<unsigned> start_idx;
unsigned start_new_string = i;
unsigned l = static_cast<unsigned int>(str.size());
// (2) search for ${ } expressions ...
while( i < l ) {
const char letter = str[i];
// whitespace -> end of expression
if( isspace(letter) && open_brackets == 0) {
expr_list.push_back(str.substr(start_new_string, i - start_new_string));
bool no_breakout_f = true;
for(++i; i < l ; ++i) {
if( ! isspace(str[i]) )
{ no_breakout_f = false; start_new_string = i; break; }
}
if( no_breakout_f ) {
// end of expression list
if( expr_list.size() < ExpectedNumber ) {
const std::string pre_tmp("<< ${ }: missing arguments>>");
STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
}
return expr_list;
}
}
// dollar-bracket expression
if( str.length() >= i+2 && str.substr(i, 2) == "${" ) {
open_brackets++;
start_idx.push_back(i+2);
}
else if( letter == '}' && open_brackets > 0) {
int start = start_idx[start_idx.size()-1];
start_idx.pop_back();
const std::string Replacement = __DBE_expand(str.substr(start, i-start));
if( start - 3 < (int)0)
str = Replacement + str.substr(i+1);
else
str = str.substr(0, start-2) + Replacement + str.substr(i+1);
l = static_cast<unsigned int>(str.size());
i = start + static_cast<unsigned int>(Replacement.size()) - 3;
open_brackets--;
}
++i;
}
// end of expression list
expr_list.push_back(str.substr(start_new_string, i-start_new_string));
if( expr_list.size() < ExpectedNumber ) {
const std::string pre_tmp("<< ${ }: missing arguments>>");
STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
}
return expr_list;
}
__GETPOT_INLINE const GetPot::variable*
GetPot::__DBE_get(std::string VarName)
{
static GetPot::variable ev;
const std::string EmptyString("");
std::string secure_Prefix = prefix;
prefix = section;
// (1) first search in currently active section
const GetPot::variable* var = __find_variable(VarName, EmptyString, false);
if( var != 0 ) { prefix = secure_Prefix; return var; }
// (2) search in root name space
prefix = "";
var = __find_variable(VarName, EmptyString);
if( var != 0 ) { prefix = secure_Prefix; return var; }
prefix = secure_Prefix;
// error occured => variable name == ""
char* tmp = new char[VarName.length() + 25];
GETPOT_SNPRINTF(tmp, (int)sizeof(char)*(VarName.length() + 25),
"<<${ } variable '%s' undefined>>", VarName.c_str());
ev.name = "";
ev.original = std::string(tmp);
delete [] tmp;
return &ev;
}
__GETPOT_INLINE std::string
GetPot::__DBE_expand(const std::string expr)
{
// ${: } pure text
if( expr[0] == ':' )
return expr.substr(1);
// ${& expr expr ... } text concatination
else if( expr[0] == '&' ) {
const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 1);
STRING_VECTOR::const_iterator it = A.begin();
std::string result = *it++;
for(; it != A.end(); ++it) result += *it;
return result;
}
// ${<-> expr expr expr} text replacement
else if( expr.length() >= 3 && expr.substr(0, 3) == "<->" ) {
STRING_VECTOR A = __DBE_get_expr_list(expr.substr(3), 3);
std::string::size_type tmp = 0;
const std::string::size_type L = A[1].length();
while( (tmp = A[0].find(A[1])) != std::string::npos ) {
A[0].replace(tmp, L, A[2]);
}
return A[0];
}
// ${+ ...}, ${- ...}, ${* ...}, ${/ ...} expressions
else if( expr[0] == '+' ) {
STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
STRING_VECTOR::const_iterator it = A.begin();
double result = __convert_to_type(*it++, 0.0);
for(; it != A.end(); ++it)
result += __convert_to_type(*it, 0.0);
return __double2string(result);
}
else if( expr[0] == '-' ) {
STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
STRING_VECTOR::const_iterator it = A.begin();
double result = __convert_to_type(*it++, 0.0);
for(; it != A.end(); ++it)
result -= __convert_to_type(*it, 0.0);
return __double2string(result);
}
else if( expr[0] == '*' ) {
STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
STRING_VECTOR::const_iterator it = A.begin();
double result = __convert_to_type(*it++, 0.0);
for(; it != A.end(); ++it)
result *= __convert_to_type(*it, 0.0);
return __double2string(result);
}
else if( expr[0] == '/' ) {
STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
STRING_VECTOR::const_iterator it = A.begin();
double result = __convert_to_type(*it++, 0.0);
if( result == 0 ) return "0.0";
for(; it != A.end(); ++it) {
const double Q = __convert_to_type(*it, 0.0);
if( Q == 0.0 ) return "0.0";
result /= Q;
}
return __double2string(result);
}
// ${^ ... } power expressions
else if( expr[0] == '^' ) {
STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
STRING_VECTOR::const_iterator it = A.begin();
double result = __convert_to_type(*it++, 0.0);
for(; it != A.end(); ++it)
result = pow(result, __convert_to_type(*it, 0.0));
return __double2string(result);
}
// ${== } ${<= } ${>= } comparisons (return the number of the first 'match'
else if( expr.length() >= 2 &&
( expr.substr(0,2) == "==" || expr.substr(0,2) == ">=" ||
expr.substr(0,2) == "<=" || expr[0] == '>' || expr[0] == '<')) {
// differentiate between two and one sign operators
unsigned op = 0;
enum { EQ, GEQ, LEQ, GT, LT };
if ( expr.substr(0, 2) == "==" ) op = EQ;
else if ( expr.substr(0, 2) == ">=" ) op = GEQ;
else if ( expr.substr(0, 2) == "<=" ) op = LEQ;
else if ( expr[0] == '>' ) op = GT;
else /* "<" */ op = LT;
STRING_VECTOR a;
if ( op == GT || op == LT ) a = __DBE_get_expr_list(expr.substr(1), 2);
else a = __DBE_get_expr_list(expr.substr(2), 2);
std::string x_orig = a[0];
double x = __convert_to_type(x_orig, 1e37);
unsigned i = 1;
STRING_VECTOR::const_iterator y_orig = a.begin();
for(y_orig++; y_orig != a.end(); y_orig++) {
double y = __convert_to_type(*y_orig, 1e37);
// set the strings as reference if one wasn't a number
if ( x == 1e37 || y == 1e37 ) {
// it's a string comparison
if( (op == EQ && x_orig == *y_orig) || (op == GEQ && x_orig >= *y_orig) ||
(op == LEQ && x_orig <= *y_orig) || (op == GT && x_orig > *y_orig) ||
(op == LT && x_orig < *y_orig) )
return __int2string(i);
}
else {
// it's a number comparison
if( (op == EQ && x == y) || (op == GEQ && x >= y) ||
(op == LEQ && x <= y) || (op == GT && x > y) ||
(op == LT && x < y) )
return __int2string(i);
}
++i;
}
// nothing fulfills the condition => return 0
return "0";
}
// ${?? expr expr} select
else if( expr.length() >= 2 && expr.substr(0, 2) == "??" ) {
STRING_VECTOR a = __DBE_get_expr_list(expr.substr(2), 2);
double x = __convert_to_type(a[0], 1e37);
// last element is always the default argument
if( x == 1e37 || x < 0 || x >= a.size() - 1 ) return a[a.size()-1];
// round x to closest integer
return a[int(x+0.5)];
}
// ${? expr expr expr} if then else conditions
else if( expr[0] == '?' ) {
STRING_VECTOR a = __DBE_get_expr_list(expr.substr(1), 2);
if( __convert_to_type(a[0], 0.0) == 1.0 ) return a[1];
else if( a.size() > 2 ) return a[2];
}
// ${! expr} maxro expansion
else if( expr[0] == '!' ) {
const GetPot::variable* Var = __DBE_get(expr.substr(1));
// error
if( Var->name == "" ) return std::string(Var->original);
const STRING_VECTOR A = __DBE_get_expr_list(Var->original, 2);
return A[0];
}
// ${@: } - string subscription
else if( expr.length() >= 2 && expr.substr(0,2) == "@:" ) {
const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(2), 2);
double x = __convert_to_type(A[1], 1e37);
// last element is always the default argument
if( x == 1e37 || x < 0 || x >= A[0].size() - 1)
return "<<1st index out of range>>";
if( A.size() > 2 ) {
double y = __convert_to_type(A[2], 1e37);
if ( y != 1e37 && y > 0 && y <= A[0].size() - 1 && y > x )
return A[0].substr(int(x+0.5), int(y+1.5) - int(x+0.5));
else if( y == -1 )
return A[0].substr(int(x+0.5));
return "<<2nd index out of range>>";
}
else {
char* tmp = new char[2];
tmp[0] = A[0][int(x+0.5)]; tmp[1] = '\0';
std::string result(tmp);
delete [] tmp;
return result;
}
}
// ${@ } - vector subscription
else if( expr[0] == '@' ) {
STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
const GetPot::variable* Var = __DBE_get(A[0]);
// error
if( Var->name == "" ) {
// make a copy of the string if an error occured
// (since the error variable is a static variable inside get())
return std::string(Var->original);
}
double x = __convert_to_type(A[1], 1e37);
// last element is always the default argument
if (x == 1e37 || x < 0 || x >= Var->value.size() )
return "<<1st index out of range>>";
if ( A.size() > 2) {
double y = __convert_to_type(A[2], 1e37);
int begin = int(x+0.5);
int end = 0;
if ( y != 1e37 && y > 0 && y <= Var->value.size() && y > x)
end = int(y+1.5);
else if( y == -1 )
end = static_cast<unsigned int>(Var->value.size());
else
return "<<2nd index out of range>>";
std::string result = *(Var->get_element(begin));
int i = begin+1;
for(; i < end; ++i)
result += std::string(" ") + *(Var->get_element(i));
return result;
}
else
return *(Var->get_element(int(x+0.5)));
}
const STRING_VECTOR A = __DBE_get_expr_list(expr, 1);
const GetPot::variable* B = __DBE_get(A[0]);
// make a copy of the string if an error occured
// (since the error variable is a static variable inside get())
if( B->name == "" ) return std::string(B->original);
// (psuggs@pobox.com mentioned to me the warning MSVC++6.0 produces
// with: else return B->original (thanks))
return B->original;
}
///////////////////////////////////////////////////////////////////////////////
// (*) unidentified flying objects
//.............................................................................
//
__GETPOT_INLINE bool
GetPot::__search_string_vector(const STRING_VECTOR& VecStr, const std::string& Str) const
{
victorate(std::string, VecStr, itk) {
if( *itk == Str ) return true;
}
return false;
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_arguments(unsigned Number,
const char* KnownArgument1, ...) const
{
STRING_VECTOR known_arguments;
// (1) create a vector of known arguments
if( Number == 0 ) return STRING_VECTOR();
va_list ap;
va_start(ap, KnownArgument1);
known_arguments.push_back(std::string(KnownArgument1));
unsigned i=1;
for(; i<Number; ++i)
known_arguments.push_back(std::string(va_arg(ap, char *)));
va_end(ap);
return unidentified_arguments(known_arguments);
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_arguments() const
{ return unidentified_arguments(_requested_arguments); }
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_arguments(const STRING_VECTOR& Knowns) const
{
STRING_VECTOR ufos;
STRING_VECTOR::const_iterator it = argv.begin();
++it; // forget about argv[0] (application or filename)
for(; it != argv.end(); ++it) {
// -- argument belongs to prefixed section ?
const std::string arg = __get_remaining_string(*it, prefix);
if( arg == "" ) continue;
// -- check if in list
if( __search_string_vector(Knowns, arg) == false)
ufos.push_back(*it);
}
return ufos;
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_options(unsigned Number,
const char* KnownOption1, ...) const
{
STRING_VECTOR known_options;
// (1) create a vector of known arguments
if( Number == 0 ) return STRING_VECTOR();
va_list ap;
va_start(ap, KnownOption1);
known_options.push_back(std::string(KnownOption1));
unsigned i=1;
for(; i<Number; ++i)
known_options.push_back(std::string(va_arg(ap, char *)));
va_end(ap);
return unidentified_options(known_options);
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_options() const
{
// -- every option is an argument.
// -- the set of requested arguments contains the set of requested options.
// -- IF the set of requested arguments contains unrequested options,
// THEN they were requested as 'follow' and 'next' arguments and not as real options.
//
// => it is not necessary to separate requested options from the list
STRING_VECTOR option_list;
victorate(std::string, _requested_arguments, it) {
const std::string arg = *it;
if( arg.length() == 0 ) continue;
if( arg[0] == '-' ) option_list.push_back(arg);
}
return unidentified_options(option_list);
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_options(const STRING_VECTOR& Knowns) const
{
STRING_VECTOR ufos;
STRING_VECTOR::const_iterator it = argv.begin();
++it; // forget about argv[0] (application or filename)
for(; it != argv.end(); ++it) {
// -- argument belongs to prefixed section ?
const std::string arg = __get_remaining_string(*it, prefix);
if( arg == "" ) continue;
// is argument really an option (starting with '-') ?
if( arg.length() < 1 || arg[0] != '-' ) continue;
if( __search_string_vector(Knowns, arg) == false)
ufos.push_back(*it);
}
return ufos;
}
__GETPOT_INLINE std::string
GetPot::unidentified_flags(const char* KnownFlagList, int ArgumentNumber=-1) const
// Two modes:
// ArgumentNumber >= 0 check specific argument
// ArgumentNumber == -1 check all options starting with one '-'
// for flags
{
std::string ufos;
STRING_VECTOR known_arguments;
std::string KFL(KnownFlagList);
// (2) iteration over '-' arguments (options)
if( ArgumentNumber == -1 ) {
STRING_VECTOR::const_iterator it = argv.begin();
++it; // forget about argv[0] (application or filename)
for(; it != argv.end(); ++it) {
// -- argument belongs to prefixed section ?
const std::string arg = __get_remaining_string(*it, prefix);
//
// -- does arguments start with '-' (but not '--')
if( arg.length() < 2 || arg[0] != '-' || arg[1] == '-' ) continue;
// -- check out if flags inside option are contained in KnownFlagList
for(std::size_t i=1; i<arg.length(); ++i) {
if( KFL.find(arg[i]) == std::string::npos ) ufos += arg[i];
}
}
}
// (1) check specific argument
else {
// -- only check arguments that start with prefix
int no_matches = 0;
unsigned i=1;
for(; i<argv.size(); ++i) {
const std::string Remain = __get_remaining_string(argv[i], prefix);
if( Remain != "") {
no_matches++;
if( no_matches == ArgumentNumber) {
// -- the right argument number inside the section is found
// => check it for flags
for(std::size_t i=1; i<Remain.length(); ++i) {
if( KFL.find(Remain[i]) == std::string::npos ) ufos += Remain[i];
}
return ufos;
}
}
}
}
return ufos;
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_variables(unsigned Number,
const char* KnownVariable1, ...) const
{
STRING_VECTOR known_variables;
// create vector of known arguments
if( Number == 0 ) return STRING_VECTOR();
va_list ap;
va_start(ap, KnownVariable1);
known_variables.push_back(std::string(KnownVariable1));
unsigned i=1;
for(; i<Number; ++i)
known_variables.push_back(std::string(va_arg(ap, char *)));
va_end(ap);
return unidentified_variables(known_variables);
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_variables(const STRING_VECTOR& Knowns) const
{
STRING_VECTOR ufos;
victorate(GetPot::variable, variables, it) {
// -- check if variable has specific prefix
const std::string var_name = __get_remaining_string((*it).name, prefix);
if( var_name == "" ) continue;
// -- check if variable is known
if( __search_string_vector(Knowns, var_name) == false)
ufos.push_back((*it).name);
}
return ufos;
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_variables() const
{ return unidentified_variables(_requested_variables); }
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_sections(unsigned Number,
const char* KnownSection1, ...) const
{
STRING_VECTOR known_sections;
// (1) create a vector of known arguments
if( Number == 0 ) return STRING_VECTOR();
va_list ap;
va_start(ap, KnownSection1);
known_sections.push_back(std::string(KnownSection1));
unsigned i=1;
for(; i<Number; ++i) {
std::string tmp = std::string(va_arg(ap, char *));
if( tmp.length() == 0 ) continue;
if( tmp[tmp.length()-1] != '/' ) tmp += '/';
known_sections.push_back(tmp);
}
va_end(ap);
return unidentified_sections(known_sections);
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_sections() const
{ return unidentified_sections(_requested_sections); }
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_sections(const STRING_VECTOR& Knowns) const
{
STRING_VECTOR ufos;
victorate(std::string, section_list, it) {
// -- check if section conform to prefix
const std::string sec_name = __get_remaining_string(*it, prefix);
if( sec_name == "" ) continue;
// -- check if section is known
if( __search_string_vector(Knowns, sec_name) == false )
ufos.push_back(*it);
}
return ufos;
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_nominuses(unsigned Number, const char* Known, ...) const
{
STRING_VECTOR known_nominuses;
// create vector of known arguments
if( Number == 0 ) return STRING_VECTOR();
va_list ap;
va_start(ap, Known);
known_nominuses.push_back(std::string(Known));
unsigned i=1;
for(; i<Number; ++i) {
std::string tmp = std::string(va_arg(ap, char *));
if( tmp.length() == 0 ) continue;
known_nominuses.push_back(tmp);
}
va_end(ap);
return unidentified_nominuses(known_nominuses);
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_nominuses() const {
// -- every nominus is an argument.
// -- the set of requested arguments contains the set of requested nominuss.
// -- IF the set of requested arguments contains unrequested nominuss,
// THEN they were requested as 'follow' and 'next' arguments and not as real nominuses.
//
// => it is not necessary to separate requested nominus from the list
return unidentified_nominuses(_requested_arguments);
}
__GETPOT_INLINE STRING_VECTOR
GetPot::unidentified_nominuses(const STRING_VECTOR& Knowns) const
{
STRING_VECTOR ufos;
// (2) iterate over all arguments
STRING_VECTOR::const_iterator it = argv.begin();
++it; // forget about argv[0] (application or filename)
for(; it != argv.end(); ++it) {
// -- check if nominus part of prefix
const std::string arg = __get_remaining_string(*it, prefix);
if( arg == "" ) continue;
if( arg.length() < 1 ) continue;
// option ? --> not a nomius
if( arg[0] == '-' ) continue;
// section ? --> not a real nominus
if( arg[0] == '[' && arg[arg.length()-1] == ']' ) continue;
// variable definition ? --> not a real nominus
bool continue_f = false;
unsigned i=0;
for(; i<arg.length() ; ++i)
if( arg[i] == '=' ) { continue_f = true; break; }
if( continue_f ) continue;
// real nominuses are compared with the given list
if( __search_string_vector(Knowns, arg) == false )
ufos.push_back(*it);
}
return ufos;
}
__GETPOT_INLINE bool
GetPot::__constraint_check(const std::string& Value, const char* ConstraintStr,
bool ThrowExceptionF) const
{
std::string ConstraintString = std::string(ConstraintStr);
if( ConstraintString == "" ) return true;
if( __constraint_check_OR(Value, &ConstraintStr) ) return true;
if( ThrowExceptionF ) {
std::string msg(GETPOT_STR_FILE " ");
msg += std::string("\"") + filename + "\": \'";
msg += std::string(Value) + "\' ";
if( ! prefix.empty() )
msg += std::string("\n " GETPOT_STR_IN_SECTION " \"") + prefix + "\"\n";
msg += std::string(GETPOT_STR_DOES_NOT_SATISFY_CONSTRAINT) + " \'" + ConstraintString + "\'";
msg += ".";
throw std::runtime_error(msg);
}
else {
return false;
}
}
/*
* GRAMMAR:
*
* or_expr: or_expr '|' and_expr
* and_expr
*
* and_expr: and_expr '&' primary
* primary
*
* primary: '>' number
* '>=' number
* '<' number
* ...
* 'string'
* '(' or_expr ')' */
__GETPOT_INLINE bool
GetPot::__constraint_check_OR(const std::string& Value, const char** iterator) const
{
bool result = false;
do {
if (**iterator == '|') ++(*iterator);
while( isspace(**iterator) ) ++(*iterator); // skip whitespace
if( __constraint_check_AND(Value, iterator) ) result = true;
while( isspace(**iterator) ) ++(*iterator); // skip whitespace
} while ( **iterator == '|' );
return result;
}
__GETPOT_INLINE bool
GetPot::__constrain_check_EQUAL_STRING(const char* viterator, const char** iterator) const
{
++(*iterator);
// Compare strings from single quote to single quote
// loop: 'break' means 'not equal'
while( 1 + 1 == 2 ) {
if( *viterator != **iterator ) break; // letter in value != letter in iterator
++(*iterator); ++viterator;
if( *viterator == '\0' ) {
if ( **iterator != '\'' ) break; // value ended before iterator
return true;
}
else if( **iterator == '\'' ) break; // iterator ended before value
}
// iterator must proceed to the place after the single quote '
while( **iterator != '\'' ) ++(*iterator);
++(*iterator);
return false;
}
__GETPOT_INLINE bool
GetPot::__constraint_check_AND(const std::string& Value, const char** iterator) const
{
bool result = true;
do {
if (**iterator == '&') ++(*iterator);
while( isspace(**iterator) ) ++(*iterator); // skip whitespace
if( ! __constraint_check_PRIMARY(Value, iterator) ) result = false;
while( isspace(**iterator) ) ++(*iterator); // skip whitespace
} while ( **iterator == '&' );
return result;
}
__GETPOT_INLINE bool
GetPot::__constraint_check_PRIMARY(const std::string& Value,
const char** iterator) const
{
enum Operator {
EQ = 0x80,
GREATER = 0x01, // 'or'-ring 0x80 into an operator
GREATER_EQ = EQ | GREATER, // means adding the 'equal option'.
LESS = 0x02,
LESS_EQ = EQ | LESS,
NOT = 0x03,
NOT_EQ = EQ | NOT,
DEVISABLE_BY = 0x05,
VOID
} op = VOID;
while( isspace(**iterator) ) ++(*iterator); // skip whitespace
switch ( (*iterator)[0] ) {
default: op = EQ; ++(*iterator); break;
case '\0': throw std::runtime_error(GETPOT_STR_REACHED_END_OF_CONSTRAINT + " " +
+ GETPOT_STR_VALUE + ": \'" + Value + "\'.");
case '>': op = GREATER; ++(*iterator); break;
case '<': op = LESS; ++(*iterator); break;
case '%': op = DEVISABLE_BY; ++(*iterator); break;
case '!': op = NOT; ++(*iterator); break;
case '\'': return __constrain_check_EQUAL_STRING(Value.c_str(), iterator);
case '(': {
++(*iterator);
bool result = __constraint_check_OR(Value, iterator);
while( isspace(**iterator) ) ++(*iterator); // skip whitespace
if( **iterator != ')' )
throw std::runtime_error(std::string("Error while processing the file \"")
+ filename + "\": a bracket is missing in a constraint.");
++(*iterator);
return result;
}
}
if( (*iterator)[0] == '=' ) {
if( op == VOID ) throw std::runtime_error(std::string("Syntax error found in a constraint")
+ "string while processing the file \""
+ filename + "\".");
else {
op = (Operator) (EQ | op);
++(*iterator);
}
}
else if( op == VOID ) throw std::runtime_error(std::string("Syntax error found in a constraint")
+ "string while processing the file \""
+ filename + "\".");
if( op == NOT ) {
return ! __constraint_check_AND(Value, iterator);
}
while( isspace(**iterator) ) ++(*iterator); // skip whitespace
// Conversions to double.
double value_numeric = -1.0;
double cmp_numeric = -1.0;
int result = 0;
result = sscanf(Value.c_str(),"%lf", &value_numeric);
if( result == 0 || result == EOF ) return false;
result = sscanf(*iterator,"%lf", &cmp_numeric);
if( result == 0 || result == EOF ) return false;
// Skip until whitespace or closing bracket.
while( !isspace(**iterator) && (*iterator)[0] != ')' ) ++(*iterator);
while( isspace(**iterator) ) ++(*iterator); // skip whitespace
switch( op ) {
case GREATER: return value_numeric > cmp_numeric;
case GREATER_EQ: return value_numeric >= cmp_numeric;
case LESS: return value_numeric < cmp_numeric;
case LESS_EQ: return value_numeric <= cmp_numeric;
case NOT_EQ: return value_numeric != cmp_numeric;
case EQ: return value_numeric == cmp_numeric;
case DEVISABLE_BY: return (value_numeric / cmp_numeric) == double(int(value_numeric / cmp_numeric));
case NOT: throw std::runtime_error(std::string("Syntax error found in a constraint")
+ "string while processing the file \""
+ filename + "\".");
case VOID: throw std::runtime_error(std::string("Syntax error found in a constraint")
+ "string while processing the file \""
+ filename + "\".");
}
throw std::runtime_error(std::string("Syntax error found in a constraint")
+ "string while processing the file \""
+ filename + "\".");
}
///////////////////////////////////////////////////////////////////////////////
// (*) variable class
//.............................................................................
//
__GETPOT_INLINE
GetPot::variable::variable()
{}
__GETPOT_INLINE
GetPot::variable::variable(const variable& That)
{
#ifdef WIN32
operator=(That);
#else
GetPot::variable::operator=(That);
#endif
}
__GETPOT_INLINE
GetPot::variable::variable(const std::string& Name, const std::string& Value, const std::string& FieldSeparator)
: name(Name)
{
// make a copy of the 'Value'
take(Value, FieldSeparator);
}
__GETPOT_INLINE const std::string*
GetPot::variable::get_element(unsigned Idx, bool ThrowExceptionF /* = GETPOT_SETTING_THROW_EXCEPTION_ON_DEFAULT */) const
{
if( Idx < value.size() ) return &(value[Idx]);
if( ThrowExceptionF ) {
std::string msg;
char tmp[64];
msg += std::string(GETPOT_STR_VARIABLE) + "\'";
msg += name + "\' ";
GETPOT_SNPRINTF(tmp, 64, "%i", (int)Idx);
msg += std::string(GETPOT_STR_DOES_NOT_CONTAIN_ELEMENT) + ": \'" + tmp + "\'";
msg += ".";
throw std::runtime_error(msg);
}
else {
return 0x0;
}
}
__GETPOT_INLINE void
GetPot::variable::take(const std::string& Value, const std::string& FieldSeparator)
{
using namespace std;
original = Value;
// separate string by white space delimiters using 'strtok'
// thread safe usage of strtok (no static members)
# ifdef GETPOT_STRTOK_3_ARGS
char* spt = 0;
# endif
// make a copy of the 'Value'
char* copy = new char[Value.length()+1];
strcpy(copy, Value.c_str());
char* follow_token = GETPOT_STRTOK(copy, FieldSeparator.c_str(), &spt);
if( value.size() != 0 ) value.erase(value.begin(), value.end());
while(follow_token != 0) {
value.push_back(std::string(follow_token));
follow_token = GETPOT_STRTOK(NULL, FieldSeparator.c_str(), &spt);
}
delete [] copy;
}
__GETPOT_INLINE
GetPot::variable::~variable()
{}
__GETPOT_INLINE GetPot::variable&
GetPot::variable::operator=(const GetPot::variable& That)
{
if( &That != this) {
name = That.name;
value = That.value;
original = That.original;
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// (*) useful functions
//.............................................................................
//
__GETPOT_INLINE std::string GetPot::__double2string(const double& Value) const {
// -- converts a double integer into a string
char* tmp = new char[128];
GETPOT_SNPRINTF(tmp, (int)sizeof(char)*128, "%e", Value);
std::string result(tmp);
delete [] tmp;
return result;
}
__GETPOT_INLINE std::string GetPot::__int2string(const int& Value) const {
// -- converts an integer into a string
char* tmp = new char[128];
GETPOT_SNPRINTF(tmp, (int)sizeof(char)*128, "%i", Value);
std::string result(tmp);
delete [] tmp;
return result;
}
__GETPOT_INLINE STRING_VECTOR GetPot::__get_section_tree(const std::string& FullPath) {
// -- cuts a variable name into a tree of sub-sections. this is requested for recording
// requested sections when dealing with 'ufo' detection.
STRING_VECTOR result;
for(std::size_t i=0; i<FullPath.length(); ++i) {
if( FullPath[i] == '/' ) {
result.push_back(FullPath.substr(0, i));
}
}
return result;
}
#undef victorate
#ifdef GETPOT_SETTING_NAMESPACE
} // namespace GetPotNamespace.
#endif
#endif // __INCLUDE_GUARD_GETPOT_CPP__
| 34.429925 | 135 | 0.577358 | [
"object",
"vector"
] |
02e54f136efafbe70affb208aa93ba5dc3b30ed9 | 4,735 | hpp | C++ | include/eve/detail/function/simd/x86/compress_store_swizzle_mask_num.hpp | microblink/eve | 26d50d59190d3e2817c3ca95614e3e74f6c6f30a | [
"MIT"
] | null | null | null | include/eve/detail/function/simd/x86/compress_store_swizzle_mask_num.hpp | microblink/eve | 26d50d59190d3e2817c3ca95614e3e74f6c6f30a | [
"MIT"
] | null | null | null | include/eve/detail/function/simd/x86/compress_store_swizzle_mask_num.hpp | microblink/eve | 26d50d59190d3e2817c3ca95614e3e74f6c6f30a | [
"MIT"
] | null | null | null | //==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/function/convert.hpp>
namespace eve::detail
{
template<eve::relative_conditional_expr C, typename T>
EVE_FORCEINLINE std::pair<int, bool>
compress_store_swizzle_mask_num_partial_(EVE_SUPPORTS(sse2_), C c, logical<wide<T, fixed<4>>> mask)
requires (current_api < avx512) && (sizeof(T) == 2)
{
static_assert(top_bits<logical<wide<T, fixed<4>>>>::bits_per_element == 2);
auto to_bytes = eve::convert(mask, eve::as<eve::logical<std::uint8_t>>{});
return compress_store_swizzle_mask_num_partial(c, to_bytes);
}
template<eve::relative_conditional_expr C, typename T>
EVE_FORCEINLINE std::pair<int, int>
compress_store_swizzle_mask_num_(EVE_SUPPORTS(sse2_), C c, logical<wide<T, fixed<4>>> mask)
requires (current_api < avx512) && (sizeof(T) == 2)
{
static_assert(top_bits<logical<wide<T, fixed<4>>>>::bits_per_element == 2);
auto to_bytes = eve::convert(mask, eve::as<eve::logical<std::uint8_t>>{});
return compress_store_swizzle_mask_num(c, to_bytes);
}
template<typename T>
EVE_FORCEINLINE std::pair<int, int>
compress_store_swizzle_mask_num_(EVE_SUPPORTS(sse2_), logical<wide<T, fixed<8>>> mask)
requires (current_api < avx512)
{
// aggregated
if constexpr ( eve::has_aggregated_abi_v<wide<T, fixed<8>>> )
{
using half_t = make_integer_t<sizeof(T) / 2, unsigned>;
auto half = eve::convert(mask, eve::as<logical<half_t>>{});
return compress_store_swizzle_mask_num(half);
}
else if constexpr ( sizeof(T) == 4 )
{
// Get 4 bits per integer
// We want 1 + 1 + 3 + 3 + 9 + 9
// We can almost achieve this with popcount
// 0001 for 1
// 0111 for 3
// Can't do 9.
// But we can mask and add
//
// sum from popcount: [ 1, 1, 3, 3, 4, 1]
// sum from extra mask: [ 0, 0, 0, 0, 5, 8]
using u8_32 = typename wide<T, fixed<8>>::template rebind<std::uint8_t, eve::fixed<32>>;
auto as_bytes = eve::bit_cast(mask, as<logical<u8_32>>{});
std::uint32_t mmask = top_bits{as_bytes}.as_int();
std::uint32_t idx_base_3 = std::popcount(mmask & 0x001f7711);
std::uint32_t extra_mask = (mmask >> 17) & 0b1'101;
idx_base_3 += extra_mask;
return {(int)idx_base_3, std::popcount(mmask) / 4};
}
else if constexpr ( sizeof(T) == 2 )
{
// Alternative for shorts is to compute both halves
// But that implies using _mm_extract_epi16 which has latency 3
// as oppose to latency 1 for _mm_packs_epi16
auto to_bytes = eve::convert(mask, eve::as<eve::logical<std::uint8_t>>{});
return compress_store_swizzle_mask_num(to_bytes);
}
else if constexpr ( sizeof(T) == 1 )
{
// The problem is there is not really a good instruction to reduce 8 chars.
// The closest we come is `_mm_sad_epu8`, it sums absolute differences for bytes.
// We could use a zero mask.
// But instead we can use the same mask we got to mask the 1, 3, 9.
// The top is responisble for popcount.
__m128i sad_mask = _mm_set_epi64x(0, 0x8080898983838181);
__m128i sum = _mm_sad_epu8(_mm_andnot_si128(mask, sad_mask), sad_mask);
int desc = _mm_cvtsi128_si32(sum);
int num = desc & 0x1f;
int popcount = desc >> 7;
return {num, popcount};
}
}
template<typename T>
EVE_FORCEINLINE auto
compress_store_swizzle_mask_num_(EVE_SUPPORTS(sse2_), logical<wide<T, fixed<16>>> mask)
requires (current_api < avx512) && x86_abi<abi_t<T, fixed<16>>> // For aggregated 16 elements
// just do the base case.
{
if constexpr ( sizeof(T) == 2 )
{
auto to_bytes = eve::convert(mask, eve::as<eve::logical<std::uint8_t>>{});
return compress_store_swizzle_mask_num(to_bytes);
}
else if constexpr ( sizeof(T) == 1 )
{
__m128i sad_mask = _mm_set_epi64x(0x8080898983838181, 0x8080898983838181);
__m128i sum = _mm_sad_epu8(_mm_andnot_si128(mask, sad_mask), sad_mask);
int desc_lo = _mm_cvtsi128_si32(sum);
int desc_hi = _mm_extract_epi16(sum, 4);
struct res {
int l_num;
int l_count;
int h_num;
int h_count;
};
return res {
desc_lo & 0x1f,
desc_lo >> 7,
desc_hi & 0x1f,
desc_hi >> 7
};
}
}
}
| 35.871212 | 101 | 0.605069 | [
"vector"
] |
02eac47b8bd0388ce22fdaf9c919e6abda49b301 | 2,672 | cpp | C++ | libcaf_net/src/net/middleman.cpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | libcaf_net/src/net/middleman.cpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | libcaf_net/src/net/middleman.cpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#include "caf/net/middleman.hpp"
#include "caf/actor_system_config.hpp"
#include "caf/detail/set_thread_name.hpp"
#include "caf/expected.hpp"
#include "caf/raise_error.hpp"
#include "caf/sec.hpp"
#include "caf/send.hpp"
#include "caf/uri.hpp"
namespace caf::net {
void middleman::init_global_meta_objects() {
// nop
}
middleman::middleman(actor_system& sys) : sys_(sys), mpx_(this) {
// nop
}
middleman::~middleman() {
// nop
}
void middleman::start() {
if (!get_or(config(), "caf.middleman.manual-multiplexing", false)) {
mpx_thread_ = sys_.launch_thread("caf.net.mpx", [this] {
mpx_.set_thread_id();
mpx_.run();
});
} else {
mpx_.set_thread_id();
}
}
void middleman::stop() {
mpx_.shutdown();
if (mpx_thread_.joinable())
mpx_thread_.join();
else
mpx_.run();
}
void middleman::init(actor_system_config& cfg) {
if (auto err = mpx_.init()) {
CAF_LOG_ERROR("mpx_.init() failed: " << err);
CAF_RAISE_ERROR("mpx_.init() failed");
}
if (auto node_uri = get_if<uri>(&cfg, "caf.middleman.this-node")) {
auto this_node = make_node_id(std::move(*node_uri));
sys_.node_.swap(this_node);
} else {
// CAF_RAISE_ERROR("no valid entry for caf.middleman.this-node found");
}
}
middleman::module::id_t middleman::id() const {
return module::network_manager;
}
void* middleman::subtype_ptr() {
return this;
}
actor_system::module* middleman::make(actor_system& sys, detail::type_list<>) {
return new middleman(sys);
}
void middleman::add_module_options(actor_system_config& cfg) {
config_option_adder{cfg.custom_options(), "caf.middleman"}
.add<std::vector<std::string>>("app-identifiers",
"valid application identifiers of this node")
.add<uri>("this-node", "locator of this CAF node")
.add<size_t>("max-consecutive-reads",
"max. number of consecutive reads per broker")
.add<bool>("manual-multiplexing",
"disables background activity of the multiplexer")
.add<size_t>("workers", "number of deserialization workers")
.add<timespan>("heartbeat-interval", "interval of heartbeat messages")
.add<timespan>("connection-timeout",
"max. time between messages before declaring a node dead "
"(disabled if 0, ignored if heartbeats are disabled)")
.add<std::string>("network-backend", "legacy option");
}
} // namespace caf::net
| 29.362637 | 80 | 0.668039 | [
"vector"
] |
02ef30d96f8a50c89554f2ef02cf5e04ee855994 | 15,999 | hpp | C++ | include/System/Guid.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Guid.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Guid.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.IFormattable
#include "System/IFormattable.hpp"
// Including type: System.IComparable
#include "System/IComparable.hpp"
// Including type: System.IComparable`1
#include "System/IComparable_1.hpp"
// Including type: System.IEquatable`1
#include "System/IEquatable_1.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: System
namespace System {
// Forward declaring type: IFormatProvider
class IFormatProvider;
}
// Forward declaring namespace: System::Security::Cryptography
namespace System::Security::Cryptography {
// Forward declaring type: RandomNumberGenerator
class RandomNumberGenerator;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Size: 0x10
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: System.Guid
// [ComVisibleAttribute] Offset: D7A830
struct Guid/*, public System::ValueType, public System::IFormattable, public System::IComparable, public System::IComparable_1<System::Guid>, public System::IEquatable_1<System::Guid>*/ {
public:
// Nested type: System::Guid::GuidStyles
struct GuidStyles;
// Nested type: System::Guid::GuidParseThrowStyle
struct GuidParseThrowStyle;
// Nested type: System::Guid::ParseFailureKind
struct ParseFailureKind;
// Nested type: System::Guid::GuidResult
struct GuidResult;
// private System.Int32 _a
// Size: 0x4
// Offset: 0x0
int a;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int16 _b
// Size: 0x2
// Offset: 0x4
int16_t b;
// Field size check
static_assert(sizeof(int16_t) == 0x2);
// private System.Int16 _c
// Size: 0x2
// Offset: 0x6
int16_t c;
// Field size check
static_assert(sizeof(int16_t) == 0x2);
// private System.Byte _d
// Size: 0x1
// Offset: 0x8
uint8_t d;
// Field size check
static_assert(sizeof(uint8_t) == 0x1);
// private System.Byte _e
// Size: 0x1
// Offset: 0x9
uint8_t e;
// Field size check
static_assert(sizeof(uint8_t) == 0x1);
// private System.Byte _f
// Size: 0x1
// Offset: 0xA
uint8_t f;
// Field size check
static_assert(sizeof(uint8_t) == 0x1);
// private System.Byte _g
// Size: 0x1
// Offset: 0xB
uint8_t g;
// Field size check
static_assert(sizeof(uint8_t) == 0x1);
// private System.Byte _h
// Size: 0x1
// Offset: 0xC
uint8_t h;
// Field size check
static_assert(sizeof(uint8_t) == 0x1);
// private System.Byte _i
// Size: 0x1
// Offset: 0xD
uint8_t i;
// Field size check
static_assert(sizeof(uint8_t) == 0x1);
// private System.Byte _j
// Size: 0x1
// Offset: 0xE
uint8_t j;
// Field size check
static_assert(sizeof(uint8_t) == 0x1);
// private System.Byte _k
// Size: 0x1
// Offset: 0xF
uint8_t k;
// Field size check
static_assert(sizeof(uint8_t) == 0x1);
// Creating value type constructor for type: Guid
constexpr Guid(int a_ = {}, int16_t b_ = {}, int16_t c_ = {}, uint8_t d_ = {}, uint8_t e_ = {}, uint8_t f_ = {}, uint8_t g_ = {}, uint8_t h_ = {}, uint8_t i_ = {}, uint8_t j_ = {}, uint8_t k_ = {}) noexcept : a{a_}, b{b_}, c{c_}, d{d_}, e{e_}, f{f_}, g{g_}, h{h_}, i{i_}, j{j_}, k{k_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Creating interface conversion operator: operator System::IFormattable
operator System::IFormattable() noexcept {
return *reinterpret_cast<System::IFormattable*>(this);
}
// Creating interface conversion operator: operator System::IComparable
operator System::IComparable() noexcept {
return *reinterpret_cast<System::IComparable*>(this);
}
// Creating interface conversion operator: operator System::IComparable_1<System::Guid>
operator System::IComparable_1<System::Guid>() noexcept {
return *reinterpret_cast<System::IComparable_1<System::Guid>*>(this);
}
// Creating interface conversion operator: operator System::IEquatable_1<System::Guid>
operator System::IEquatable_1<System::Guid>() noexcept {
return *reinterpret_cast<System::IEquatable_1<System::Guid>*>(this);
}
// Get static field: static public readonly System.Guid Empty
static System::Guid _get_Empty();
// Set static field: static public readonly System.Guid Empty
static void _set_Empty(System::Guid value);
// Get static field: static private System.Object _rngAccess
static ::Il2CppObject* _get__rngAccess();
// Set static field: static private System.Object _rngAccess
static void _set__rngAccess(::Il2CppObject* value);
// Get static field: static private System.Security.Cryptography.RandomNumberGenerator _rng
static System::Security::Cryptography::RandomNumberGenerator* _get__rng();
// Set static field: static private System.Security.Cryptography.RandomNumberGenerator _rng
static void _set__rng(System::Security::Cryptography::RandomNumberGenerator* value);
// Get static field: static private System.Security.Cryptography.RandomNumberGenerator _fastRng
static System::Security::Cryptography::RandomNumberGenerator* _get__fastRng();
// Set static field: static private System.Security.Cryptography.RandomNumberGenerator _fastRng
static void _set__fastRng(System::Security::Cryptography::RandomNumberGenerator* value);
// public System.Void .ctor(System.Byte[] b)
// Offset: 0xF02694
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
Guid(::Array<uint8_t>* b) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Guid::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(b)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, b);
}
// public System.Void .ctor(System.Int32 a, System.Int16 b, System.Int16 c, System.Byte[] d)
// Offset: 0xF0269C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
Guid(int a, int16_t b, int16_t c, ::Array<uint8_t>* d) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Guid::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(a), ::il2cpp_utils::ExtractType(b), ::il2cpp_utils::ExtractType(c), ::il2cpp_utils::ExtractType(d)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, a, b, c, d);
}
// public System.Void .ctor(System.Int32 a, System.Int16 b, System.Int16 c, System.Byte d, System.Byte e, System.Byte f, System.Byte g, System.Byte h, System.Byte i, System.Byte j, System.Byte k)
// Offset: 0xF026A4
// template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
// ABORTED: conflicts with another method. Guid(int a, int16_t b, int16_t c, uint8_t d, uint8_t e, uint8_t f, uint8_t g, uint8_t h, uint8_t i, uint8_t j, uint8_t k)
// public System.Void .ctor(System.String g)
// Offset: 0xF026E4
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
Guid(::Il2CppString* g) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Guid::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(g)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, g);
}
// static public System.Guid Parse(System.String input)
// Offset: 0x19E5D20
static System::Guid Parse(::Il2CppString* input);
// static public System.Boolean TryParse(System.String input, out System.Guid result)
// Offset: 0x19E5E28
static bool TryParse(::Il2CppString* input, System::Guid& result);
// static private System.Boolean TryParseGuid(System.String g, System.Guid/GuidStyles flags, ref System.Guid/GuidResult result)
// Offset: 0x19E5904
static bool TryParseGuid(::Il2CppString* g, System::Guid::GuidStyles flags, System::Guid::GuidResult& result);
// static private System.Boolean TryParseGuidWithHexPrefix(System.String guidString, ref System.Guid/GuidResult result)
// Offset: 0x19E629C
static bool TryParseGuidWithHexPrefix(::Il2CppString* guidString, System::Guid::GuidResult& result);
// static private System.Boolean TryParseGuidWithNoStyle(System.String guidString, ref System.Guid/GuidResult result)
// Offset: 0x19E6820
static bool TryParseGuidWithNoStyle(::Il2CppString* guidString, System::Guid::GuidResult& result);
// static private System.Boolean TryParseGuidWithDashes(System.String guidString, ref System.Guid/GuidResult result)
// Offset: 0x19E5F28
static bool TryParseGuidWithDashes(::Il2CppString* guidString, System::Guid::GuidResult& result);
// static private System.Boolean StringToShort(System.String str, System.Int32 requiredLength, System.Int32 flags, out System.Int16 result, ref System.Guid/GuidResult parseResult)
// Offset: 0x19E6EBC
static bool StringToShort(::Il2CppString* str, int requiredLength, int flags, int16_t& result, System::Guid::GuidResult& parseResult);
// static private System.Boolean StringToShort(System.String str, System.Int32* parsePos, System.Int32 requiredLength, System.Int32 flags, out System.Int16 result, ref System.Guid/GuidResult parseResult)
// Offset: 0x19E708C
static bool StringToShort(::Il2CppString* str, int* parsePos, int requiredLength, int flags, int16_t& result, System::Guid::GuidResult& parseResult);
// static private System.Boolean StringToInt(System.String str, System.Int32 requiredLength, System.Int32 flags, out System.Int32 result, ref System.Guid/GuidResult parseResult)
// Offset: 0x19E6E24
static bool StringToInt(::Il2CppString* str, int requiredLength, int flags, int& result, System::Guid::GuidResult& parseResult);
// static private System.Boolean StringToInt(System.String str, ref System.Int32 parsePos, System.Int32 requiredLength, System.Int32 flags, out System.Int32 result, ref System.Guid/GuidResult parseResult)
// Offset: 0x19E6FE8
static bool StringToInt(::Il2CppString* str, int& parsePos, int requiredLength, int flags, int& result, System::Guid::GuidResult& parseResult);
// static private System.Boolean StringToInt(System.String str, System.Int32* parsePos, System.Int32 requiredLength, System.Int32 flags, out System.Int32 result, ref System.Guid/GuidResult parseResult)
// Offset: 0x19E7148
static bool StringToInt(::Il2CppString* str, int* parsePos, int requiredLength, int flags, int& result, System::Guid::GuidResult& parseResult);
// static private System.Boolean StringToLong(System.String str, ref System.Int32 parsePos, System.Int32 flags, out System.Int64 result, ref System.Guid/GuidResult parseResult)
// Offset: 0x19E6F54
static bool StringToLong(::Il2CppString* str, int& parsePos, int flags, int64_t& result, System::Guid::GuidResult& parseResult);
// static private System.Boolean StringToLong(System.String str, System.Int32* parsePos, System.Int32 flags, out System.Int64 result, ref System.Guid/GuidResult parseResult)
// Offset: 0x19E7368
static bool StringToLong(::Il2CppString* str, int* parsePos, int flags, int64_t& result, System::Guid::GuidResult& parseResult);
// static private System.String EatAllWhitespace(System.String str)
// Offset: 0x19E6BF0
static ::Il2CppString* EatAllWhitespace(::Il2CppString* str);
// static private System.Boolean IsHexPrefix(System.String str, System.Int32 i)
// Offset: 0x19E6D08
static bool IsHexPrefix(::Il2CppString* str, int i);
// public System.Byte[] ToByteArray()
// Offset: 0xF026EC
::Array<uint8_t>* ToByteArray();
// public System.Boolean Equals(System.Guid g)
// Offset: 0xF0272C
bool Equals(System::Guid g);
// private System.Int32 GetResult(System.UInt32 me, System.UInt32 them)
// Offset: 0xF02734
int GetResult(uint me, uint them);
// public System.Int32 CompareTo(System.Object value)
// Offset: 0xF02744
int CompareTo(::Il2CppObject* value);
// public System.Int32 CompareTo(System.Guid value)
// Offset: 0xF0274C
int CompareTo(System::Guid value);
// public System.String ToString(System.String format)
// Offset: 0xF02754
::Il2CppString* ToString(::Il2CppString* format);
// static private System.Char HexToChar(System.Int32 a)
// Offset: 0x19E821C
static ::Il2CppChar HexToChar(int a);
// static private System.Int32 HexsToChars(System.Char* guidChars, System.Int32 offset, System.Int32 a, System.Int32 b)
// Offset: 0x19E8238
static int HexsToChars(::Il2CppChar* guidChars, int offset, int a, int b);
// static private System.Int32 HexsToChars(System.Char* guidChars, System.Int32 offset, System.Int32 a, System.Int32 b, System.Boolean hex)
// Offset: 0x19E82C8
static int HexsToChars(::Il2CppChar* guidChars, int offset, int a, int b, bool hex);
// public System.String ToString(System.String format, System.IFormatProvider provider)
// Offset: 0xF0275C
::Il2CppString* ToString(::Il2CppString* format, System::IFormatProvider* provider);
// static public System.Guid NewGuid()
// Offset: 0x19E842C
static System::Guid NewGuid();
// static private System.Void .cctor()
// Offset: 0x19E85EC
static void _cctor();
// public override System.String ToString()
// Offset: 0xF026F4
// Implemented from: System.ValueType
// Base method: System.String ValueType::ToString()
::Il2CppString* ToString();
// public override System.Int32 GetHashCode()
// Offset: 0xF026FC
// Implemented from: System.ValueType
// Base method: System.Int32 ValueType::GetHashCode()
int GetHashCode();
// public override System.Boolean Equals(System.Object o)
// Offset: 0xF02724
// Implemented from: System.ValueType
// Base method: System.Boolean ValueType::Equals(System.Object o)
bool Equals(::Il2CppObject* o);
}; // System.Guid
#pragma pack(pop)
static check_size<sizeof(Guid), 15 + sizeof(uint8_t)> __System_GuidSizeCheck;
static_assert(sizeof(Guid) == 0x10);
// static public System.Boolean op_Equality(System.Guid a, System.Guid b)
// Offset: 0x19E80D4
bool operator ==(const System::Guid& a, const System::Guid& b);
// static public System.Boolean op_Inequality(System.Guid a, System.Guid b)
// Offset: 0x19E8180
bool operator !=(const System::Guid& a, const System::Guid& b);
}
DEFINE_IL2CPP_ARG_TYPE(System::Guid, "System", "Guid");
| 54.979381 | 292 | 0.701231 | [
"object",
"vector"
] |
02f7d29f435b61c8895ebdeb2de7914d66e09935 | 2,641 | inl | C++ | Source Code/AsTeRICS/ARE/components/sensor.eyex/src/main/c++/include/eyex-cpp/InteractionEvent.inl | EliKabasele/openHAB_MyUI | f6c66a42cca24a484c2bd4013b20b05edaa88161 | [
"Apache-2.0"
] | 2 | 2020-05-19T09:48:20.000Z | 2020-07-14T14:37:45.000Z | Source Code/AsTeRICS/ARE/components/sensor.eyex/src/main/c++/include/eyex-cpp/InteractionEvent.inl | EliKabasele/openHAB_MyUI | f6c66a42cca24a484c2bd4013b20b05edaa88161 | [
"Apache-2.0"
] | 1 | 2016-12-01T15:26:24.000Z | 2016-12-01T18:05:09.000Z | Source Code/AsTeRICS/ARE/components/sensor.eyex/src/main/c++/include/eyex-cpp/InteractionEvent.inl | EliKabasele/openHAB_MyUI | f6c66a42cca24a484c2bd4013b20b05edaa88161 | [
"Apache-2.0"
] | 1 | 2020-12-16T02:55:54.000Z | 2020-12-16T02:55:54.000Z | /*********************************************************************************************************************
* Copyright 2013-2014 Tobii Technology AB. All rights reserved.
* InteractionEvent.inl
*********************************************************************************************************************/
#if !defined(__TOBII_TX_CLIENT_CPPBINDINGS_INTERACTIONEVENT__INL__)
#define __TOBII_TX_CLIENT_CPPBINDINGS_INTERACTIONEVENT__INL__
/*********************************************************************************************************************/
TX_NAMESPACE_BEGIN
/*********************************************************************************************************************/
inline InteractionEvent::InteractionEvent(const std::shared_ptr<const Context>& spContext, TX_HANDLE hEvent)
: InteractionObject(spContext, hEvent)
{}
/*********************************************************************************************************************/
inline std::string InteractionEvent::GetInteractorId() const
{
return GetString(txGetEventInteractorId, _hObject);
}
/*********************************************************************************************************************/
inline std::vector<std::shared_ptr<Behavior>> InteractionEvent::GetBehaviors() const
{
std::vector<Tx::Utils::ScopedHandle> behaviorHandles;
TX_VALIDATE(Tx::Utils::GetBufferData(behaviorHandles, txGetEventBehaviors, _hObject));
std::vector<std::shared_ptr<Behavior>> behaviors;
for(auto& hBehavior : behaviorHandles)
{
auto spBehavior = _spContext->CreateObject<Behavior>(hBehavior);
behaviors.push_back(spBehavior);
}
return behaviors;
}
/*********************************************************************************************************************/
inline bool InteractionEvent::TryGetBehavior(std::shared_ptr<Behavior>* pspBehavior, TX_BEHAVIORTYPE behaviorType) const
{
Tx::Utils::ScopedHandle hBehavior;
if(!TX_VALIDATE(txGetEventBehavior(_hObject, &hBehavior, behaviorType), TX_RESULT_NOTFOUND))
return false;
*pspBehavior = _spContext->CreateObject<Behavior>(hBehavior);
return true;
}
/*********************************************************************************************************************/
TX_NAMESPACE_END
/*********************************************************************************************************************/
#endif // !defined(__TOBII_TX_CLIENT_CPPBINDINGS_INTERACTIONEVENT__INL__)
/*********************************************************************************************************************/
| 41.265625 | 120 | 0.432412 | [
"vector"
] |
02f8d0b421df49d7039719483d0175895497e485 | 1,128 | cpp | C++ | src/D3D/VertexLayout.cpp | razerx100/GaiaX | 6bf8fb1da9e2a60b43736742fb6f4c56b1f5f315 | [
"MIT"
] | null | null | null | src/D3D/VertexLayout.cpp | razerx100/GaiaX | 6bf8fb1da9e2a60b43736742fb6f4c56b1f5f315 | [
"MIT"
] | null | null | null | src/D3D/VertexLayout.cpp | razerx100/GaiaX | 6bf8fb1da9e2a60b43736742fb6f4c56b1f5f315 | [
"MIT"
] | null | null | null | #include <VertexLayout.hpp>
static const std::vector<const char*> vertexElementTypeNameMap{
"Position",
"UV"
};
static const std::vector<DXGI_FORMAT> vertexElementTypeFormatMap{
DXGI_FORMAT_R32G32B32_FLOAT,
DXGI_FORMAT_R32G32_FLOAT
};
static const std::vector<size_t> vertexElementTypeSizeMap{
12u,
8u
};
VertexLayout::VertexLayout(const std::vector<VertexElementType>& inputLayout) noexcept {
InitLayout(inputLayout);
}
D3D12_INPUT_LAYOUT_DESC VertexLayout::GetLayout() const noexcept {
return {
m_inputDescs.data(),
static_cast<UINT>(m_inputDescs.size())
};
}
void VertexLayout::InitLayout(const std::vector<VertexElementType>& inputLayout) noexcept {
for (size_t inputOffset = 0u; VertexElementType elementType : inputLayout) {
auto elementTypeId = static_cast<size_t>(elementType);
m_inputDescs.emplace_back(
vertexElementTypeNameMap[elementTypeId], 0u,
vertexElementTypeFormatMap[elementTypeId], 0u,
static_cast<UINT>(inputOffset), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0u
);
inputOffset += vertexElementTypeSizeMap[elementTypeId];
}
}
| 26.857143 | 92 | 0.759752 | [
"vector"
] |
02fa787a479202c796ee9e3038eb09d2a6f0a9e4 | 10,912 | cc | C++ | src/xenia/base/logging.cc | EmulationChannel/xenia-1 | d58dcf71123e216e8d933751a37d45da1d16932b | [
"BSD-3-Clause"
] | 262 | 2019-08-17T08:27:30.000Z | 2022-03-29T02:36:04.000Z | src/xenia/base/logging.cc | EmulationChannel/xenia-1 | d58dcf71123e216e8d933751a37d45da1d16932b | [
"BSD-3-Clause"
] | 33 | 2019-08-18T09:39:40.000Z | 2022-03-31T20:47:39.000Z | src/xenia/base/logging.cc | EmulationChannel/xenia-1 | d58dcf71123e216e8d933751a37d45da1d16932b | [
"BSD-3-Clause"
] | 141 | 2019-09-06T01:37:01.000Z | 2022-03-23T23:39:05.000Z | /**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2020 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include <atomic>
#include <mutex>
#include <vector>
#include "third_party/disruptorplus/include/disruptorplus/multi_threaded_claim_strategy.hpp"
#include "third_party/disruptorplus/include/disruptorplus/ring_buffer.hpp"
#include "third_party/disruptorplus/include/disruptorplus/sequence_barrier.hpp"
#include "third_party/disruptorplus/include/disruptorplus/spin_wait_strategy.hpp"
#include "xenia/base/atomic.h"
#include "xenia/base/cvar.h"
#include "xenia/base/debugging.h"
#include "xenia/base/filesystem.h"
#include "xenia/base/main.h"
#include "xenia/base/math.h"
#include "xenia/base/memory.h"
#include "xenia/base/ring_buffer.h"
#include "xenia/base/string.h"
#include "xenia/base/system.h"
#include "xenia/base/threading.h"
// For MessageBox:
// TODO(benvanik): generic API? logging_win.cc?
#if XE_PLATFORM_WIN32
#include "xenia/base/platform_win.h"
#endif // XE_PLATFORM_WIN32
#include "third_party/fmt/include/fmt/format.h"
DEFINE_path(log_file, "", "Logs are written to the given file", "Logging");
DEFINE_bool(log_to_stdout, true, "Write log output to stdout", "Logging");
DEFINE_bool(log_to_debugprint, false, "Dump the log to DebugPrint.", "Logging");
DEFINE_bool(flush_log, true, "Flush log file after each log line batch.",
"Logging");
DEFINE_int32(
log_level, 2,
"Maximum level to be logged. (0=error, 1=warning, 2=info, 3=debug)",
"Logging");
namespace dp = disruptorplus;
namespace xe {
class Logger;
Logger* logger_ = nullptr;
struct LogLine {
size_t buffer_length;
uint32_t thread_id;
uint16_t _pad_0; // (2b) padding
bool terminate;
char prefix_char;
};
thread_local char thread_log_buffer_[64 * 1024];
void FileLogSink::Write(const char* buf, size_t size) {
if (file_) {
fwrite(buf, 1, size, file_);
}
}
void FileLogSink::Flush() {
if (file_) {
fflush(file_);
}
}
class Logger {
public:
explicit Logger(const std::string_view app_name)
: wait_strategy_(),
claim_strategy_(kBlockCount, wait_strategy_),
consumed_(wait_strategy_) {
claim_strategy_.add_claim_barrier(consumed_);
write_thread_ =
xe::threading::Thread::Create({}, [this]() { WriteThread(); });
write_thread_->set_name("Logging Writer");
}
~Logger() {
AppendLine(0, '\0', nullptr, 0, true); // append a terminator
xe::threading::Wait(write_thread_.get(), true);
}
void AddLogSink(std::unique_ptr<LogSink>&& sink) {
sinks_.push_back(std::move(sink));
}
private:
static const size_t kBufferSize = 8 * 1024 * 1024;
uint8_t buffer_[kBufferSize];
static const size_t kBlockSize = 256;
static const size_t kBlockCount = kBufferSize / kBlockSize;
static const size_t kBlockIndexMask = kBlockCount - 1;
static const size_t kClaimStrategyFootprint =
sizeof(std::atomic<dp::sequence_t>[kBlockCount]);
static size_t BlockOffset(dp::sequence_t sequence) {
return (sequence & kBlockIndexMask) * kBlockSize;
}
static size_t BlockCount(size_t byte_size) {
return (byte_size + (kBlockSize - 1)) / kBlockSize;
}
dp::spin_wait_strategy wait_strategy_;
dp::multi_threaded_claim_strategy<dp::spin_wait_strategy> claim_strategy_;
dp::sequence_barrier<dp::spin_wait_strategy> consumed_;
std::vector<std::unique_ptr<LogSink>> sinks_;
std::unique_ptr<xe::threading::Thread> write_thread_;
void Write(const char* buf, size_t size) {
for (const auto& sink : sinks_) {
sink->Write(buf, size);
}
if (cvars::log_to_debugprint) {
debugging::DebugPrint("{}", std::string_view(buf, size));
}
}
void WriteThread() {
RingBuffer rb(buffer_, kBufferSize);
size_t idle_loops = 0;
dp::sequence_t next_sequence = 0;
dp::sequence_t last_sequence = -1;
size_t desired_count = 1;
while (true) {
// We want one block to find out how many blocks we need or we know how
// many blocks needed for at least one log line.
auto next_range = dp::sequence_range(next_sequence, desired_count);
auto available_sequence = claim_strategy_.wait_until_published(
next_range.last(), last_sequence);
size_t read_count = 0;
auto available_range = next_range;
auto available_count = available_range.size();
rb.set_write_offset(BlockOffset(available_range.end()));
bool terminate = false;
for (size_t i = available_range.first(); i != available_range.end();) {
rb.set_read_offset(BlockOffset(i));
LogLine line;
rb.Read(&line, sizeof(line));
auto needed_count = BlockCount(sizeof(LogLine) + line.buffer_length);
if (read_count + needed_count > available_count) {
// More blocks are needed for a complete line.
desired_count = needed_count;
break;
} else {
// Enough blocks to read this log line, advance by that many.
read_count += needed_count;
i += needed_count;
if (line.prefix_char) {
char prefix[] = {
line.prefix_char,
'>',
' ',
'?', // Thread ID gets placed here (8 chars).
'?',
'?',
'?',
'?',
'?',
'?',
'?',
' ',
0,
};
fmt::format_to_n(prefix + 3, sizeof(prefix) - 3, "{:08X}",
line.thread_id);
Write(prefix, sizeof(prefix) - 1);
}
if (line.buffer_length) {
// Get access to the line data - which may be split in the ring
// buffer - and write it out in parts.
auto line_range = rb.BeginRead(line.buffer_length);
Write(reinterpret_cast<const char*>(line_range.first),
line_range.first_length);
if (line_range.second_length) {
Write(reinterpret_cast<const char*>(line_range.second),
line_range.second_length);
}
// Always ensure there is a newline.
char last_char =
line_range.second
? line_range.second[line_range.second_length - 1]
: line_range.first[line_range.first_length - 1];
if (last_char != '\n') {
const char suffix[1] = {'\n'};
Write(suffix, 1);
}
rb.EndRead(std::move(line_range));
} else {
// Always ensure there is a newline.
const char suffix[1] = {'\n'};
Write(suffix, 1);
}
if (line.terminate) {
terminate = true;
break;
}
}
}
if (terminate) {
break;
}
if (read_count) {
// Advance by the number of blocks we read.
auto read_range = dp::sequence_range(next_sequence, read_count);
next_sequence = read_range.end();
last_sequence = read_range.last();
consumed_.publish(last_sequence);
desired_count = 1;
if (cvars::flush_log) {
for (const auto& sink : sinks_) {
sink->Flush();
}
}
idle_loops = 0;
} else {
if (idle_loops >= 1000) {
// Introduce a waiting period.
xe::threading::Sleep(std::chrono::milliseconds(50));
} else {
idle_loops++;
}
}
}
}
public:
void AppendLine(uint32_t thread_id, const char prefix_char,
const char* buffer_data, size_t buffer_length,
bool terminate = false) {
size_t count = BlockCount(sizeof(LogLine) + buffer_length);
auto range = claim_strategy_.claim(count);
assert_true(range.size() == count);
RingBuffer rb(buffer_, kBufferSize);
rb.set_write_offset(BlockOffset(range.first()));
rb.set_read_offset(BlockOffset(range.end()));
LogLine line = {};
line.buffer_length = buffer_length;
line.thread_id = thread_id;
line.prefix_char = prefix_char;
line.terminate = terminate;
rb.Write(&line, sizeof(LogLine));
if (buffer_length) {
rb.Write(buffer_data, buffer_length);
}
claim_strategy_.publish(range);
}
};
void InitializeLogging(const std::string_view app_name) {
auto mem = memory::AlignedAlloc<Logger>(0x10);
logger_ = new (mem) Logger(app_name);
FILE* log_file = nullptr;
if (cvars::log_file.empty()) {
// Default to app name.
auto file_name = fmt::format("{}.log", app_name);
auto file_path = std::filesystem::path(file_name);
xe::filesystem::CreateParentFolder(file_path);
log_file = xe::filesystem::OpenFile(file_path, "wt");
} else {
xe::filesystem::CreateParentFolder(cvars::log_file);
log_file = xe::filesystem::OpenFile(cvars::log_file, "wt");
}
auto sink = std::make_unique<FileLogSink>(log_file);
logger_->AddLogSink(std::move(sink));
if (cvars::log_to_stdout) {
auto stdout_sink = std::make_unique<FileLogSink>(stdout);
logger_->AddLogSink(std::move(stdout_sink));
}
}
void ShutdownLogging() {
Logger* logger = logger_;
logger_ = nullptr;
logger->~Logger();
memory::AlignedFree(logger);
}
bool logging::internal::ShouldLog(LogLevel log_level) {
return logger_ != nullptr &&
static_cast<int32_t>(log_level) <= cvars::log_level;
}
std::pair<char*, size_t> logging::internal::GetThreadBuffer() {
return {thread_log_buffer_, sizeof(thread_log_buffer_)};
}
void logging::internal::AppendLogLine(LogLevel log_level,
const char prefix_char, size_t written) {
if (!ShouldLog(log_level) || !written) {
return;
}
logger_->AppendLine(xe::threading::current_thread_id(), prefix_char,
thread_log_buffer_, written);
}
void logging::AppendLogLine(LogLevel log_level, const char prefix_char,
const std::string_view str) {
if (!internal::ShouldLog(log_level) || !str.size()) {
return;
}
logger_->AppendLine(xe::threading::current_thread_id(), prefix_char,
str.data(), str.size());
}
void FatalError(const std::string_view str) {
logging::AppendLogLine(LogLevel::Error, 'X', str);
if (!xe::has_console_attached()) {
ShowSimpleMessageBox(SimpleMessageBoxType::Error, str);
}
ShutdownLogging();
std::exit(1);
}
} // namespace xe
| 29.814208 | 92 | 0.609696 | [
"vector"
] |
02fffad521dbbc0632f38db514ca086465e5fdcc | 4,366 | hpp | C++ | include/albatross/src/models/least_squares.hpp | swift-nav/albatross | 54f2edec3f19149f04a2e2e3bbb0b05aba7faba6 | [
"MIT"
] | 15 | 2018-04-10T02:05:06.000Z | 2022-02-07T23:33:27.000Z | include/albatross/src/models/least_squares.hpp | swift-nav/albatross | 54f2edec3f19149f04a2e2e3bbb0b05aba7faba6 | [
"MIT"
] | 79 | 2018-04-19T20:36:18.000Z | 2021-08-04T16:21:19.000Z | include/albatross/src/models/least_squares.hpp | swift-nav/albatross | 54f2edec3f19149f04a2e2e3bbb0b05aba7faba6 | [
"MIT"
] | 4 | 2018-04-06T03:12:16.000Z | 2020-09-11T03:25:08.000Z | /*
* Copyright (C) 2018 Swift Navigation Inc.
* Contact: Swift Navigation <dev@swiftnav.com>
*
* This source is subject to the license found in the file 'LICENSE' which must
* be distributed together with this source. All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef ALBATROSS_MODELS_LEAST_SQUARES_H
#define ALBATROSS_MODELS_LEAST_SQUARES_H
namespace albatross {
template <typename ImplType> class LeastSquares;
template <typename ImplType> struct Fit<LeastSquares<ImplType>> {
Eigen::VectorXd coefs;
bool operator==(const Fit &other) const { return (coefs == other.coefs); }
};
inline bool all_same_value(const Eigen::VectorXd &x) {
if (x.size() == 0) {
return true;
} else {
const double first = x[0];
for (Eigen::Index i = 0; i < x.size(); ++i) {
if (x[i] != first) {
return false;
}
}
return true;
}
}
/*
* This model supports a family of models which consist of
* first creating a design matrix, A, then solving least squares. Ie,
*
* min_x |y - Ax|_2^2
*
* The FeatureType in this case is a single row from the design matrix.
*/
template <typename ImplType> class LeastSquares : public ModelBase<ImplType> {
public:
using FitType = Fit<LeastSquares<ImplType>>;
std::string get_name() const { return "least_squares"; }
FitType _fit_impl(const std::vector<Eigen::VectorXd> &features,
const MarginalDistribution &targets) const {
// The way this is currently implemented we assume all targets have the same
// variance (or zero variance).
assert(all_same_value(targets.covariance.diagonal()));
// Build the design matrix
int m = static_cast<int>(features.size());
int n = static_cast<int>(features[0].size());
Eigen::MatrixXd A(m, n);
for (int i = 0; i < m; i++) {
A.row(i) = features[static_cast<std::size_t>(i)];
}
FitType model_fit = {least_squares_solver(A, targets.mean)};
return model_fit;
}
Eigen::VectorXd _predict_impl(const std::vector<Eigen::VectorXd> &features,
const FitType &least_squares_fit,
PredictTypeIdentity<Eigen::VectorXd>) const {
std::size_t n = features.size();
Eigen::VectorXd mean(n);
for (std::size_t i = 0; i < n; i++) {
mean(static_cast<Eigen::Index>(i)) =
features[i].dot(least_squares_fit.coefs);
}
return Eigen::VectorXd(mean);
}
/*
* This lets you customize the least squares approach if need be,
* default uses the QR decomposition.
*/
Eigen::VectorXd least_squares_solver(const Eigen::MatrixXd &A,
const Eigen::VectorXd &b) const {
return A.colPivHouseholderQr().solve(b);
}
};
/*
* Creates a least squares problem by building a design matrix where the
* i^th row looks like:
*
* A_i = [1 x]
*
* Setup like this the resulting least squares solve will represent
* an offset and slope.
*/
class LinearRegression : public LeastSquares<LinearRegression> {
public:
using Base = LeastSquares<LinearRegression>;
std::string get_name() const { return "linear_regression"; }
Eigen::VectorXd convert_feature(const double &f) const {
Eigen::VectorXd converted(2);
converted << 1., f;
return converted;
}
std::vector<Eigen::VectorXd>
convert_features(const std::vector<double> &features) const {
std::vector<Eigen::VectorXd> output;
for (const auto &f : features) {
output.emplace_back(convert_feature(f));
}
return output;
}
Base::FitType _fit_impl(const std::vector<double> &features,
const MarginalDistribution &targets) const {
return Base::_fit_impl(convert_features(features), targets);
}
Eigen::VectorXd _predict_impl(const std::vector<double> &features,
const Base::FitType &least_squares_fit,
PredictTypeIdentity<Eigen::VectorXd>) const {
return Base::_predict_impl(convert_features(features), least_squares_fit,
PredictTypeIdentity<Eigen::VectorXd>());
}
};
} // namespace albatross
#endif
| 31.410072 | 80 | 0.65781 | [
"vector",
"model"
] |
f300095cd5ab68c21435543effa19cecf85e68b2 | 17,549 | cpp | C++ | tc/sgx/trusted_worker_manager/enclave_untrusted/enclave_bridge/dcap/dcap_attestation.cpp | MarkYQJ/avalon | ce962a09bda033d9e33c219bb1f2452f091e28dd | [
"Apache-2.0"
] | 127 | 2019-10-25T08:43:26.000Z | 2022-03-20T15:33:32.000Z | tc/sgx/trusted_worker_manager/enclave_untrusted/enclave_bridge/dcap/dcap_attestation.cpp | Mateus-dang/avalon | 3f6f4f4b892753cf2ae9f3cab839664ed6e7512c | [
"Apache-2.0"
] | 275 | 2019-10-24T23:36:21.000Z | 2022-01-24T20:38:07.000Z | tc/sgx/trusted_worker_manager/enclave_untrusted/enclave_bridge/dcap/dcap_attestation.cpp | Mateus-dang/avalon | 3f6f4f4b892753cf2ae9f3cab839664ed6e7512c | [
"Apache-2.0"
] | 110 | 2019-10-30T07:09:25.000Z | 2022-01-28T09:40:44.000Z | /* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <string>
#include <sgx_uae_launch.h>
#include "sgx_dcap_quoteverify.h"
#include "dcap_attestation.h"
#include "sgx_utility.h"
#include "avalon_sgx_error.h"
#include "zero.h"
#include "hex_string.h"
#include "enclave_common_u.h"
#include "sgx_dcap_ql_wrapper.h"
#include "sgx_quote_3.h"
#include "sgx_utils.h"
#include "sgx_report.h"
#include "sgx_error.h"
#include "sgx_qve_header.h"
#include "sgx_ql_quote.h"
#include "sgx_urts.h"
#include "sgx_pce.h"
#include "jsonvalue.h"
#include "parson.h"
#include "types.h"
#include "utils.h"
#include "log.h"
#include "sgx_utility.h"
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
DcapAttestation::DcapAttestation() {
// Initialize the targetinfo
quote3_error_t qe3_ret = tcf::sgx_util::CallSgx([this] () {
return sgx_qe_get_target_info(&this->reportTargetInfo);
});
tcf::error::ThrowSgxError(qe3_ret,
"Failed to initialize dcap quote in enclave constructor");
// Initialize the quote size
uint32_t size;
qe3_ret = sgx_qe_get_quote_size(&size);
tcf::error::ThrowSgxError(qe3_ret,
"Failed to get Intel SGX quote size.");
this->quoteSize = size;
} // DcapAttestation::DcapAttestation
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
DcapAttestation::~DcapAttestation() {
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
tcf_err_t DcapAttestation::GetEnclaveCharacteristics(
const sgx_enclave_id_t& enclave_id,
sgx_measurement_t* outEnclaveMeasurement,
sgx_basename_t* outEnclaveBasename) {
tcf::error::ThrowIfNull(outEnclaveMeasurement,
"Enclave measurement pointer is NULL");
tcf::error::ThrowIfNull(outEnclaveBasename,
"Enclave basename pointer is NULL");
Zero(outEnclaveMeasurement, sizeof(*outEnclaveMeasurement));
Zero(outEnclaveBasename, sizeof(*outEnclaveBasename));
// We can get the enclave's measurement (i.e., mr_enclave) and
// basename only by getting a quote. To do that, we need to first
// generate a report.
// Initialize a quote
sgx_target_info_t targetInfo = { 0 };
quote3_error_t ret = tcf::sgx_util::CallSgx([&targetInfo] () {
return sgx_qe_get_target_info(&targetInfo);
});
tcf::error::ThrowSgxError(ret, "Failed to initialize enclave quote");
// Now retrieve a fake enclave report so that we can later
// create a quote from it. We need to the quote so that we can
// get some of the information (basename and mr_enclave,
// specifically) being requested.
sgx_report_t enclaveReport = { 0 };
tcf_err_t tcfRet = TCF_SUCCESS;
sgx_status_t s_ret = tcf::sgx_util::CallSgx(
[&enclave_id,
&tcfRet,
&targetInfo,
&enclaveReport] () {
sgx_status_t ret =
ecall_CreateErsatzEnclaveReport(
enclave_id,
&tcfRet,
&targetInfo,
&enclaveReport);
return tcf::error::ConvertErrorStatus(ret, tcfRet);
});
tcf::error::ThrowSgxError(s_ret,
"Failed to retrieve ersatz enclave report");
if (tcfRet != TCF_SUCCESS) {
return tcfRet;
}
// Properly size a buffer to receive an enclave quote and then
// retrieve it. The enclave quote contains the basename.
ByteArray enclaveQuoteBuffer(this->quoteSize);
sgx_quote_t* enclaveQuote = reinterpret_cast<sgx_quote_t *>(&enclaveQuoteBuffer[0]);
uint32_t quote_size = 0;
quote3_error_t qe3_ret = sgx_qe_get_quote_size("e_size);
tcf::error::ThrowSgxError(qe3_ret,
"Failed to calculate the quote size");
this->quoteSize = quote_size;
uint8_t* p_quote_buffer = NULL;
p_quote_buffer = (uint8_t*)malloc(this->quoteSize);
memset(p_quote_buffer, 0, this->quoteSize);
quote3_error_t sresult = tcf::sgx_util::CallSgx(
[this,
&enclaveReport,
p_quote_buffer] () {
return sgx_qe_get_quote(
&enclaveReport,
this->quoteSize,
p_quote_buffer);
});
tcf::error::ThrowSgxError(
sresult,
"Failed to get DCAP quote from the enclave");
std::copy(p_quote_buffer, p_quote_buffer+this->quoteSize,
enclaveQuoteBuffer.begin());
// Copy the mr_enclave and basename to the caller's buffers
memcpy_s(outEnclaveMeasurement,
sizeof(*outEnclaveMeasurement),
&enclaveQuote->report_body.mr_enclave,
sizeof(*outEnclaveMeasurement));
memcpy_s(outEnclaveBasename,
sizeof(*outEnclaveBasename),
&enclaveQuote->basename,
sizeof(*outEnclaveBasename));
return TCF_SUCCESS;
} // DcapAttestation::GetEnclaveCharacteristics
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
size_t DcapAttestation::GetQuoteSize(void) {
return this->quoteSize;
} // GetQuoteSize
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
void DcapAttestation::CreateQuoteFromReport(
const sgx_report_t* inEnclaveReport,
ByteArray& outEnclaveQuote) {
// Properly size the enclave quote buffer for the caller and zero
// it out so we have predictable contents.
outEnclaveQuote.resize(this->quoteSize);
uint8_t* p_quote_buffer = NULL;
p_quote_buffer = (uint8_t*)malloc(this->quoteSize);
memset(p_quote_buffer, 0, this->quoteSize);
quote3_error_t sresult =
tcf::sgx_util::CallSgx(
[&inEnclaveReport,
this,
p_quote_buffer] () {
return sgx_qe_get_quote(
inEnclaveReport,
this->quoteSize,
p_quote_buffer);
});
tcf::error::ThrowSgxError(sresult,
"Failed to get the DCAP quote from enclave");
std::copy(p_quote_buffer,
p_quote_buffer+this->quoteSize,
outEnclaveQuote.begin());
} // DcapAttestation::CreateQuoteFromReport
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
void DcapAttestation::InitQuote(sgx_target_info_t& target_info) {
quote3_error_t qe3_ret = tcf::sgx_util::CallSgx(
[&target_info] () {
return sgx_qe_get_target_info(&target_info);
});
tcf::error::ThrowSgxError(qe3_ret,
"Intel SGX enclave call failed (sgx_qe_get_target_info);"
" failed to initialize target info");
} // DcapAttestation::InitQuote
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#ifdef BUILD_SINGLETON
tcf_err_t DcapAttestation::VerifyEnclaveInfoSingleton(
const std::string& enclaveInfo, const std::string& mr_enclave,
const sgx_enclave_id_t& enclave_id) {
tcf_err_t presult = TCF_SUCCESS;
tcf_err_t result = this->VerifyEnclaveInfo(enclaveInfo, enclave_id);
tcf::error::ThrowSgxError(result,
"Failed to verify DCAP enclave info");
sgx_status_t sresult = tcf::sgx_util::CallSgx(
[ enclave_id,
&presult,
enclaveInfo,
mr_enclave ] () {
sgx_status_t sresult = ecall_VerifyEnclaveInfoDcap(
enclave_id,
&presult,
enclaveInfo.c_str(),
mr_enclave.c_str());
return tcf::error::ConvertErrorStatus(sresult, presult);
});
tcf::error::ThrowSgxError(sresult,
"Intel SGX enclave call failed (ecall_VerifyEnclaveInfoDcap)");
return presult;
} // DcapAttestation::VerifyEnclaveInfoSingleton
#elif BUILD_KME
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
tcf_err_t DcapAttestation::VerifyEnclaveInfoKME(
const std::string& enclaveInfo, const std::string& mr_enclave,
const std::string& ext_data, const sgx_enclave_id_t& enclave_id) {
tcf_err_t presult = TCF_SUCCESS;
tcf_err_t result = this->VerifyEnclaveInfo(enclaveInfo, enclave_id);
tcf::error::ThrowIf<tcf::error::ValueError>(result != TCF_SUCCESS,
"Failed to verify DCAP enclave info");
ByteArray ext_data_bytes = HexEncodedStringToByteArray(ext_data);
sgx_status_t sresult = tcf::sgx_util::CallSgx(
[ enclave_id,
&presult,
enclaveInfo,
mr_enclave,
ext_data_bytes ] () {
sgx_status_t sresult = ecall_VerifyEnclaveInfoKMEDcap(
enclave_id,
&presult,
enclaveInfo.c_str(),
mr_enclave.c_str(),
ext_data_bytes.data(),
ext_data_bytes.size());
return tcf::error::ConvertErrorStatus(sresult, presult);
});
tcf::error::ThrowSgxError(sresult,
"Intel SGX enclave call failed (ecall_VerifyEnclaveInfoKMEDcap)");
return presult;
} // DcapAttestation::VerifyEnclaveInfoKME
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#elif BUILD_WPE
tcf_err_t DcapAttestation::VerifyEnclaveInfoWPE(
const std::string& enclaveInfo, const std::string& mr_enclave,
const std::string& ext_data, const sgx_enclave_id_t& enclave_id) {
tcf_err_t presult = TCF_SUCCESS;
tcf_err_t result = this->VerifyEnclaveInfo(enclaveInfo, enclave_id);
tcf::error::ThrowIf<tcf::error::ValueError>(result != TCF_SUCCESS,
"Failed to verify DCAP enclave info");
sgx_status_t sresult = tcf::sgx_util::CallSgx(
[ enclave_id,
&presult,
enclaveInfo,
mr_enclave,
ext_data ] () {
sgx_status_t sresult = ecall_VerifyEnclaveInfoWPEDcap(
enclave_id,
&presult,
enclaveInfo.c_str(),
mr_enclave.c_str(),
ext_data.c_str());
return tcf::error::ConvertErrorStatus(sresult,
presult);
});
tcf::error::ThrowSgxError(sresult,
"Intel SGX enclave call failed (ecall_VerifyEnclaveInfoWPEDcap)");
return presult;
} // DcapAttestation::VerifyEnclaveInfoWPE
#endif
tcf_err_t DcapAttestation::VerifyEnclaveInfo(const std::string& enclave_info,
const sgx_enclave_id_t& enclave_id) {
tcf_err_t result = TCF_SUCCESS;
sgx_status_t sgx_ret = SGX_SUCCESS;
quote3_error_t dcap_ret = SGX_QL_ERROR_UNEXPECTED;
sgx_ql_qv_result_t quote_verification_result = SGX_QL_QV_RESULT_UNSPECIFIED;
sgx_ql_qe_report_info_t qve_report_info;
uint32_t supplemental_data_size = 0;
uint8_t *p_supplemental_data = NULL;
unsigned char rand_nonce[16] = "59jslk201fgjmm;";
time_t current_time = 0;
uint32_t collateral_expiration_status = 1;
quote3_error_t verify_qveid_ret = SGX_QL_ERROR_UNEXPECTED;
// Parse the enclave_info
JsonValue enclave_info_parsed(json_parse_string(enclave_info.c_str()));
tcf::error::ThrowIfNull(enclave_info_parsed.value,
"Failed to parse the enclave info, badly formed JSON");
JSON_Object* enclave_info_object = \
json_value_get_object(enclave_info_parsed);
tcf::error::ThrowIfNull(enclave_info_object,
"Invalid enclave_info, expecting object");
const char* svalue = nullptr;
svalue = json_object_dotget_string(enclave_info_object, "verifying_key");
tcf::error::ThrowIfNull(svalue, "Invalid verifying_key");
svalue = json_object_dotget_string(enclave_info_object, "encryption_key");
tcf::error::ThrowIfNull(svalue, "Invalid encryption_key");
// Parse proof data
svalue = json_object_dotget_string(enclave_info_object, "proof_data");
std::string proof_data(svalue);
JsonValue proof_data_parsed(json_parse_string(proof_data.c_str()));
tcf::error::ThrowIfNull(proof_data_parsed.value,
"Failed to parse the proofData, badly formed JSON");
JSON_Object* proof_object = json_value_get_object(proof_data_parsed);
tcf::error::ThrowIfNull(proof_object, "Invalid proof, expecting object");
//Parse verification report
svalue = json_object_dotget_string(proof_object, "verification_report");
tcf::error::ThrowIfNull(svalue, "Invalid proof_verification_report");
const std::string verification_report(svalue);
ByteArray quote = Base64EncodedStringToByteArray(verification_report);
// Set nonce
memcpy(qve_report_info.nonce.rand, rand_nonce, sizeof(rand_nonce));
// Get target info of the current Enclave.
// QvE will target the generated report to this enclave.
sgx_status_t get_target_info_ret;
sgx_ret = ecall_get_target_info(enclave_id,
&get_target_info_ret, &qve_report_info.app_enclave_target_info);
tcf::error::ThrowSgxError(sgx_ret,
"Failed to get target info while verifying DCAP quote");
//this->InitQuote(qve_report_info.app_enclave_target_info);
// Call DCAP quote verify library to set QvE loading policy
dcap_ret = sgx_qv_set_enclave_load_policy(SGX_QL_DEFAULT);
tcf::error::ThrowIf<tcf::error::ValueError>(dcap_ret != SGX_QL_SUCCESS,
"Error: failed to set quote verifying enclave load policy");
// Call DCAP quote verify library to get supplemental data size
dcap_ret = sgx_qv_get_quote_supplemental_data_size(&supplemental_data_size);
if (dcap_ret == SGX_QL_SUCCESS) {
p_supplemental_data = (uint8_t*)malloc(supplemental_data_size);
}
else {
tcf::error::ThrowIf<tcf::error::ValueError>(dcap_ret != SGX_QL_SUCCESS,
"Error: failed to get quote supplement data size");
}
// Set current time. This is only for sample purposes,
// in production mode a trusted time should be used.
current_time = time(NULL);
// Call DCAP quote verify library for quote verification
// Here we can choose 'trusted' or 'untrusted' quote verification
// by specifying parameter '&qve_report_info'
// If '&qve_report_info' is NOT NULL, this API will call Intel QvE to verify quote
// If '&qve_report_info' is NULL, this API will call 'untrusted quote verify lib'
// to verify quote, this mode doesn't rely on SGX capable system,
// but the results can not be cryptographically authenticated.
std::string err_str1 = "Error: Dcap Quote verification "
"failed with error code ";
dcap_ret = sgx_qv_verify_quote(
quote.data(), (uint32_t)quote.size(),
NULL,
current_time,
&collateral_expiration_status,
"e_verification_result,
&qve_report_info,
supplemental_data_size,
p_supplemental_data);
err_str1 += std::to_string(static_cast<int>(dcap_ret));
tcf::error::ThrowIf<tcf::error::ValueError>(dcap_ret != SGX_QL_SUCCESS,
err_str1.c_str());
// Threshold of QvE ISV SVN.
// The ISV SVN of QvE used to verify quote must be greater or
// equal to this threshold
// e.g. You can get latest QvE ISVSVN in QvE Identity JSON file from
// https://api.trustedservices.intel.com/sgx/certification/v2/qve/identity
// Make sure you are using trusted & latest QvE ISV SVN as threshold
sgx_isv_svn_t qve_isvsvn_threshold = 3;
std::string err_str2 = "Error: Dcap Quote verifying enclave indentity "
"is failed with ";
// Call sgx_dcap_tvl API in SampleISVEnclave to verify QvE's
// report and identity
sgx_ret = sgx_tvl_verify_qve_report_and_identity(enclave_id,
&verify_qveid_ret,
quote.data(),
(uint32_t) quote.size(),
&qve_report_info,
current_time,
collateral_expiration_status,
quote_verification_result,
p_supplemental_data,
supplemental_data_size,
qve_isvsvn_threshold);
std::string sgx_err_code = std::to_string(static_cast<int>(sgx_ret));
std::string qve_err_code = std::to_string(static_cast<int>(
verify_qveid_ret));
err_str2 += " SGX error " + sgx_err_code + " QVE error " + qve_err_code;
tcf::error::ThrowIf<tcf::error::ValueError>(
(sgx_ret != SGX_SUCCESS || verify_qveid_ret != SGX_QL_SUCCESS),
err_str2.c_str());
// Check verification result
switch (quote_verification_result)
{
case SGX_QL_QV_RESULT_OK:
result = TCF_SUCCESS;
tcf::Log(TCF_LOG_INFO, "Verification completed successfully: %d\n",(int)quote_verification_result);
break;
case SGX_QL_QV_RESULT_CONFIG_NEEDED:
case SGX_QL_QV_RESULT_OUT_OF_DATE:
case SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED:
case SGX_QL_QV_RESULT_SW_HARDENING_NEEDED:
case SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED:
result = TCF_SUCCESS;
tcf::Log(TCF_LOG_WARNING, "Verification completed with Non-terminal result: %x",
(int)quote_verification_result);
break;
case SGX_QL_QV_RESULT_INVALID_SIGNATURE:
case SGX_QL_QV_RESULT_REVOKED:
case SGX_QL_QV_RESULT_UNSPECIFIED:
default:
tcf::error::ThrowIf<tcf::error::ValueError>(
false,
"Error: Quote Verification completed with Terminal result:");
result = TCF_ERR_UNKNOWN;
break;
}
return result;
} // VerifyEnclaveInfo
| 38.316594 | 110 | 0.692632 | [
"object"
] |
f3011ec2bacf5787578fcfa925684c3e0fc3aca1 | 34,173 | cpp | C++ | src/mongo/db/query/sbe_stage_builder_coll_scan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/sbe_stage_builder_coll_scan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/sbe_stage_builder_coll_scan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/query/sbe_stage_builder_coll_scan.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/exec/sbe/stages/co_scan.h"
#include "mongo/db/exec/sbe/stages/exchange.h"
#include "mongo/db/exec/sbe/stages/filter.h"
#include "mongo/db/exec/sbe/stages/limit_skip.h"
#include "mongo/db/exec/sbe/stages/loop_join.h"
#include "mongo/db/exec/sbe/stages/project.h"
#include "mongo/db/exec/sbe/stages/scan.h"
#include "mongo/db/exec/sbe/stages/union.h"
#include "mongo/db/query/sbe_stage_builder.h"
#include "mongo/db/query/sbe_stage_builder_filter.h"
#include "mongo/db/query/util/make_data_structure.h"
#include "mongo/db/record_id_helpers.h"
#include "mongo/logv2/log.h"
#include "mongo/util/str.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kQuery
namespace mongo::stage_builder {
namespace {
boost::optional<sbe::value::SlotId> registerOplogTs(sbe::RuntimeEnvironment* env,
sbe::value::SlotIdGenerator* slotIdGenerator) {
auto slotId = env->getSlotIfExists("oplogTs"_sd);
if (!slotId) {
return env->registerSlot(
"oplogTs"_sd, sbe::value::TypeTags::Nothing, 0, false, slotIdGenerator);
}
return slotId;
}
/**
* If 'shouldTrackLatestOplogTimestamp' is true, then returns a vector holding the name of the oplog
* 'ts' field along with another vector holding a SlotId to map this field to, as well as the
* standalone value of the same SlotId (the latter is returned purely for convenience purposes).
*/
std::tuple<std::vector<std::string>, sbe::value::SlotVector, boost::optional<sbe::value::SlotId>>
makeOplogTimestampSlotsIfNeeded(sbe::RuntimeEnvironment* env,
sbe::value::SlotIdGenerator* slotIdGenerator,
bool shouldTrackLatestOplogTimestamp) {
if (shouldTrackLatestOplogTimestamp) {
auto slotId = registerOplogTs(env, slotIdGenerator);
return {{repl::OpTime::kTimestampFieldName.toString()}, sbe::makeSV(*slotId), slotId};
}
return {};
}
/**
* Checks whether a callback function should be created for a ScanStage and returns it, if so. The
* logic in the provided callback will be executed when the ScanStage is opened or reopened.
*/
sbe::ScanOpenCallback makeOpenCallbackIfNeeded(const CollectionPtr& collection,
const CollectionScanNode* csn) {
if (csn->direction == CollectionScanParams::FORWARD && csn->shouldWaitForOplogVisibility) {
invariant(!csn->tailable);
invariant(collection->ns().isOplog());
return [](OperationContext* opCtx, const CollectionPtr& collection, bool reOpen) {
if (!reOpen) {
// Forward, non-tailable scans from the oplog need to wait until all oplog entries
// before the read begins to be visible. This isn't needed for reverse scans because
// we only hide oplog entries from forward scans, and it isn't necessary for tailing
// cursors because they ignore EOF and will eventually see all writes. Forward,
// non-tailable scans are the only case where a meaningful EOF will be seen that
// might not include writes that finished before the read started. This also must be
// done before we create the cursor as that is when we establish the endpoint for
// the cursor. Also call abandonSnapshot to make sure that we are using a fresh
// storage engine snapshot while waiting. Otherwise, we will end up reading from the
// snapshot where the oplog entries are not yet visible even after the wait.
opCtx->recoveryUnit()->abandonSnapshot();
collection->getRecordStore()->waitForAllEarlierOplogWritesToBeVisible(opCtx);
}
};
}
return {};
}
// If the scan should be started after the provided resume RecordId, we will construct a nested-loop
// join sub-tree to project out the resume RecordId and feed it into the inner side (scan). We will
// also construct a union sub-tree as an outer side of the loop join to implement the check that the
// record we're trying to reposition the scan exists.
//
// nlj [] [seekRecordIdSlot]
// left
// limit 1
// union [seekRecordIdSlot]
// [seekSlot]
// nlj
// left
// project seekSlot = <seekRecordIdExpression>
// limit 1
// coscan
// right
// seek seekSlot ...
// [unusedSlot]
// project unusedSlot = efail(KeyNotFound)
// limit 1
// coscan
// right
// skip 1
// <inputStage>
std::unique_ptr<sbe::PlanStage> buildResumeFromRecordIdSubtree(
StageBuilderState& state,
const CollectionPtr& collection,
const CollectionScanNode* csn,
std::unique_ptr<sbe::PlanStage> inputStage,
sbe::value::SlotId seekRecordIdSlot,
std::unique_ptr<sbe::EExpression> seekRecordIdExpression,
PlanYieldPolicy* yieldPolicy,
bool isTailableResumeBranch,
bool resumeAfterRecordId) {
invariant(seekRecordIdExpression);
const auto forward = csn->direction == CollectionScanParams::FORWARD;
// Project out the RecordId we want to resume from as 'seekSlot'.
auto seekSlot = state.slotId();
auto projStage = sbe::makeProjectStage(
sbe::makeS<sbe::LimitSkipStage>(
sbe::makeS<sbe::CoScanStage>(csn->nodeId()), 1, boost::none, csn->nodeId()),
csn->nodeId(),
seekSlot,
std::move(seekRecordIdExpression));
// Construct a 'seek' branch of the 'union'. If we're succeeded to reposition the cursor,
// the branch will output the 'seekSlot' to start the real scan from, otherwise it will
// produce EOF.
auto seekBranch =
sbe::makeS<sbe::LoopJoinStage>(std::move(projStage),
sbe::makeS<sbe::ScanStage>(collection->uuid(),
boost::none /* recordSlot */,
boost::none /* recordIdSlot*/,
boost::none /* snapshotIdSlot */,
boost::none /* indexIdSlot */,
boost::none /* indexKeySlot */,
boost::none /* keyPatternSlot */,
boost::none /* oplogTsSlot */,
std::vector<std::string>{},
sbe::makeSV(),
seekSlot,
forward,
yieldPolicy,
csn->nodeId(),
sbe::ScanCallbacks{}),
sbe::makeSV(seekSlot),
sbe::makeSV(seekSlot),
nullptr,
csn->nodeId());
// Construct a 'fail' branch of the union. The 'unusedSlot' is needed as each union branch must
// have the same number of slots, and we use just one in the 'seek' branch above. This branch
// will only be executed if the 'seek' branch produces EOF, which can only happen if the seek
// did not find the resume record of a tailable cursor or the record id specified in
// $_resumeAfter.
auto unusedSlot = state.slotId();
auto [errorCode, errorMessage] = [&]() -> std::pair<ErrorCodes::Error, std::string> {
if (isTailableResumeBranch) {
return {ErrorCodes::CappedPositionLost,
"CollectionScan died due to failure to restore tailable cursor position."};
}
return {ErrorCodes::ErrorCodes::KeyNotFound,
str::stream() << "Failed to resume collection scan the recordId from which we are "
"attempting to resume no longer exists in the collection: "
<< csn->resumeAfterRecordId};
}();
auto failBranch = sbe::makeProjectStage(sbe::makeS<sbe::CoScanStage>(csn->nodeId()),
csn->nodeId(),
unusedSlot,
sbe::makeE<sbe::EFail>(errorCode, errorMessage));
// Construct a union stage from the 'seek' and 'fail' branches. Note that this stage will ever
// produce a single call to getNext() due to a 'limit 1' sitting on top of it.
auto unionStage = sbe::makeS<sbe::UnionStage>(
sbe::makeSs(std::move(seekBranch), std::move(failBranch)),
std::vector<sbe::value::SlotVector>{sbe::makeSV(seekSlot), sbe::makeSV(unusedSlot)},
sbe::makeSV(seekRecordIdSlot),
csn->nodeId());
// Construct the final loop join. Note that for the resume branch of a tailable cursor case we
// use the 'seek' stage as an inner branch, since we need to produce all records starting from
// the supplied position. For a resume token case we also inject a 'skip 1' stage on top of the
// inner branch, as we need to start _after_ the resume RecordId. In both cases we inject a
// 'limit 1' stage on top of the outer branch, as it should produce just a single seek recordId.
auto innerStage = isTailableResumeBranch || !resumeAfterRecordId
? std::move(inputStage)
: sbe::makeS<sbe::LimitSkipStage>(std::move(inputStage), boost::none, 1, csn->nodeId());
return sbe::makeS<sbe::LoopJoinStage>(
sbe::makeS<sbe::LimitSkipStage>(std::move(unionStage), 1, boost::none, csn->nodeId()),
std::move(innerStage),
sbe::makeSV(),
sbe::makeSV(seekRecordIdSlot),
nullptr,
csn->nodeId());
}
/**
* Creates a collection scan sub-tree optimized for oplog scans. We can built an optimized scan
* when any of the following scenarios apply:
*
* 1. There is a predicted on the 'ts' field of the oplog collection.
* 1.1 If a lower bound on 'ts' is present, the collection scan will seek directly to the
* RecordId of an oplog entry as close to this lower bound as possible without going higher.
* 1.2 If the query is *only* a lower bound on 'ts' on a forward scan, every document in the
* collection after the first matching one must also match. To avoid wasting time running the
* filter on every document to be returned, we will stop applying the filter once it finds
* the first match.
* 1.3 If an upper bound on 'ts' is present, the collection scan will stop and return EOF the
* first time it fetches a document that does not pass the filter and has 'ts' greater than
* the upper bound.
* 2. The user request specified a $_resumeAfter recordId from which to begin the scan.
*/
std::pair<std::unique_ptr<sbe::PlanStage>, PlanStageSlots> generateOptimizedOplogScan(
StageBuilderState& state,
const CollectionPtr& collection,
const CollectionScanNode* csn,
PlanYieldPolicy* yieldPolicy,
bool isTailableResumeBranch) {
invariant(collection->ns().isOplog());
// We can apply oplog scan optimizations only when at least one of the following was specified.
invariant(csn->resumeAfterRecordId || csn->minRecord || csn->maxRecord);
// The minRecord and maxRecord optimizations are not compatible with resumeAfterRecordId.
invariant(!(csn->resumeAfterRecordId && (csn->minRecord || csn->maxRecord)));
// Oplog scan optimizations can only be done for a forward scan.
invariant(csn->direction == CollectionScanParams::FORWARD);
auto resultSlot = state.slotId();
auto recordIdSlot = state.slotId();
// Start the scan from the RecordId stored in seekRecordId.
// Otherwise, if we're building a collection scan for a resume branch of a special union
// sub-tree implementing a tailable cursor scan, we can use the seekRecordIdSlot directly
// to access the recordId to resume the scan from.
auto [seekRecordIdSlot, seekRecordIdExpression] =
[&]() -> std::pair<boost::optional<sbe::value::SlotId>, std::unique_ptr<sbe::EExpression>> {
if (isTailableResumeBranch) {
auto resumeRecordIdSlot = state.data->env->getSlot("resumeRecordId"_sd);
return {resumeRecordIdSlot, makeVariable(resumeRecordIdSlot)};
} else if (csn->resumeAfterRecordId) {
auto [tag, val] = sbe::value::makeCopyRecordId(*csn->resumeAfterRecordId);
return {state.slotId(), makeConstant(tag, val)};
} else if (csn->minRecord) {
auto cursor = collection->getRecordStore()->getCursor(state.opCtx);
auto startRec = cursor->seekNear(csn->minRecord->recordId());
if (startRec) {
LOGV2_DEBUG(205841, 3, "Using direct oplog seek");
auto [tag, val] = sbe::value::makeCopyRecordId(startRec->id);
return {state.slotId(), makeConstant(tag, val)};
}
}
return {};
}();
// Check if we need to project out an oplog 'ts' field as part of the collection scan. We will
// need it either when 'maxRecord' bound has been provided, so that we can apply an EOF filter,
// of if we need to track the latest oplog timestamp.
const auto shouldTrackLatestOplogTimestamp =
(csn->maxRecord || csn->shouldTrackLatestOplogTimestamp);
auto&& [fields, slots, tsSlot] = makeOplogTimestampSlotsIfNeeded(
state.data->env, state.slotIdGenerator, shouldTrackLatestOplogTimestamp);
sbe::ScanCallbacks callbacks({}, {}, makeOpenCallbackIfNeeded(collection, csn));
auto stage = sbe::makeS<sbe::ScanStage>(collection->uuid(),
resultSlot,
recordIdSlot,
boost::none /* snapshotIdSlot */,
boost::none /* indexIdSlot */,
boost::none /* indexKeySlot */,
boost::none /* keyPatternSlot */,
tsSlot,
std::move(fields),
std::move(slots),
seekRecordIdSlot,
true /* forward */,
yieldPolicy,
csn->nodeId(),
std::move(callbacks));
// Start the scan from the seekRecordId.
if (seekRecordIdSlot) {
stage = buildResumeFromRecordIdSubtree(state,
collection,
csn,
std::move(stage),
*seekRecordIdSlot,
std::move(seekRecordIdExpression),
yieldPolicy,
isTailableResumeBranch,
csn->resumeAfterRecordId.has_value());
}
// Create a filter which checks the first document to ensure either that its 'ts' is less than
// or equal the minimum timestamp that should not have rolled off the oplog, or that it is a
// replica set initialization message. If this fails, then we throw
// ErrorCodes::OplogQueryMinTsMissing. We avoid doing this check on the resumable branch of a
// tailable scan; it only needs to be done once, when the initial branch is run.
if (csn->assertTsHasNotFallenOffOplog && !isTailableResumeBranch) {
invariant(csn->shouldTrackLatestOplogTimestamp);
// There should always be a 'tsSlot' already allocated on the RuntimeEnvironment for the
// existing scan that we created previously.
invariant(tsSlot);
// We will be constructing a filter that needs to see the 'ts' field. We name it 'minTsSlot'
// here so that it does not shadow the 'tsSlot' which we allocated earlier. Our filter will
// also need to see the 'op' and 'o.msg' fields.
auto opTypeSlot = state.slotId();
auto oObjSlot = state.slotId();
auto minTsSlot = state.slotId();
sbe::value::SlotVector minTsSlots = {minTsSlot, opTypeSlot, oObjSlot};
std::vector<std::string> fields = {repl::OpTime::kTimestampFieldName.toString(), "op", "o"};
// If the first entry we see in the oplog is the replset initialization, then it doesn't
// matter if its timestamp is later than the specified minTs; no events earlier than the
// minTs can have fallen off this oplog. Otherwise, we must verify that the timestamp of the
// first observed oplog entry is earlier than or equal to the minTs time.
//
// To achieve this, we build a two-branch union subtree. The left branch is a scan with a
// filter that checks the first entry in the oplog for the above criteria, throws via EFail
// if they are not met, and EOFs otherwise. The right branch of the union plan is the tree
// that we originally built above.
//
// union [s9, s10, s11] [
// [s6, s7, s8] efilter {if (ts <= minTs || op == "n" && isObject (o) &&
// getField (o, "msg") == "initiating set", false, fail ( 326 ))}
// scan [s6 = ts, s7 = op, s8 = o] @oplog,
// <stage>
// Set up the filter stage to be used in the left branch of the union. If the main body of
// the expression does not match the input document, it throws OplogQueryMinTsMissing. If
// the expression does match, then it returns 'false', which causes the filter (and as a
// result, the branch) to EOF immediately. Note that the resultSlot and recordIdSlot
// arguments to the ScanStage are boost::none, as we do not need them.
sbe::ScanCallbacks branchCallbacks{};
auto minTsBranch = sbe::makeS<sbe::FilterStage<false, true>>(
sbe::makeS<sbe::ScanStage>(collection->uuid(),
boost::none /* resultSlot */,
boost::none /* recordIdSlot */,
boost::none /* snapshotIdSlot */,
boost::none /* indexIdSlot */,
boost::none /* indexKeySlot */,
boost::none /* keyPatternSlot */,
boost::none /* oplogTsSlot*/,
std::move(fields),
minTsSlots, /* don't move this */
boost::none,
true /* forward */,
yieldPolicy,
csn->nodeId(),
branchCallbacks),
sbe::makeE<sbe::EIf>(
makeBinaryOp(
sbe::EPrimBinary::logicOr,
makeBinaryOp(sbe::EPrimBinary::lessEq,
makeVariable(minTsSlot),
makeConstant(sbe::value::TypeTags::Timestamp,
csn->assertTsHasNotFallenOffOplog->asULL())),
makeBinaryOp(
sbe::EPrimBinary::logicAnd,
makeBinaryOp(sbe::EPrimBinary::eq,
makeVariable(opTypeSlot),
makeConstant("n")),
makeBinaryOp(sbe::EPrimBinary::logicAnd,
makeFunction("isObject", makeVariable(oObjSlot)),
makeBinaryOp(sbe::EPrimBinary::eq,
makeFunction("getField",
makeVariable(oObjSlot),
makeConstant("msg")),
makeConstant(repl::kInitiatingSetMsg))))),
makeConstant(sbe::value::TypeTags::Boolean, false),
sbe::makeE<sbe::EFail>(ErrorCodes::OplogQueryMinTsMissing,
"Specified minTs has already fallen off the oplog")),
csn->nodeId());
// All branches of the UnionStage must have the same number of input and output slots, and
// we want to remap all slots from the basic scan we constructed earlier through the union
// stage to the output. We're lucky that the real scan happens to have the same number of
// slots (resultSlot, recordSlot, tsSlot) as the minTs check branch (minTsSlot, opTypeSlot,
// oObjSlot), so we don't have to compensate with any unused slots. Note that the minTsSlots
// will never be mapped to output in practice, since the minTs branch either throws or EOFs.
//
// We also need to update the local variables for each slot to their remapped values, so
// subsequent subtrees constructed by this function refer to the correct post-union slots.
auto realSlots = sbe::makeSV(resultSlot, recordIdSlot, *tsSlot);
resultSlot = state.slotId();
recordIdSlot = state.slotId();
tsSlot = state.slotId();
auto outputSlots = sbe::makeSV(resultSlot, recordIdSlot, *tsSlot);
// Create the union stage. The left branch, which runs first, is our resumability check.
stage = sbe::makeS<sbe::UnionStage>(
sbe::makeSs(std::move(minTsBranch), std::move(stage)),
makeVector<sbe::value::SlotVector>(std::move(minTsSlots), std::move(realSlots)),
std::move(outputSlots),
csn->nodeId());
}
// Add an EOF filter to stop the scan after we fetch the first document that has 'ts' greater
// than the upper bound.
if (csn->maxRecord) {
// The 'maxRecord' optimization is not compatible with 'stopApplyingFilterAfterFirstMatch'.
invariant(!csn->stopApplyingFilterAfterFirstMatch);
invariant(tsSlot);
stage = sbe::makeS<sbe::FilterStage<false, true>>(
std::move(stage),
makeBinaryOp(sbe::EPrimBinary::lessEq,
makeVariable(*tsSlot),
makeConstant(sbe::value::TypeTags::Timestamp,
csn->maxRecord->recordId().getLong())),
csn->nodeId());
}
// If csn->stopApplyingFilterAfterFirstMatch is true, assert that csn has a filter.
invariant(!csn->stopApplyingFilterAfterFirstMatch || csn->filter);
if (csn->filter) {
auto relevantSlots = sbe::makeSV(resultSlot, recordIdSlot);
if (tsSlot) {
relevantSlots.push_back(*tsSlot);
}
auto [_, outputStage] = generateFilter(state,
csn->filter.get(),
{std::move(stage), std::move(relevantSlots)},
resultSlot,
csn->nodeId());
stage = std::move(outputStage.stage);
// We may be requested to stop applying the filter after the first match. This can happen
// if the query is just a lower bound on 'ts' on a forward scan. In this case every document
// in the collection after the first matching one must also match, so there is no need to
// run the filter on such elements.
//
// To apply this optimization we will construct the following sub-tree:
//
// nlj [] [seekRecordIdSlot]
// left
// limit 1
// filter <predicate>
// <stage>
// right
// seek seekRecordIdSlot resultSlot recordIdSlot @coll
//
// Here, the nested loop join outer branch is the collection scan we constructed above, with
// a csn->filter predicate sitting on top. The 'limit 1' stage is to ensure this branch
// returns a single row. Once executed, this branch will filter out documents which doesn't
// satisfy the predicate, and will return the first document, along with a RecordId, that
// matches. This RecordId is then used as a starting point of the collection scan in the
// inner branch, and the execution will continue from this point further on, without
// applying the filter.
if (csn->stopApplyingFilterAfterFirstMatch) {
invariant(!csn->maxRecord);
invariant(csn->direction == CollectionScanParams::FORWARD);
seekRecordIdSlot = recordIdSlot;
resultSlot = state.slotId();
recordIdSlot = state.slotId();
std::tie(fields, slots, tsSlot) = makeOplogTimestampSlotsIfNeeded(
state.data->env, state.slotIdGenerator, shouldTrackLatestOplogTimestamp);
stage = sbe::makeS<sbe::LoopJoinStage>(
sbe::makeS<sbe::LimitSkipStage>(std::move(stage), 1, boost::none, csn->nodeId()),
sbe::makeS<sbe::ScanStage>(collection->uuid(),
resultSlot,
recordIdSlot,
boost::none /* snapshotIdSlot */,
boost::none /* indexIdSlot */,
boost::none /* indexKeySlot */,
boost::none /* keyPatternSlot */,
tsSlot,
std::move(fields),
std::move(slots),
seekRecordIdSlot,
true /* forward */,
yieldPolicy,
csn->nodeId(),
sbe::ScanCallbacks{}),
sbe::makeSV(),
sbe::makeSV(*seekRecordIdSlot),
nullptr,
csn->nodeId());
}
}
// If csn->shouldTrackLatestOplogTimestamp is true, assert that we generated tsSlot.
invariant(!csn->shouldTrackLatestOplogTimestamp || tsSlot);
PlanStageSlots outputs;
outputs.set(PlanStageSlots::kResult, resultSlot);
outputs.set(PlanStageSlots::kRecordId, recordIdSlot);
return {std::move(stage), std::move(outputs)};
}
/**
* Generates a generic collection scan sub-tree.
* - If a resume token has been provided, the scan will start from a RecordId contained within this
* token.
* - Else if 'isTailableResumeBranch' is true, the scan will start from a RecordId contained in
* slot "resumeRecordId".
* - Otherwise the scan will start from the beginning of the collection.
*/
std::pair<std::unique_ptr<sbe::PlanStage>, PlanStageSlots> generateGenericCollScan(
StageBuilderState& state,
const CollectionPtr& collection,
const CollectionScanNode* csn,
PlanYieldPolicy* yieldPolicy,
bool isTailableResumeBranch) {
const auto forward = csn->direction == CollectionScanParams::FORWARD;
invariant(!csn->shouldTrackLatestOplogTimestamp || collection->ns().isOplog());
invariant(!csn->resumeAfterRecordId || forward);
invariant(!csn->resumeAfterRecordId || !csn->tailable);
auto resultSlot = state.slotId();
auto recordIdSlot = state.slotId();
auto [seekRecordIdSlot, seekRecordIdExpression] =
[&]() -> std::pair<boost::optional<sbe::value::SlotId>, std::unique_ptr<sbe::EExpression>> {
if (csn->resumeAfterRecordId) {
auto [tag, val] = sbe::value::makeCopyRecordId(*csn->resumeAfterRecordId);
return {state.slotId(), makeConstant(tag, val)};
} else if (isTailableResumeBranch) {
auto resumeRecordIdSlot = state.data->env->getSlot("resumeRecordId"_sd);
return {resumeRecordIdSlot, makeVariable(resumeRecordIdSlot)};
}
return {};
}();
// See if we need to project out an oplog latest timestamp.
auto&& [fields, slots, tsSlot] = makeOplogTimestampSlotsIfNeeded(
state.data->env, state.slotIdGenerator, csn->shouldTrackLatestOplogTimestamp);
sbe::ScanCallbacks callbacks({}, {}, makeOpenCallbackIfNeeded(collection, csn));
auto stage = sbe::makeS<sbe::ScanStage>(collection->uuid(),
resultSlot,
recordIdSlot,
boost::none /* snapshotIdSlot */,
boost::none /* indexIdSlot */,
boost::none /* indexKeySlot */,
boost::none /* keyPatternSlot */,
tsSlot,
std::move(fields),
std::move(slots),
seekRecordIdSlot,
forward,
yieldPolicy,
csn->nodeId(),
std::move(callbacks));
if (seekRecordIdSlot) {
stage = buildResumeFromRecordIdSubtree(state,
collection,
csn,
std::move(stage),
*seekRecordIdSlot,
std::move(seekRecordIdExpression),
yieldPolicy,
isTailableResumeBranch,
true /* resumeAfterRecordId */);
}
if (csn->filter) {
// The 'stopApplyingFilterAfterFirstMatch' optimization is only applicable when the 'ts'
// lower bound is also provided for an oplog scan, and is handled in
// 'generateOptimizedOplogScan()'.
invariant(!csn->stopApplyingFilterAfterFirstMatch);
auto relevantSlots = sbe::makeSV(resultSlot, recordIdSlot);
auto [_, outputStage] = generateFilter(state,
csn->filter.get(),
{std::move(stage), std::move(relevantSlots)},
resultSlot,
csn->nodeId());
stage = std::move(outputStage.stage);
}
PlanStageSlots outputs;
outputs.set(PlanStageSlots::kResult, resultSlot);
outputs.set(PlanStageSlots::kRecordId, recordIdSlot);
return {std::move(stage), std::move(outputs)};
}
} // namespace
std::pair<std::unique_ptr<sbe::PlanStage>, PlanStageSlots> generateCollScan(
StageBuilderState& state,
const CollectionPtr& collection,
const CollectionScanNode* csn,
PlanYieldPolicy* yieldPolicy,
bool isTailableResumeBranch) {
if (csn->minRecord || csn->maxRecord || csn->stopApplyingFilterAfterFirstMatch) {
return generateOptimizedOplogScan(
state, collection, csn, yieldPolicy, isTailableResumeBranch);
} else {
return generateGenericCollScan(state, collection, csn, yieldPolicy, isTailableResumeBranch);
}
}
} // namespace mongo::stage_builder
| 53.731132 | 100 | 0.56173 | [
"vector"
] |
f301a9c5428ecb410076ebc83af8160ffac0b0d3 | 764 | cpp | C++ | persistence/src/vespa/persistence/spi/abstractpersistenceprovider.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | persistence/src/vespa/persistence/spi/abstractpersistenceprovider.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | persistence/src/vespa/persistence/spi/abstractpersistenceprovider.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "abstractpersistenceprovider.h"
#include <vespa/document/base/documentid.h>
#include <vespa/vespalib/util/idestructorcallback.h>
namespace storage::spi {
void
AbstractPersistenceProvider::removeIfFoundAsync(const Bucket& b, Timestamp timestamp,
const DocumentId& id, OperationComplete::UP onComplete)
{
std::vector<TimeStampAndDocumentId> ids;
ids.emplace_back(timestamp, id);
removeAsync(b, std::move(ids), std::move(onComplete));
}
BucketIdListResult
AbstractPersistenceProvider::getModifiedBuckets(BucketSpace) const
{
return BucketIdListResult(BucketIdListResult::List());
}
}
| 30.56 | 104 | 0.736911 | [
"vector"
] |
f301ced7c6e9a8485bbb0f4c2b013d8b5ca40498 | 41,783 | cpp | C++ | DataViewer/OGRColumn.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | DataViewer/OGRColumn.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | DataViewer/OGRColumn.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | /**
* GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved
*
* This file is part of GeoDa.
*
* GeoDa is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GeoDa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <istream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <set>
#include <boost/foreach.hpp>
#include <locale>
#include <wx/regex.h>
#include <wx/numformatter.h>
#include "../GenUtils.h"
#include "../GeoDa.h"
#include "../logger.h"
#include "../ShapeOperations/OGRDataAdapter.h"
#include "../GdaException.h"
#include "OGRColumn.h"
#include "VarOrderMapper.h"
using namespace std;
OGRColumn::OGRColumn(wxString name, int field_length, int decimals, int n_rows)
: name(name), length(field_length), decimals(decimals), is_new(true), is_deleted(false), rows(n_rows)
{
}
OGRColumn::OGRColumn(OGRLayerProxy* _ogr_layer,
wxString name, int field_length,int decimals)
: name(name), ogr_layer(_ogr_layer), length(field_length), decimals(decimals),
is_new(true), is_deleted(false)
{
rows = ogr_layer->GetNumRecords();
}
OGRColumn::OGRColumn(OGRLayerProxy* _ogr_layer, int idx)
{
// note: idx is only valid when create a OGRColumn. It's value could be
// updated when delete columns in OGRLayer. Therefore, return current
// column index will always dynamically fetch from GetColIndex() by using
// the column name.
is_new = false;
is_deleted = false;
ogr_layer = _ogr_layer;
rows = ogr_layer->GetNumRecords();
name = ogr_layer->GetFieldName(idx);
length = ogr_layer->GetFieldLength(idx);
decimals = ogr_layer->GetFieldDecimals(idx);
}
int OGRColumn::GetColIndex()
{
if (is_new) return -1;
return ogr_layer->GetFieldPos(name);
}
int OGRColumn::GetLength()
{
if (is_new) return length;
length = ogr_layer->GetFieldLength(GetColIndex());
return length;
}
void OGRColumn::SetLength(int new_length)
{
if (!is_new)
ogr_layer->SetFieldLength(GetColIndex(), new_length);
length = new_length;
}
int OGRColumn::GetDecimals()
{
if (is_new) return decimals;
decimals = ogr_layer->GetFieldDecimals(GetColIndex());
return decimals;
}
void OGRColumn::SetDecimals(int new_decimals)
{
if (!is_new)
ogr_layer->SetFieldDecimals(GetColIndex(), new_decimals);
decimals = new_decimals;
}
wxString OGRColumn::GetName()
{
if (!is_new) name = ogr_layer->GetFieldName(GetColIndex());
return name;
}
void OGRColumn::Rename(const wxString& new_name)
{
if (!is_new)
ogr_layer->SetFieldName(GetColIndex(), new_name);
name = new_name;
}
void OGRColumn::UpdateOGRLayer(OGRLayerProxy* new_ogr_layer)
{
ogr_layer = new_ogr_layer;
}
bool OGRColumn::IsCellUpdated(int row)
{
if (!undef_markers.empty()) {
return undef_markers[row];
}
return false;
}
bool OGRColumn::IsUndefined(int row)
{
return undef_markers[row];
}
void OGRColumn::UpdateData(const vector<double> &data)
{
wxString msg = "Internal error: UpdateData(double) not implemented.";
throw GdaException(msg.mb_str());
}
void OGRColumn::UpdateData(const vector<wxInt64> &data)
{
wxString msg = "Internal error: UpdateData(wxInt64) not implemented.";
throw GdaException(msg.mb_str());
}
void OGRColumn::UpdateData(const vector<wxString> &data)
{
wxString msg = "Internal error: UpdateData(wxString) not implemented.";
throw GdaException(msg.mb_str());
}
void OGRColumn::UpdateData(const vector<double> &data,
const vector<bool>& undef_markers_)
{
UpdateData(data);
undef_markers = undef_markers_;
}
void OGRColumn::UpdateData(const vector<wxInt64> &data,
const vector<bool>& undef_markers_)
{
UpdateData(data);
undef_markers = undef_markers_;
}
void OGRColumn::UpdateData(const vector<wxString> &data,
const vector<bool>& undef_markers_)
{
UpdateData(data);
undef_markers = undef_markers_;
}
void OGRColumn::FillData(vector<double>& data)
{
wxString msg = "Internal error: FillData(double) not implemented.";
throw GdaException(msg.mb_str());
}
void OGRColumn::FillData(vector<wxInt64>& data)
{
wxString msg = "Internal error: FillData(wxInt64) not implemented.";
throw GdaException(msg.mb_str());
}
void OGRColumn::FillData(vector<wxString>& data)
{
wxString msg = "Internal error: FillData(wxString) not implemented.";
throw GdaException(msg.mb_str());
}
void OGRColumn::FillData(vector<double> &data,
vector<bool>& undef_markers_)
{
FillData(data);
undef_markers_ = undef_markers;
}
void OGRColumn::FillData(vector<wxInt64> &data,
vector<bool>& undef_markers_)
{
FillData(data);
undef_markers_ = undef_markers;
}
void OGRColumn::FillData(vector<wxString> &data,
vector<bool>& undef_markers_)
{
FillData(data);
undef_markers_ = undef_markers;
}
bool OGRColumn::GetCellValue(int row, wxInt64& val)
{
wxString msg = "Internal error: GetCellValue(wxInt64) not implemented.";
throw GdaException(msg.mb_str());
}
bool OGRColumn::GetCellValue(int row, double& val)
{
wxString msg = "Internal error: GetCellValue(double) not implemented.";
throw GdaException(msg.mb_str());
}
bool OGRColumn::GetCellValue(int row, wxString& val)
{
wxString msg = "Internal error: GetCellValue(wxString) not implemented.";
throw GdaException(msg.mb_str());
}
void OGRColumn::UpdateNullMarkers(const vector<bool>& undef_markers_)
{
if (!undef_markers_.empty())
undef_markers = undef_markers_;
}
////////////////////////////////////////////////////////////////////////////////
//
OGRColumnInteger::OGRColumnInteger(wxString name, int field_length, int decimals, int n_rows)
: OGRColumn(name, field_length, decimals, n_rows)
{
// a new in-memory integer column
is_new = true;
new_data.resize(rows);
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
new_data[i] = 0;
undef_markers[i] = false;
}
}
OGRColumnInteger::OGRColumnInteger(OGRLayerProxy* ogr_layer, wxString name,
int field_length, int decimals)
: OGRColumn(ogr_layer, name, field_length, decimals)
{
// a new integer column
is_new = true;
new_data.resize(rows);
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
new_data[i] = 0;
undef_markers[i] = false;
}
}
OGRColumnInteger::OGRColumnInteger(OGRLayerProxy* ogr_layer, int idx)
:OGRColumn(ogr_layer, idx)
{
// a integer column from OGRLayer
is_new = false;
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
// for non-undefined value
if ( ogr_layer->data[i]->IsFieldSet(idx) )
undef_markers[i] = false;
else
undef_markers[i] = true;
}
}
OGRColumnInteger::~OGRColumnInteger()
{
if (new_data.size() > 0 ) new_data.clear();
if (undef_markers.size() > 0) undef_markers.clear();
}
// Return this column to a vector of wxInt64
void OGRColumnInteger::FillData(vector<wxInt64> &data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
data[i] = new_data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
data[i] = (wxInt64)ogr_layer->data[i]->GetFieldAsInteger64(col_idx);
}
}
}
// Return this column to a vector of double
void OGRColumnInteger::FillData(vector<double> &data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
data[i] = (double)new_data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
data[i] = (double)ogr_layer->data[i]->GetFieldAsInteger64(col_idx);
}
}
}
// Return this column to a vector of wxString
void OGRColumnInteger::FillData(vector<wxString> &data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
data[i] = wxString::Format(wxT("%") wxT(wxLongLongFmtSpec) wxT("d"), new_data[i]);
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
data[i] = wxString::Format(wxT("%") wxT(wxLongLongFmtSpec) wxT("d"),
ogr_layer->data[i]->GetFieldAsInteger64(col_idx));
}
}
}
// Update this column from a vector of wxInt64
void OGRColumnInteger::UpdateData(const vector<wxInt64>& data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
new_data[i] = data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
ogr_layer->data[i]->SetField(col_idx, (GIntBig)data[i]);
}
}
}
void OGRColumnInteger::UpdateData(const vector<double>& data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
new_data[i] = (int)data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
ogr_layer->data[i]->SetField(col_idx, (GIntBig)data[i]);
}
}
}
// Return an integer value from a cell at position (row)
bool OGRColumnInteger::GetCellValue(int row, wxInt64& val)
{
if (undef_markers[row] == true) {
val = 0;
return false;
}
if (is_new) {
val = new_data[row];
} else {
int col_idx = GetColIndex();
val = (wxInt64)ogr_layer->data[row]->GetFieldAsInteger64(col_idx);
}
return true;
}
// Return a String value from a cell at position (row)
// Note: used by wxGrid Table
wxString OGRColumnInteger::GetValueAt(int row_idx, int disp_decimals,
wxCSConv* m_wx_encoding)
{
// if is undefined, return empty string
if ( undef_markers[row_idx] == true)
return wxEmptyString;
if (is_new) {
return wxString::Format("%lld",new_data[row_idx]);
} else {
int col_idx = GetColIndex();
if (col_idx == -1)
return wxEmptyString;
wxLongLong val(ogr_layer->data[row_idx]->GetFieldAsInteger64(col_idx));
return val.ToString();
}
}
// Set a cell value from user input wxString (in Table/wxGrid)
void OGRColumnInteger::SetValueAt(int row_idx, const wxString &value)
{
// if is already undefined, and user inputs nothing
if ( undef_markers[row_idx] == true && value.IsEmpty() ) {
return;
}
int col_idx = GetColIndex();
if ( value.IsEmpty() ) {
undef_markers[row_idx] = true;
if (!is_new) {
if (col_idx >=0) {
ogr_layer->data[row_idx]->UnsetField(col_idx);
}
}
return;
}
wxInt64 l_val;
if ( GenUtils::validInt(value) ) {
GenUtils::strToInt64(value, &l_val);
if (is_new) {
new_data[row_idx] = l_val;
} else {
if (col_idx == -1)
return;
ogr_layer->data[row_idx]->SetField(col_idx, (GIntBig)l_val);
}
undef_markers[row_idx] = false;
}
}
////////////////////////////////////////////////////////////////////////////////
//
OGRColumnDouble::OGRColumnDouble(wxString name, int field_length,
int decimals, int n_rows)
: OGRColumn(name, field_length, decimals, n_rows)
{
// a new in-memory integer column
if ( decimals < 0)
decimals = GdaConst::default_dbf_double_decimals;
is_new = true;
new_data.resize(rows);
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
new_data[i] = 0.0;
undef_markers[i] = false;
}
}
OGRColumnDouble::OGRColumnDouble(OGRLayerProxy* ogr_layer, wxString name,
int field_length, int decimals)
: OGRColumn(ogr_layer, name, field_length, decimals)
{
// a new double column
if ( decimals < 0)
decimals = GdaConst::default_dbf_double_decimals;
is_new = true;
new_data.resize(rows);
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
new_data[i] = 0.0;
undef_markers[i] = false;
}
}
OGRColumnDouble::OGRColumnDouble(OGRLayerProxy* ogr_layer, int idx)
:OGRColumn(ogr_layer, idx)
{
// a double column from OGRLayer
if ( decimals < 0)
decimals = GdaConst::default_dbf_double_decimals;
is_new = false;
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
// for non-undefined value
if ( ogr_layer->data[i]->IsFieldSet(idx) )
undef_markers[i] = false;
else
undef_markers[i] = true;
}
}
OGRColumnDouble::~OGRColumnDouble()
{
if (new_data.size() > 0 )
new_data.clear();
if (undef_markers.size() > 0)
undef_markers.clear();
}
// Assign this column to a vector of wxInt64
void OGRColumnDouble::FillData(vector<wxInt64> &data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
data[i] = (wxInt64)new_data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
data[i] = (wxInt64)ogr_layer->data[i]->GetFieldAsDouble(col_idx);
}
}
}
// Assign this column to a vector of double
void OGRColumnDouble::FillData(vector<double> &data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
data[i] = new_data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
data[i] = ogr_layer->data[i]->GetFieldAsDouble(col_idx);
}
}
}
void OGRColumnDouble::FillData(vector<wxString> &data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
data[i] = wxString::Format("%f", new_data[i]);
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
data[i] = wxString::Format("%f",
ogr_layer->data[i]->GetFieldAsDouble(col_idx));
}
}
}
// Update this column from a vector of double
void OGRColumnDouble::UpdateData(const vector<double>& data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
new_data[i] = data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
ogr_layer->data[i]->SetField(col_idx, data[i]);
}
}
}
void OGRColumnDouble::UpdateData(const vector<wxInt64>& data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
new_data[i] = (double)data[i];
undef_markers[i] = false;
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
ogr_layer->data[i]->SetField(col_idx, (double)data[i]);
undef_markers[i] = false;
}
}
}
// Fill a double value from a cell at position (row)
bool OGRColumnDouble::GetCellValue(int row, double& val)
{
if (undef_markers[row] == true) {
val = 0.0;
return false;
}
if (is_new) {
val = new_data[row];
} else {
int col_idx = GetColIndex();
val = ogr_layer->data[row]->GetFieldAsDouble(col_idx);
}
return true;
}
// Return a String value from a cell at position (row)
// Note: used by wxGrid Table
wxString OGRColumnDouble::GetValueAt(int row_idx, int disp_decimals,
wxCSConv* m_wx_encoding)
{
if (undef_markers[row_idx] == true)
return wxEmptyString;
if ( disp_decimals < 0)
disp_decimals = GdaConst::default_dbf_double_decimals;
double val;
if (is_new) {
val = new_data[row_idx];
wxString rst = wxNumberFormatter::ToString(val, disp_decimals,
wxNumberFormatter::Style_None);
return rst;
} else {
int col_idx = GetColIndex();
if (col_idx == -1)
return wxEmptyString;
const char* tmp = ogr_layer->data[row_idx]->GetFieldAsString(col_idx);
if (*tmp == '\0' ) {
return wxEmptyString;
}
val = ogr_layer->data[row_idx]->GetFieldAsDouble(col_idx);
wxString rst = wxNumberFormatter::ToString(val, disp_decimals,
wxNumberFormatter::Style_None);
return rst;
}
}
// Set a cell value from user input wxString (in Table/wxGrid)
void OGRColumnDouble::SetValueAt(int row_idx, const wxString &value)
{
// if user inputs nothing for a double valued cell, GeoDa treats it as NULL
if ( value.IsEmpty() ) {
undef_markers[row_idx] = true;
if (is_new ) {
new_data[row_idx] = 0.0;
} else {
// set undefined/null
ogr_layer->data[row_idx]->UnsetField(row_idx);
}
return;
}
double d_val;
if ( value.ToDouble(&d_val) ) {
if (is_new) {
new_data[row_idx] = d_val;
} else {
int col_idx = GetColIndex();
ogr_layer->data[row_idx]->SetField(col_idx, d_val);
}
undef_markers[row_idx] = false;
}
}
////////////////////////////////////////////////////////////////////////////////
//
OGRColumnString::OGRColumnString(wxString name, int field_length,
int decimals, int n_rows)
: OGRColumn(name, field_length, decimals, n_rows)
{
// a new in-memory string column
is_new = true;
new_data.resize(rows);
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
new_data[i] = wxEmptyString;
undef_markers[i] = false;
}
}
OGRColumnString::OGRColumnString(OGRLayerProxy* ogr_layer, wxString name,
int field_length, int decimals)
: OGRColumn(ogr_layer, name, field_length, decimals)
{
// a new string column
is_new = true;
new_data.resize(rows);
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
new_data[i] = wxEmptyString;
undef_markers[i] = false;
}
}
OGRColumnString::OGRColumnString(OGRLayerProxy* ogr_layer, int idx)
:OGRColumn(ogr_layer, idx)
{
// a string column from OGRLayer
is_new = false;
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
if ( ogr_layer->data[i]->IsFieldSet(idx) )
undef_markers[i] = false;
else
undef_markers[i] = true;
}
}
OGRColumnString::~OGRColumnString()
{
if (new_data.size() > 0 )
new_data.clear();
if (undef_markers.size() > 0)
undef_markers.clear();
}
// This column -> vector<double>
void OGRColumnString::FillData(vector<double>& data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
double val = 0.0;
if ( !new_data[i].ToDouble(&val) ) {
// internal is always local "C"
//wxString error_msg = wxString::Format( "Fill data error: can't convert '%s' to floating-point number.", new_data[i]);
//throw GdaException(error_msg.c_str());
undef_markers[i] = true;
}
data[i] = val;
}
} else {
int col_idx = GetColIndex();
wxString tmp;
// default C locale
for (int i=0; i<rows; ++i) {
if ( undef_markers[i] == true) {
data[i] = 0.0;
continue;
}
tmp = wxString(ogr_layer->data[i]->GetFieldAsString(col_idx));
double val;
if (tmp.IsEmpty()) {
data[i] = 0.0;
undef_markers[i] = true;
} else if (tmp.ToDouble(&val)) {
data[i] = val;
} else {
// try comma as decimal point
setlocale(LC_NUMERIC, "de_DE");
double _val;
if (tmp.ToDouble(&_val)) {
data[i] = _val;
} else {
data[i] = 0.0;
undef_markers[i] = true;
}
setlocale(LC_NUMERIC, "C");
}
}
}
}
// This column -> vector<wxInt64>
void OGRColumnString::FillData(vector<wxInt64> &data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
wxInt64 val = 0;
if (!new_data[i].ToLongLong(&val)) {
//wxString error_msg = wxString::Format("Fill data error: can't convert '%s' to integer number.", new_data[i]);
//throw GdaException(error_msg.mb_str());
double d_val;
if (new_data[i].ToDouble(&d_val)) {
val = static_cast<wxInt64>(d_val);
data[i] = val;
} else {
undef_markers[i] = true;
data[i] = 0;
}
} else {
data[i] = val;
}
}
} else {
int col_idx = GetColIndex();
bool conv_success = true;
wxString tmp;
// default C locale
for (int i=0; i<rows; ++i) {
if ( undef_markers[i] == true) {
data[i] = 0;
continue;
}
tmp = wxString(ogr_layer->data[i]->GetFieldAsString(col_idx));
wxInt64 val;
double val_d;
if (tmp.IsEmpty()) {
undef_markers[i] = true;
data[i] = 0;
} else if (tmp.ToLongLong(&val)) {
data[i] = val;
} else if (tmp.ToDouble(&val_d)) {
val = static_cast<wxInt64>(val_d);
data[i] = val;
} else {
setlocale(LC_NUMERIC, "de_DE");
wxInt64 val_;
double val_d_;
if (tmp.ToLongLong(&val_)) {
data[i] = val_;
} else if (tmp.ToDouble(&val_d_)) {
val_ = static_cast<wxInt64>(val_d_);
data[i] = val_;
} else {
data[i] = 0;
undef_markers[i] = true;
}
setlocale(LC_NUMERIC, "C");
}
}
}
}
// This column -> vector<wxString>
void OGRColumnString::FillData(vector<wxString> &data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
data[i] = new_data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
data[i] = wxString(ogr_layer->data[i]->GetFieldAsString(col_idx));
}
}
}
// vector<wxString> -> this column
void OGRColumnString::UpdateData(const vector<wxString>& data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
new_data[i] = data[i];
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
ogr_layer->data[i]->SetField(col_idx, data[i].c_str());
}
}
}
void OGRColumnString::UpdateData(const vector<wxInt64>& data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
wxString tmp;
tmp << data[i];
new_data[i] = tmp.c_str();
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
wxString tmp;
tmp << data[i];
ogr_layer->data[i]->SetField(col_idx, tmp.c_str());
}
}
}
void OGRColumnString::UpdateData(const vector<double>& data)
{
if (is_new) {
for (int i=0; i<rows; ++i) {
wxString tmp;
tmp << data[i];
new_data[i] = tmp.c_str();
}
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
wxString tmp;
tmp << data[i];
ogr_layer->data[i]->SetField(col_idx, tmp.c_str());
}
}
}
// Fill a wxString value from a cell at position (row)
bool OGRColumnString::GetCellValue(int row, wxString& val)
{
if (undef_markers[row] == true) {
val = wxEmptyString;
return false;
}
if (is_new) {
val = new_data[row];
} else {
int col_idx = GetColIndex();
const char* val = ogr_layer->data[row]->GetFieldAsString(col_idx);
val = wxString(val);
}
return true;
}
wxString OGRColumnString::GetValueAt(int row_idx, int disp_decimals,
wxCSConv* m_wx_encoding)
{
if (undef_markers[row_idx] == true)
return wxEmptyString;
if (is_new) {
return new_data[row_idx];
} else {
int col_idx = GetColIndex();
if (col_idx == -1)
return wxEmptyString;
const char* val = ogr_layer->data[row_idx]->GetFieldAsString(col_idx);
wxString rtn;
if (m_wx_encoding == NULL)
rtn = wxString(val);
else
rtn = wxString(val,*m_wx_encoding);
return rtn;
}
}
void OGRColumnString::SetValueAt(int row_idx, const wxString &value)
{
// if user inputs nothing for a undefined cell
if ( undef_markers[row_idx] == true && value.IsEmpty() ) {
return;
}
if (is_new) {
new_data[row_idx] = value;
} else {
int col_idx = GetColIndex();
ogr_layer->data[row_idx]->SetField(col_idx, value.c_str());
}
undef_markers[row_idx] = false;
}
////////////////////////////////////////////////////////////////////////////////
// XXX current GeoDa don't support adding new date column
//
OGRColumnDate::OGRColumnDate(OGRLayerProxy* ogr_layer, int idx)
:OGRColumn(ogr_layer, idx)
{
is_new = false;
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
if ( ogr_layer->data[i]->IsFieldSet(idx) )
undef_markers[i] = false;
else
undef_markers[i] = true;
}
}
OGRColumnDate::~OGRColumnDate()
{
if (new_data.size() > 0 ) new_data.clear();
}
void OGRColumnDate::FillData(vector<wxInt64> &data)
{
if (is_new) {
wxString msg = "Internal error: GeoDa doesn't support new date column.";
throw GdaException(msg.mb_str());
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
if (undef_markers[i]) {
data[i] = 0.0;
continue;
}
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
int col_idx = GetColIndex();
ogr_layer->data[i]->GetFieldAsDateTime(col_idx, &year, &month, &day,&hour, &minute, &second, &tzflag);
wxInt64 ldatetime = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second;
data[i] = ldatetime;
}
}
}
void OGRColumnDate::FillData(vector<wxString> &data)
{
if (is_new) {
wxString msg = "Internal error: GeoDa doesn't support new date column.";
throw GdaException(msg.mb_str());
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
if (undef_markers[i]) {
data[i] = "";
continue;
}
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
ogr_layer->data[i]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
data[i] = ogr_layer->data[i]->GetFieldAsString(col_idx);
}
}
}
bool OGRColumnDate::GetCellValue(int row, wxInt64& val)
{
if (undef_markers[row] == true) {
val = 0;
return false;
}
if (new_data.empty()) {
int col_idx = GetColIndex();
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
ogr_layer->data[row]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
val = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second;
} else {
val = new_data[row];
}
return true;
}
wxString OGRColumnDate::GetValueAt(int row_idx, int disp_decimals,
wxCSConv* m_wx_encoding)
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
if (new_data.empty()) {
int col_idx = GetColIndex();
ogr_layer->data[row_idx]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
} else {
//val = new_data[row_idx];
}
wxString sDateTime;
if (year >0 && month > 0 && day > 0) {
sDateTime << wxString::Format("%i-%i-%i", year, month, day);
}
if (hour >0 || minute > 0 || second > 0) {
if (!sDateTime.IsEmpty()) sDateTime << " ";
sDateTime << wxString::Format("%i:%i:%i", hour, minute, second);
}
return sDateTime;
}
void OGRColumnDate::SetValueAt(int row_idx, const wxString &value)
{
wxRegEx regex;
wxString date_regex_str = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})";
wxString _year, _month, _day, _hour, _minute, _second;
regex.Compile(date_regex_str);
if (regex.Matches(value)) {
//wxString _all = regex.GetMatch(value,0);
_year = regex.GetMatch(value,1);
_month = regex.GetMatch(value,2);
_day = regex.GetMatch(value,3);
}
long _l_year =0, _l_month=0, _l_day=0, _l_hour=0, _l_minute=0, _l_second=0;
_year.ToLong(&_l_year);
_month.ToLong(&_l_month);
_day.ToLong(&_l_day);
wxInt64 val = _l_year * 10000000000 + _l_month * 100000000 + _l_day * 1000000 + _l_hour * 10000 + _l_minute * 100 + _l_second;
if (is_new) {
new_data[row_idx] = val;
} else {
int col_idx = GetColIndex();
ogr_layer->data[row_idx]->SetField(col_idx, _l_year, _l_month, _l_day, _l_hour, _l_minute, _l_second, 0); // last TZFlag
}
}
////////////////////////////////////////////////////////////////////////////////
// OGRColumnTime
OGRColumnTime::OGRColumnTime(OGRLayerProxy* ogr_layer, int idx)
:OGRColumn(ogr_layer, idx)
{
is_new = false;
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
if ( ogr_layer->data[i]->IsFieldSet(idx) )
undef_markers[i] = false;
else
undef_markers[i] = true;
}
}
OGRColumnTime::~OGRColumnTime()
{
if (new_data.size() > 0 ) new_data.clear();
}
void OGRColumnTime::FillData(vector<wxInt64> &data)
{
if (is_new) {
wxString msg = "Internal error: GeoDa doesn't support new date column.";
throw GdaException(msg.mb_str());
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
int col_idx = GetColIndex();
ogr_layer->data[i]->GetFieldAsDateTime(col_idx, &year, &month, &day,&hour, &minute, &second, &tzflag);
wxInt64 ldatetime = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second;
data[i] = ldatetime;
}
}
}
void OGRColumnTime::FillData(vector<wxString> &data)
{
if (is_new) {
wxString msg = "Internal error: GeoDa doesn't support new Time column.";
throw GdaException(msg.mb_str());
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
ogr_layer->data[i]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
data[i] = ogr_layer->data[i]->GetFieldAsString(col_idx);
}
}
}
bool OGRColumnTime::GetCellValue(int row, wxInt64& val)
{
if (undef_markers[row] == true) {
val = 0;
return false;
}
/*
if (new_data.empty()) {
int col_idx = GetColIndex();
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
ogr_layer->data[row]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
//val = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second;
} else {
//val = new_data[row];
}
*/
return true;
}
wxString OGRColumnTime::GetValueAt(int row_idx, int disp_decimals,
wxCSConv* m_wx_encoding)
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
if (new_data.empty()) {
int col_idx = GetColIndex();
ogr_layer->data[row_idx]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
} else {
//val = new_data[row_idx];
}
wxString sDateTime;
if (hour >0 || minute > 0 || second > 0) {
sDateTime << wxString::Format("%i:%i:%i", hour, minute, second);
}
return sDateTime;
}
void OGRColumnTime::SetValueAt(int row_idx, const wxString &value)
{
wxRegEx regex;
wxString time_regex_str = "([0-9]{2}):([0-9]{2}):([0-9]{2})";
wxString _hour, _minute, _second;
regex.Compile(time_regex_str);
if (regex.Matches(value)) {
_hour = regex.GetMatch(value,1);
_minute = regex.GetMatch(value,2);
_second = regex.GetMatch(value,3);
}
long _l_year =0, _l_month=0, _l_day=0, _l_hour=0, _l_minute=0, _l_second=0;
_hour.ToLong(&_l_hour);
_minute.ToLong(&_l_minute);
_second.ToLong(&_l_second);
wxInt64 val = _l_year * 10000000000 + _l_month * 100000000 + _l_day * 1000000 + _l_hour * 10000 + _l_minute * 100 + _l_second;
if (is_new) {
new_data[row_idx] = val;
} else {
int col_idx = GetColIndex();
ogr_layer->data[row_idx]->SetField(col_idx, _l_year, _l_month, _l_day, _l_hour, _l_minute, _l_second, 0); // last TZFlag
}
}
////////////////////////////////////////////////////////////////////////////////
//OGRColumnDateTime
OGRColumnDateTime::OGRColumnDateTime(OGRLayerProxy* ogr_layer, int idx)
:OGRColumn(ogr_layer, idx)
{
is_new = false;
undef_markers.resize(rows);
for (int i=0; i<rows; ++i) {
if ( ogr_layer->data[i]->IsFieldSet(idx) )
undef_markers[i] = false;
else
undef_markers[i] = true;
}
}
OGRColumnDateTime::~OGRColumnDateTime()
{
if (new_data.size() > 0 ) new_data.clear();
}
void OGRColumnDateTime::FillData(vector<wxInt64> &data)
{
if (is_new) {
wxString msg = "Internal error: GeoDa doesn't support new date column.";
throw GdaException(msg.mb_str());
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
int col_idx = GetColIndex();
ogr_layer->data[i]->GetFieldAsDateTime(col_idx, &year, &month, &day,&hour, &minute, &second, &tzflag);
wxInt64 ldatetime = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second;
data[i] = ldatetime;
}
}
}
void OGRColumnDateTime::FillData(vector<wxString>& data)
{
if (is_new) {
wxString msg = "Internal error: GeoDa doesn't support new date column.";
throw GdaException(msg.mb_str());
} else {
int col_idx = GetColIndex();
for (int i=0; i<rows; ++i) {
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
ogr_layer->data[i]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
data[i] = ogr_layer->data[i]->GetFieldAsString(col_idx);
}
}
}
bool OGRColumnDateTime::GetCellValue(int row, wxInt64& val)
{
if (undef_markers[row] == true) {
val = 0;
return false;
}
if (new_data.empty()) {
int col_idx = GetColIndex();
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
ogr_layer->data[row]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
val = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second;
} else {
val = new_data[row];
}
return true;
}
wxString OGRColumnDateTime::GetValueAt(int row_idx, int disp_decimals,
wxCSConv* m_wx_encoding)
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int tzflag = 0;
if (new_data.empty()) {
int col_idx = GetColIndex();
ogr_layer->data[row_idx]->GetFieldAsDateTime(col_idx, &year, &month,
&day,&hour,&minute,
&second, &tzflag);
} else {
//val = new_data[row_idx];
}
wxString sDateTime;
if (year >0 && month > 0 && day > 0) {
sDateTime << wxString::Format("%i-%i-%i", year, month, day);
}
if (hour >0 || minute > 0 || second > 0) {
if (!sDateTime.IsEmpty()) sDateTime << " ";
sDateTime << wxString::Format("%i:%i:%i", hour, minute, second);
}
return sDateTime;
}
void OGRColumnDateTime::SetValueAt(int row_idx, const wxString &value)
{
wxRegEx regex;
wxString time_regex_str = "([0-9]{2}):([0-9]{2}):([0-9]{2})";
wxString date_regex_str = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})";
wxString datetime_regex_str = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})";
wxString _year, _month, _day, _hour, _minute, _second;
regex.Compile(time_regex_str);
if (regex.Matches(value)) {
_hour = regex.GetMatch(value,1);
_minute = regex.GetMatch(value,2);
_second = regex.GetMatch(value,3);
} else {
regex.Compile(date_regex_str);
if (regex.Matches(value)) {
//wxString _all = regex.GetMatch(value,0);
_year = regex.GetMatch(value,1);
_month = regex.GetMatch(value,2);
_day = regex.GetMatch(value,3);
} else {
regex.Compile(datetime_regex_str);
if (regex.Matches(value)) {
_year = regex.GetMatch(value,1);
_month = regex.GetMatch(value,2);
_day = regex.GetMatch(value,3);
_hour = regex.GetMatch(value,4);
_minute = regex.GetMatch(value,5);
_second = regex.GetMatch(value,6);
}
}
}
long _l_year =0, _l_month=0, _l_day=0, _l_hour=0, _l_minute=0, _l_second=0;
_year.ToLong(&_l_year);
_month.ToLong(&_l_month);
_day.ToLong(&_l_day);
_hour.ToLong(&_l_hour);
_minute.ToLong(&_l_minute);
_second.ToLong(&_l_second);
wxInt64 val = _l_year * 10000000000 + _l_month * 100000000 + _l_day * 1000000 + _l_hour * 10000 + _l_minute * 100 + _l_second;
if (is_new) {
new_data[row_idx] = val;
} else {
int col_idx = GetColIndex();
ogr_layer->data[row_idx]->SetField(col_idx, _l_year, _l_month, _l_day, _l_hour, _l_minute, _l_second, 0); // last TZFlag
}
}
| 28.098857 | 135 | 0.53663 | [
"vector"
] |
f3026bcfc4e4e5795e0e3f8c3e10acf905b4c1f4 | 4,248 | cpp | C++ | test/transform_vector.cpp | romariorios/coruja | 275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af | [
"BSL-1.0"
] | 13 | 2017-10-24T07:13:28.000Z | 2020-10-07T02:51:31.000Z | test/transform_vector.cpp | romariorios/coruja | 275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af | [
"BSL-1.0"
] | 1 | 2019-10-30T21:50:44.000Z | 2019-11-06T19:35:23.000Z | test/transform_vector.cpp | romariorios/coruja | 275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af | [
"BSL-1.0"
] | 5 | 2018-09-19T20:29:07.000Z | 2020-03-20T18:12:09.000Z | #include "check_equal.hpp"
#include <coruja/container/view/transform.hpp>
#include <coruja/container/vector.hpp>
#include <boost/optional/optional.hpp>
#include <range/v3/back.hpp>
#include <range/v3/front.hpp>
#include <range/v3/range_concepts.hpp>
#include <string>
using namespace coruja;
using svector = vector<std::string>;
struct append_space {
std::string operator()(const std::string& s)
{ return s + " "; }
};
struct append_exclamation {
std::string operator()(const std::string& s)
{ return s + "!"; }
};
struct check_str {
template<typename T>
void operator()(T&& s) const
{
b = true;
BOOST_TEST(s == expected);
}
bool& b;
std::string& expected;
};
template<typename V, typename T>
void run(V& s, T&& t, std::string suffix)
{
bool called{false};
std::string fexpected{"hello" + suffix};
t.for_each(check_str{called, fexpected});
bool bcalled{false};
std::string bexpected{"hello" + suffix};
t.before_erase(check_str{bcalled, bexpected});
BOOST_TEST(called);
BOOST_TEST(ranges::front(t) == "hello" + suffix);
fexpected = "jimmy" + suffix;
called = false;
s.emplace_back("jimmy");
BOOST_TEST(called);
BOOST_TEST(ranges::back(t) == "jimmy" + suffix);
s.erase(s.begin());
BOOST_TEST(bcalled);
bcalled = false;
bexpected = "jimmy" + suffix;
s.erase(s.begin());
BOOST_TEST(bcalled);
}
int main()
{
{
svector s;
auto t = view::transform(s, [](std::string& s){ return s; });
using tsvector = decltype(t);
static_assert(std::is_same<tsvector::observed_t,
svector::observed_t>::value, "");
static_assert(std::is_same<tsvector::for_each_connection_t,
svector::for_each_connection_t>::value, "");
static_assert(std::is_same<tsvector::before_erase_connection_t,
svector::before_erase_connection_t>::value, "");
static_assert(is_observable_erasable_range<svector>::value, "");
static_assert(is_observable_erasable_range<tsvector>::value, "");
}
//default ctor
{
svector s;
auto t = view::transform(s, [](std::string& s){ return s; });
using tsvector = decltype(t);
tsvector def;
}
//view::transform(lv, rv) rv is const
{
svector s{"hello"};
auto t = view::transform(s, [](std::string& s){ return s + "!"; });
run(s, t, "!");
}
//view::transform(lv, rv) rv is non const
{
svector s{"hello"};
auto t = view::transform(s, append_exclamation{});
run(s, t, "!");
}
//view::transform(lv, lv)
{
svector s{"hello"};
append_exclamation f{};
auto t = view::transform(s, f);
run(s, t, "!");
}
//vector | view::transform | view::transform (using lv)
{
svector s{"hello"};
auto t0 = view::transform(s, append_space{});
auto t1 = view::transform(t0, append_exclamation{});
run(s, t1, " !");
}
//vector | view::transform | view::transform (using rv)
{
svector s{"hello"};
auto t = view::transform(view::transform(s, append_space{}),
append_exclamation{});
run(s, t, " !");
}
//observed()
{
svector s{"hello"};
auto t = view::transform(s, append_exclamation{});
BOOST_TEST(t.observed().front() == "hello");
}
//copy ctor
{
svector s{"hello"};
auto t = view::transform(s, append_exclamation{});
auto ct = t;
run(s, ct, "!");
}
//copy assignment operator
{
svector s{"hello"};
auto t = view::transform(s, append_exclamation{});
decltype(t) ct;
ct = t;
run(s, ct, "!");
}
//move ctor
{
svector s{"hello"};
auto t = view::transform(s, append_exclamation{});
auto ct = std::move(t);
run(s, ct, "!");
}
//move assignment operator
{
svector s{"hello"};
auto t = view::transform(s, append_exclamation{});
decltype(t) ct;
ct = std::move(t);
run(s, ct, "!");
}
}
| 25.745455 | 75 | 0.551318 | [
"vector",
"transform"
] |
f3071c1a6e5b287910cfd111d01917e7a0856f36 | 13,740 | cc | C++ | webkit/tools/test_shell/test_shell_webthemecontrol.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | webkit/tools/test_shell/test_shell_webthemecontrol.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | webkit/tools/test_shell/test_shell_webthemecontrol.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 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.
// This file implements a simple generic version of the WebKitThemeEngine,
// which is used to draw all the native controls on a web page. We use this
// file when running in layout test mode in order to remove any
// platform-specific rendering differences due to themes, colors, etc.
//
#include "webkit/tools/test_shell/test_shell_webthemecontrol.h"
#include "base/logging.h"
#include "skia/ext/platform_canvas.h"
#include "skia/ext/skia_utils_win.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkPath.h"
namespace TestShellWebTheme {
const SkColor kEdgeColor = SK_ColorBLACK;
const SkColor kReadOnlyColor = SkColorSetRGB(0xe9, 0xc2, 0xa6);
const SkColor kFgColor = SK_ColorBLACK;
const SkColor kBgColors[] = {
SK_ColorBLACK, // Unknown
SkColorSetRGB(0xc9, 0xc9, 0xc9), // Disabled
SkColorSetRGB(0xf3, 0xe0, 0xd0), // Readonly
SkColorSetRGB(0x89, 0xc4, 0xff), // Normal
SkColorSetRGB(0x43, 0xf9, 0xff), // Hot
SkColorSetRGB(0x20, 0xf6, 0xcc), // Focused
SkColorSetRGB(0x00, 0xf3, 0xac), // Hover
SkColorSetRGB(0xa9, 0xff, 0x12) // Pressed
};
Control::Control(skia::PlatformCanvas *canvas, const SkIRect &irect,
Type ctype, State cstate)
: canvas_(canvas),
irect_(irect),
type_(ctype),
state_(cstate),
left_(irect.fLeft),
right_(irect.fRight),
top_(irect.fTop),
bottom_(irect.fBottom),
height_(irect.height()),
width_(irect.width()),
edge_color_(kEdgeColor),
bg_color_(kBgColors[cstate]),
fg_color_(kFgColor) {
}
Control::~Control() {
}
void Control::box(const SkIRect &rect, SkColor fill_color) {
SkPaint paint;
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(fill_color);
canvas_->drawIRect(rect, paint);
paint.setColor(edge_color_);
paint.setStyle(SkPaint::kStroke_Style);
canvas_->drawIRect(rect, paint);
}
void Control::line(int x0, int y0, int x1, int y1, SkColor color) {
SkPaint paint;
paint.setColor(color);
canvas_->drawLine(SkIntToScalar(x0), SkIntToScalar(y0),
SkIntToScalar(x1), SkIntToScalar(y1),
paint);
}
void Control::triangle(int x0, int y0,
int x1, int y1,
int x2, int y2,
SkColor color) {
SkPath path;
SkPaint paint;
paint.setColor(color);
paint.setStyle(SkPaint::kFill_Style);
path.incReserve(4);
path.moveTo(SkIntToScalar(x0), SkIntToScalar(y0));
path.lineTo(SkIntToScalar(x1), SkIntToScalar(y1));
path.lineTo(SkIntToScalar(x2), SkIntToScalar(y2));
path.close();
canvas_->drawPath(path, paint);
paint.setColor(edge_color_);
paint.setStyle(SkPaint::kStroke_Style);
canvas_->drawPath(path, paint);
}
void Control::roundRect(SkColor color) {
SkRect rect;
SkScalar radius = SkIntToScalar(5);
SkPaint paint;
rect.set(irect_);
paint.setColor(color);
paint.setStyle(SkPaint::kFill_Style);
canvas_->drawRoundRect(rect, radius, radius, paint);
paint.setColor(edge_color_);
paint.setStyle(SkPaint::kStroke_Style);
canvas_->drawRoundRect(rect, radius, radius, paint);
}
void Control::oval(SkColor color) {
SkRect rect;
SkPaint paint;
rect.set(irect_);
paint.setColor(color);
paint.setStyle(SkPaint::kFill_Style);
canvas_->drawOval(rect, paint);
paint.setColor(edge_color_);
paint.setStyle(SkPaint::kStroke_Style);
canvas_->drawOval(rect, paint);
}
void Control::circle(SkScalar radius, SkColor color) {
SkScalar cy = SkIntToScalar(top_ + height_ / 2);
SkScalar cx = SkIntToScalar(left_ + width_ / 2);
SkPaint paint;
paint.setColor(color);
paint.setStyle(SkPaint::kFill_Style);
canvas_->drawCircle(cx, cy, radius, paint);
paint.setColor(edge_color_);
paint.setStyle(SkPaint::kStroke_Style);
canvas_->drawCircle(cx, cy, radius, paint);
}
void Control::nested_boxes(int indent_left, int indent_top,
int indent_right, int indent_bottom,
SkColor outer_color, SkColor inner_color) {
SkIRect lirect;
box(irect_, outer_color);
lirect.set(irect_.fLeft + indent_left, irect_.fTop + indent_top,
irect_.fRight - indent_right, irect_.fBottom - indent_bottom);
box(lirect, inner_color);
}
void Control::markState() {
// The horizontal lines in a read only control are spaced by this amount.
const int kReadOnlyLineOffset = 5;
// The length of a triangle side for the corner marks.
const int kTriangleSize = 5;
switch (state_) {
case kUnknown_State: // FALLTHROUGH
case kDisabled_State: // FALLTHROUGH
case kNormal_State:
// Don't visually mark these states (color is enough).
break;
case kReadOnly_State:
// Drawing lines across the control.
for (int i = top_ + kReadOnlyLineOffset; i < bottom_ ;
i += kReadOnlyLineOffset) {
line(left_ + 1, i, right_ - 1, i, kReadOnlyColor);
}
break;
case kHot_State:
// Draw a triangle in the upper left corner of the control.
triangle(left_, top_,
left_ + kTriangleSize, top_,
left_, top_ + kTriangleSize, edge_color_);
break;
case kHover_State:
// Draw a triangle in the upper right corner of the control.
triangle(right_, top_,
right_, top_ + kTriangleSize,
right_ - kTriangleSize, top_, edge_color_);
break;
case kFocused_State:
// Draw a triangle in the bottom right corner of the control.
triangle(right_, bottom_,
right_ - kTriangleSize, bottom_,
right_, bottom_ - kTriangleSize, edge_color_);
break;
case kPressed_State:
// Draw a triangle in the bottom left corner of the control.
triangle(left_, bottom_,
left_, bottom_ - kTriangleSize,
left_ + kTriangleSize, bottom_, edge_color_);
break;
default:
NOTREACHED();
break;
}
}
void Control::draw() {
int half_width = width_ / 2;
int half_height = height_ / 2;
int quarter_width = width_ / 4;
int quarter_height = height_ / 4;
// Indent amounts for the check in a checkbox or radio button.
const int kCheckIndent = 3;
// Indent amounts for short and long sides of the scrollbar notches.
const int kNotchLongOffset = 1;
const int kNotchShortOffset = 4;
const int kNoOffset = 0;
int short_offset;
int long_offset;
// Indent amounts for the short and long sides of a scroll thumb box.
const int kThumbLongIndent = 0;
const int kThumbShortIndent = 2;
// Indents for the crosshatch on a scroll grip.
const int kGripLongIndent = 3;
const int kGripShortIndent = 5;
// Indents for the the slider track.
const int kSliderIndent = 2;
canvas_->beginPlatformPaint();
switch (type_) {
case kUnknown_Type:
NOTREACHED();
break;
case kTextField_Type:
// We render this by hand outside of this function.
NOTREACHED();
break;
case kPushButton_Type:
// push buttons render as a rounded rectangle
roundRect(bg_color_);
break;
case kUncheckedBox_Type:
// Unchecked boxes are simply plain boxes.
box(irect_, bg_color_);
break;
case kCheckedBox_Type:
nested_boxes(kCheckIndent, kCheckIndent, kCheckIndent, kCheckIndent,
bg_color_, fg_color_);
break;
case kUncheckedRadio_Type:
circle(SkIntToScalar(half_height), bg_color_);
break;
case kCheckedRadio_Type:
circle(SkIntToScalar(half_height), bg_color_);
circle(SkIntToScalar(half_height - kCheckIndent), fg_color_);
break;
case kHorizontalScrollTrackBack_Type:
// Draw a box with a notch at the left.
long_offset = half_height - kNotchLongOffset;
short_offset = width_ - kNotchShortOffset;
nested_boxes(kNoOffset, long_offset, short_offset, long_offset,
bg_color_, edge_color_);
break;
case kHorizontalScrollTrackForward_Type:
// Draw a box with a notch at the right.
long_offset = half_height - kNotchLongOffset;
short_offset = width_ - kNotchShortOffset;
nested_boxes(short_offset, long_offset, kNoOffset, long_offset,
bg_color_, fg_color_);
break;
case kVerticalScrollTrackBack_Type:
// Draw a box with a notch at the top.
long_offset = half_width - kNotchLongOffset;
short_offset = height_ - kNotchShortOffset;
nested_boxes(long_offset, kNoOffset, long_offset, short_offset,
bg_color_, fg_color_);
break;
case kVerticalScrollTrackForward_Type:
// Draw a box with a notch at the bottom.
long_offset = half_width - kNotchLongOffset;
short_offset = height_ - kNotchShortOffset;
nested_boxes(long_offset, short_offset, long_offset, kNoOffset,
bg_color_, fg_color_);
break;
case kHorizontalScrollThumb_Type:
// Draw a narrower box on top of the outside box.
nested_boxes(kThumbLongIndent, kThumbShortIndent, kThumbLongIndent,
kThumbShortIndent, bg_color_, bg_color_);
break;
case kVerticalScrollThumb_Type:
// Draw a shorter box on top of the outside box.
nested_boxes(kThumbShortIndent, kThumbLongIndent, kThumbShortIndent,
kThumbLongIndent, bg_color_, bg_color_);
break;
case kHorizontalSliderThumb_Type:
// Slider thumbs are ovals.
oval(bg_color_);
break;
case kHorizontalScrollGrip_Type:
// Draw a horizontal crosshatch for the grip.
long_offset = half_width - kGripLongIndent;
line(left_ + kGripLongIndent, top_ + half_height,
right_ - kGripLongIndent, top_ + half_height, fg_color_);
line(left_ + long_offset, top_ + kGripShortIndent,
left_ + long_offset, bottom_ - kGripShortIndent, fg_color_);
line(right_ - long_offset, top_ + kGripShortIndent,
right_ - long_offset, bottom_ - kGripShortIndent, fg_color_);
break;
case kVerticalScrollGrip_Type:
// Draw a vertical crosshatch for the grip.
long_offset = half_height - kGripLongIndent;
line(left_ + half_width, top_ + kGripLongIndent,
left_ + half_width, bottom_ - kGripLongIndent, fg_color_);
line(left_ + kGripShortIndent, top_ + long_offset,
right_ - kGripShortIndent, top_ + long_offset, fg_color_);
line(left_ + kGripShortIndent, bottom_ - long_offset,
right_ - kGripShortIndent, bottom_ - long_offset, fg_color_);
break;
case kLeftArrow_Type:
// Draw a left arrow inside a box.
box(irect_, bg_color_);
triangle(right_ - quarter_width, top_ + quarter_height,
right_ - quarter_width, bottom_ - quarter_height,
left_ + quarter_width, top_ + half_height, fg_color_);
break;
case kRightArrow_Type:
// Draw a left arrow inside a box.
box(irect_, bg_color_);
triangle(left_ + quarter_width, top_ + quarter_height,
right_ - quarter_width, top_ + half_height,
left_ + quarter_width, bottom_ - quarter_height, fg_color_);
break;
case kUpArrow_Type:
// Draw an up arrow inside a box.
box(irect_, bg_color_);
triangle(left_ + quarter_width, bottom_ - quarter_height,
left_ + half_width, top_ + quarter_height,
right_ - quarter_width, bottom_ - quarter_height, fg_color_);
break;
case kDownArrow_Type:
// Draw a down arrow inside a box.
box(irect_, bg_color_);
triangle(left_ + quarter_width, top_ + quarter_height,
right_ - quarter_width, top_ + quarter_height,
left_ + half_width, bottom_ - quarter_height, fg_color_);
break;
case kHorizontalSliderTrack_Type:
// Draw a narrow rect for the track plus box hatches on the ends.
SkIRect lirect;
lirect = irect_;
lirect.inset(kNoOffset, half_height - kSliderIndent);
box(lirect, bg_color_);
line(left_, top_, left_, bottom_, edge_color_);
line(right_, top_, right_, bottom_, edge_color_);
break;
case kDropDownButton_Type:
// Draw a box with a big down arrow on top.
box(irect_, bg_color_);
triangle(left_ + quarter_width, top_,
right_ - quarter_width, top_,
left_ + half_width, bottom_, fg_color_);
break;
default:
NOTREACHED();
break;
}
markState();
canvas_->endPlatformPaint();
}
// Because rendering a text field is dependent on input
// parameters the other controls don't have, we render it directly
// rather than trying to overcomplicate draw() further.
void Control::drawTextField(bool draw_edges, bool fill_content_area,
SkColor color) {
SkPaint paint;
canvas_->beginPlatformPaint();
if (fill_content_area) {
paint.setColor(color);
paint.setStyle(SkPaint::kFill_Style);
canvas_->drawIRect(irect_, paint);
}
if (draw_edges) {
paint.setColor(edge_color_);
paint.setStyle(SkPaint::kStroke_Style);
canvas_->drawIRect(irect_, paint);
}
markState();
canvas_->endPlatformPaint();
}
} // namespace TestShellWebTheme
| 34.69697 | 77 | 0.65524 | [
"render"
] |
f30fdbdb760f4a0bc21901839a1798fdd35bd8bb | 1,734 | cxx | C++ | Libs/MRML/Core/Testing/vtkMRMLSceneViewNodeTest1.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Libs/MRML/Core/Testing/vtkMRMLSceneViewNodeTest1.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Libs/MRML/Core/Testing/vtkMRMLSceneViewNodeTest1.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*=auto=========================================================================
Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH)
All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
=========================================================================auto=*/
// MRML includes
#include "vtkMRMLCoreTestingMacros.h"
#include "vtkMRMLScene.h"
#include "vtkMRMLSceneViewNode.h"
// VTK includes
#include <vtkCollection.h>
#include <vtkImageData.h>
#include <vtkNew.h>
int vtkMRMLSceneViewNodeTest1(int , char * [] )
{
vtkNew<vtkMRMLSceneViewNode> node1;
// test with null scene
node1->StoreScene();
node1->SetAbsentStorageFileNames();
vtkCollection *col = node1->GetNodesByClass(nullptr);
CHECK_NULL(col);
// make a scene and test again
vtkNew<vtkMRMLScene> scene;
scene->AddNode(node1.GetPointer());
EXERCISE_ALL_BASIC_MRML_METHODS(node1.GetPointer());
node1->StoreScene();
vtkMRMLScene *storedScene = node1->GetStoredScene();
std::cout << "GetStoredScene returned " << (storedScene == nullptr ? "null" : "not null") << std::endl;
node1->SetAbsentStorageFileNames();
TEST_SET_GET_STRING( node1.GetPointer(), SceneViewDescription);
node1->SetScreenShot(nullptr);
vtkImageData *nullImage = node1->GetScreenShot();
CHECK_NULL(nullImage);
vtkImageData *imageData = vtkImageData::New();
node1->SetScreenShot(imageData);
imageData->Delete();
imageData = node1->GetScreenShot();
TEST_SET_GET_INT_RANGE( node1.GetPointer(), ScreenShotType, 0, 4);
col = node1->GetNodesByClass("vtkMRMLNode");
CHECK_NOT_NULL(col);
col->RemoveAllItems();
col->Delete();
return EXIT_SUCCESS;
}
| 26.676923 | 105 | 0.66609 | [
"3d"
] |
f3130bd992a0338b43a59aca7596077940612f87 | 3,312 | cpp | C++ | src/target_jpeg.cpp | folkertvanheusden/constatus | 7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6 | [
"Apache-2.0"
] | 5 | 2021-07-15T11:39:25.000Z | 2022-02-25T06:14:58.000Z | src/target_jpeg.cpp | folkertvanheusden/constatus | 7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6 | [
"Apache-2.0"
] | 2 | 2021-09-27T11:13:42.000Z | 2021-10-10T01:02:39.000Z | src/target_jpeg.cpp | folkertvanheusden/constatus | 7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6 | [
"Apache-2.0"
] | 2 | 2021-06-11T09:19:47.000Z | 2022-02-18T22:22:01.000Z | // (C) 2017-2021 by folkert van heusden, released under Apache License v2.0
#include "config.h"
#include <unistd.h>
#include "target_jpeg.h"
#include "error.h"
#include "exec.h"
#include "log.h"
#include "picio.h"
#include "utils.h"
#include "source.h"
#include "view.h"
#include "filter.h"
#include "schedule.h"
target_jpeg::target_jpeg(const std::string & id, const std::string & descr, source *const s, const std::string & store_path, const std::string & prefix, const std::string & fmt, const int quality, const int max_time, const double interval, const std::vector<filter *> *const filters, const std::string & exec_start, const std::string & exec_cycle, const std::string & exec_end, configuration_t *const cfg, const bool is_view_proxy, const bool handle_failure, schedule *const sched) : target(id, descr, s, store_path, prefix, fmt, max_time, interval, filters, exec_start, exec_cycle, exec_end, -1, cfg, is_view_proxy, handle_failure, sched), quality(quality)
{
if (this -> descr == "")
this -> descr = store_path + "/" + prefix;
}
target_jpeg::~target_jpeg()
{
stop();
}
std::string target_jpeg::write_frame(video_frame *put_f)
{
std::string name = gen_filename(s, fmt, store_path, prefix, "jpg", get_us(), f_nr++);
create_path(name);
if (!exec_start.empty() && is_start) {
if (check_thread(&exec_start_th))
exec_start_th = exec(exec_start, name);
is_start = false;
}
log(id, LL_DEBUG_VERBOSE, "Write frame to %s", name.c_str());
FILE *fh = fopen(name.c_str(), "wb");
if (!fh)
error_exit(true, "Cannot create file %s", name.c_str());
auto img = put_f->get_data_and_len(E_JPEG);
fwrite(std::get<0>(img), std::get<1>(img), 1, fh);
delete put_f;
fclose(fh);
return name;
}
void target_jpeg::operator()()
{
set_thread_name("storej_" + prefix);
uint64_t prev_ts = 0;
std::string name;
const double fps = 1.0 / interval;
f_nr = 0;
is_start = true;
s -> start();
video_frame *prev_frame = nullptr;
for(;!local_stop_flag;) {
pauseCheck();
st->track_fps();
uint64_t before_ts = get_us();
video_frame *pvf = s -> get_frame(handle_failure, prev_ts);
if (pvf) {
prev_ts = pvf->get_ts();
if (!filters || filters -> empty()) {
pre_record.push_back(pvf);
}
else {
source *cur_s = is_view_proxy ? ((view *)s) -> get_current_source() : s;
instance *inst = find_instance_by_interface(cfg, cur_s);
video_frame *temp = pvf->apply_filtering(inst, cur_s, prev_frame, filters, nullptr);
pre_record.push_back(temp);
delete prev_frame;
prev_frame = temp->duplicate({ });
}
video_frame * put_f = pre_record.front();
pre_record.erase(pre_record.begin());
const bool allow_store = sched == nullptr || (sched && sched->is_on());
if (allow_store)
write_frame(put_f);
}
st->track_cpu_usage();
handle_fps(&local_stop_flag, fps, before_ts);
}
join_thread(&exec_start_th, id, "exec-start");
if (!exec_end.empty()) {
if (check_thread(&exec_end_th))
exec_end_th = exec(exec_end, name);
join_thread(&exec_end_th, id, "exec-end");
}
const bool allow_store = sched == nullptr || (sched && sched->is_on());
for(auto f : pre_record) {
if (allow_store)
write_frame(f);
else
delete f;
}
pre_record.clear();
delete prev_frame;
s -> stop();
}
| 24.716418 | 657 | 0.669082 | [
"vector"
] |
f31733485a25f834e017dbc616fa06e10b7e2a2c | 3,955 | cpp | C++ | live/src/v20180801/model/DescribeLiveStreamPushInfoListRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | live/src/v20180801/model/DescribeLiveStreamPushInfoListRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | live/src/v20180801/model/DescribeLiveStreamPushInfoListRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/live/v20180801/model/DescribeLiveStreamPushInfoListRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Live::V20180801::Model;
using namespace std;
DescribeLiveStreamPushInfoListRequest::DescribeLiveStreamPushInfoListRequest() :
m_pushDomainHasBeenSet(false),
m_appNameHasBeenSet(false),
m_pageNumHasBeenSet(false),
m_pageSizeHasBeenSet(false)
{
}
string DescribeLiveStreamPushInfoListRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_pushDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PushDomain";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_pushDomain.c_str(), allocator).Move(), allocator);
}
if (m_appNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AppName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_appName.c_str(), allocator).Move(), allocator);
}
if (m_pageNumHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PageNum";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_pageNum, allocator);
}
if (m_pageSizeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PageSize";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_pageSize, allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DescribeLiveStreamPushInfoListRequest::GetPushDomain() const
{
return m_pushDomain;
}
void DescribeLiveStreamPushInfoListRequest::SetPushDomain(const string& _pushDomain)
{
m_pushDomain = _pushDomain;
m_pushDomainHasBeenSet = true;
}
bool DescribeLiveStreamPushInfoListRequest::PushDomainHasBeenSet() const
{
return m_pushDomainHasBeenSet;
}
string DescribeLiveStreamPushInfoListRequest::GetAppName() const
{
return m_appName;
}
void DescribeLiveStreamPushInfoListRequest::SetAppName(const string& _appName)
{
m_appName = _appName;
m_appNameHasBeenSet = true;
}
bool DescribeLiveStreamPushInfoListRequest::AppNameHasBeenSet() const
{
return m_appNameHasBeenSet;
}
uint64_t DescribeLiveStreamPushInfoListRequest::GetPageNum() const
{
return m_pageNum;
}
void DescribeLiveStreamPushInfoListRequest::SetPageNum(const uint64_t& _pageNum)
{
m_pageNum = _pageNum;
m_pageNumHasBeenSet = true;
}
bool DescribeLiveStreamPushInfoListRequest::PageNumHasBeenSet() const
{
return m_pageNumHasBeenSet;
}
uint64_t DescribeLiveStreamPushInfoListRequest::GetPageSize() const
{
return m_pageSize;
}
void DescribeLiveStreamPushInfoListRequest::SetPageSize(const uint64_t& _pageSize)
{
m_pageSize = _pageSize;
m_pageSizeHasBeenSet = true;
}
bool DescribeLiveStreamPushInfoListRequest::PageSizeHasBeenSet() const
{
return m_pageSizeHasBeenSet;
}
| 27.275862 | 95 | 0.740834 | [
"model"
] |
f3173fb6f8c05b706b9bf7dc9fecd5e584526260 | 3,586 | cc | C++ | smartag/src/model/DescribeQosCarsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | smartag/src/model/DescribeQosCarsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | smartag/src/model/DescribeQosCarsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/smartag/model/DescribeQosCarsRequest.h>
using AlibabaCloud::Smartag::Model::DescribeQosCarsRequest;
DescribeQosCarsRequest::DescribeQosCarsRequest() :
RpcServiceRequest("smartag", "2018-03-13", "DescribeQosCars")
{
setMethod(HttpRequest::Method::Post);
}
DescribeQosCarsRequest::~DescribeQosCarsRequest()
{}
long DescribeQosCarsRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void DescribeQosCarsRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string DescribeQosCarsRequest::getDescription()const
{
return description_;
}
void DescribeQosCarsRequest::setDescription(const std::string& description)
{
description_ = description;
setParameter("Description", description);
}
int DescribeQosCarsRequest::getPageNumber()const
{
return pageNumber_;
}
void DescribeQosCarsRequest::setPageNumber(int pageNumber)
{
pageNumber_ = pageNumber;
setParameter("PageNumber", std::to_string(pageNumber));
}
std::string DescribeQosCarsRequest::getRegionId()const
{
return regionId_;
}
void DescribeQosCarsRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
int DescribeQosCarsRequest::getPageSize()const
{
return pageSize_;
}
void DescribeQosCarsRequest::setPageSize(int pageSize)
{
pageSize_ = pageSize;
setParameter("PageSize", std::to_string(pageSize));
}
std::string DescribeQosCarsRequest::getQosId()const
{
return qosId_;
}
void DescribeQosCarsRequest::setQosId(const std::string& qosId)
{
qosId_ = qosId;
setParameter("QosId", qosId);
}
std::string DescribeQosCarsRequest::getOrder()const
{
return order_;
}
void DescribeQosCarsRequest::setOrder(const std::string& order)
{
order_ = order;
setParameter("Order", order);
}
std::string DescribeQosCarsRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void DescribeQosCarsRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string DescribeQosCarsRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void DescribeQosCarsRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setParameter("OwnerAccount", ownerAccount);
}
long DescribeQosCarsRequest::getOwnerId()const
{
return ownerId_;
}
void DescribeQosCarsRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string DescribeQosCarsRequest::getQosCarId()const
{
return qosCarId_;
}
void DescribeQosCarsRequest::setQosCarId(const std::string& qosCarId)
{
qosCarId_ = qosCarId;
setParameter("QosCarId", qosCarId);
}
| 23.748344 | 94 | 0.755717 | [
"model"
] |
f31a9e6ea6b811d50567061d20981efbb7bc2cdb | 841 | cpp | C++ | Algorithms/0532.K-diff_Pairs_in_an_Array.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0532.K-diff_Pairs_in_an_Array.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0532.K-diff_Pairs_in_an_Array.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
int findPairs(vector<int>& ar, int k) {
int n = ar.size() , ans = 0;
set<int> nums,add;
set<int>::iterator it;
for( int i = 0 ; i < n ; i++ ) {
it = nums.find(ar[i]-k);
if(it != nums.end()) {
it = add.find(ar[i]-k);
if(it == add.end()) {
ans++;
add.insert(ar[i]-k);
}
}
if(k > 0) {
it = nums.find(ar[i]+k);
if(it != nums.end()) {
it = add.find(ar[i]);
if(it == add.end()) {
ans++;
add.insert(ar[i]);
}
}
}
nums.insert(ar[i]);
}
return ans;
}
}; | 28.033333 | 43 | 0.299643 | [
"vector"
] |
f31ad597f65fd32a5b8410315f0c30013a2eacfb | 7,969 | cpp | C++ | Game/dmusic/mixer.cpp | da3m0nsec/OpenGothic | af30c52309cb84ff338d42554610679e0e245f91 | [
"MIT"
] | null | null | null | Game/dmusic/mixer.cpp | da3m0nsec/OpenGothic | af30c52309cb84ff338d42554610679e0e245f91 | [
"MIT"
] | null | null | null | Game/dmusic/mixer.cpp | da3m0nsec/OpenGothic | af30c52309cb84ff338d42554610679e0e245f91 | [
"MIT"
] | null | null | null | #include "mixer.h"
#include <Tempest/Application>
#include <Tempest/SoundEffect>
#include <Tempest/Sound>
#include <Tempest/Log>
#include <cmath>
#include <set>
#include "soundfont.h"
#include "wave.h"
using namespace Dx8;
using namespace Tempest;
static int64_t toSamples(uint64_t time) {
return int64_t(time*SoundFont::SampleRate)/1000;
}
Mixer::Mixer() {
const size_t reserve=2048;
pcm.reserve(reserve*2);
pcmMix.reserve(reserve*2);
vol.reserve(reserve);
uniqInstr.reserve(32);
}
Mixer::~Mixer() {
for(auto& i:active)
SoundFont::noteOff(i.ticket);
}
void Mixer::setMusic(const Music& m) {
current = m.impl;
}
int64_t Mixer::currentPlayTime() const {
return (sampleCursor*1000/SoundFont::SampleRate);
}
int64_t Mixer::nextNoteOn(PatternList::PatternInternal& part,int64_t b,int64_t e) {
int64_t nextDt = std::numeric_limits<int64_t>::max();
int64_t timeTotal = toSamples(part.timeTotal);
bool inv = (e<b);
b-=patStart;
e-=patStart;
for(auto& i:part.waves) {
int64_t at = toSamples(i.at);
if((b<at && at<=e)^inv) {
int64_t t = at-b;
if(inv)
t += timeTotal;
if(t<nextDt && i.duration>0)
nextDt = t;
}
}
return nextDt;
}
int64_t Mixer::nextNoteOff(int64_t b, int64_t /*e*/) {
int64_t actT = std::numeric_limits<int64_t>::max();
for(auto& i:active) {
int64_t at = i.at;
int64_t dt = at>=b ? i.at-b : 0;
if(dt<actT)
actT = dt;
}
return actT;
}
void Mixer::noteOn(std::shared_ptr<PatternInternal>& pattern, PatternList::Note *r) {
Active a;
a.at = sampleCursor + toSamples(r->duration);
//a.ticket = r->inst->font.noteOn(r->note,uint8_t(r->velosity*100.0/pattern->styh.dblTempo));
//a.ticket = r->inst->font.noteOn(r->note,r->velosity*pattern->styh.dblTempo/100.0);
a.ticket = r->inst->font.noteOn(r->note,r->velosity);
if(a.ticket==nullptr)
return;
active.push_back(a);
for(auto& i:uniqInstr)
if(i.ptr==r->inst){
return;
}
Instr u;
u.ptr = r->inst;
u.pattern = pattern;
uniqInstr.push_back(u);
}
void Mixer::noteOn(std::shared_ptr<PatternInternal>& pattern, int64_t time) {
time-=patStart;
size_t n=0;
for(auto& i:pattern->waves) {
int64_t at = toSamples(i.at);
if(at==time) {
noteOn(pattern,&i);
++n;
}
}
if(n==0)
throw std::runtime_error("mixer critical error");
}
void Mixer::noteOff(int64_t time) {
size_t sz=0;
for(size_t i=0;i<active.size();++i){
if(active[i].at>time) {
active[sz]=active[i];
sz++;
} else {
SoundFont::noteOff(active[i].ticket);
}
}
active.resize(sz);
}
void Mixer::nextPattern() {
auto mus = current;
if(mus->pptn.size()==0) {
// no active music
pattern = nullptr;
return;
}
auto prev = pattern;
pattern = std::shared_ptr<PatternInternal>(mus,mus->pptn[0].get());
for(size_t i=0;i<mus->pptn.size();++i){
if(mus->pptn[i].get()==prev.get()) {
size_t next = (i+1)%mus->pptn.size();
pattern = std::shared_ptr<PatternList::PatternInternal>(mus,mus->pptn[next].get());
break;
}
}
patStart = sampleCursor;
patEnd = patStart+toSamples(pattern->timeTotal);
for(auto& i:pattern->waves)
if(i.at==0) {
noteOn(pattern,&i);
}
}
Mixer::Step Mixer::stepInc(PatternInternal& pptn, int64_t b, int64_t e, int64_t samplesRemain) {
int64_t nextT = nextNoteOn (pptn,b,e);
int64_t offT = nextNoteOff(b,e);
int64_t samples = std::min(offT,nextT);
Step s;
if(samples>samplesRemain) {
s.samples=samplesRemain;
return s;
}
s.nextOn = nextNoteOn (pptn,b,e);
s.nextOff = nextNoteOff(b,e);
s.samples = std::min(offT,nextT);
return s;
}
void Mixer::stepApply(std::shared_ptr<PatternInternal> &pptn, const Mixer::Step &s,int64_t b) {
if(s.nextOff<s.nextOn) {
noteOff(s.nextOff+b);
} else
if(s.nextOff>s.nextOn) {
noteOn (pptn,s.nextOn+b);
} else
if(s.nextOff==s.nextOn) {
noteOff(s.nextOff+b);
noteOn (pptn,s.nextOn+b);
}
}
std::shared_ptr<Mixer::PatternInternal> Mixer::checkPattern(std::shared_ptr<PatternInternal> p) {
auto cur = current;
if(cur==nullptr)
return nullptr;
for(auto& i:cur->pptn)
if(i.get()==p.get()) {
return p;
}
// null or foreign
nextPattern();
return pattern;
}
void Mixer::mix(int16_t *out, size_t samples) {
std::memset(out,0,2*samples*sizeof(int16_t));
auto cur = current;
if(cur==nullptr)
return;
auto pat = checkPattern(pattern);
const int64_t samplesTotal = toSamples(cur->timeTotal);
if(samplesTotal==0)
return;
size_t samplesRemain = samples;
while(samplesRemain>0) {
if(pat==nullptr)
return;
const int64_t remain = std::min(patEnd-sampleCursor,int64_t(samplesRemain));
const int64_t b = (sampleCursor );
const int64_t e = (sampleCursor+remain);
auto& pptn = *pat;
const float volume = cur->volume.load()*this->volume.load();
const Step stp = stepInc(pptn,b,e,remain);
implMix(pptn,volume,out,size_t(stp.samples));
if(remain!=stp.samples)
stepApply(pat,stp,sampleCursor);
sampleCursor += stp.samples;
out += stp.samples*2;
samplesRemain-= size_t(stp.samples);
if(sampleCursor==patEnd)
nextPattern();
}
}
void Mixer::setVolume(float v) {
volume.store(v);
}
void Mixer::implMix(PatternInternal &pptn, float volume, int16_t *out, size_t cnt) {
const size_t cnt2=cnt*2;
pcm .resize(cnt2);
pcmMix.resize(cnt2);
vol .resize(cnt);
std::memset(pcmMix.data(),0,cnt2*sizeof(pcmMix[0]));
for(auto& i:uniqInstr) {
auto& ins = *i.ptr;
if(!ins.font.hasNotes())
continue;
volFromCurve(pptn,i,vol);
std::memset(pcm.data(),0,cnt2*sizeof(pcm[0]));
ins.font.mix(pcm.data(),cnt);
float volume = ins.volume;
for(size_t i=0;i<cnt2;++i) {
float v = volume*vol[i/2];
pcmMix[i] += pcm[i]*(v*v);
}
}
for(size_t i=0;i<cnt2;++i) {
float v = pcmMix[i]*volume;
out[i] = (v < -1.00004566f ? int16_t(-32768) : (v > 1.00001514f ? int16_t(32767) : int16_t(v * 32767.5f)));
}
}
void Mixer::volFromCurve(PatternInternal &part,Instr& inst,std::vector<float> &v) {
float& base = inst.volLast;
for(auto& i:v)
i=base;
const int64_t shift = sampleCursor-patStart;
//const int64_t e = s+v.size();
for(auto& i:part.volume) {
if(i.inst!=inst.ptr)
continue;
int64_t s = toSamples(i.at)-shift;
int64_t e = toSamples(i.at+i.duration)-shift;
if((s>=0 && size_t(s)>v.size()) || e<0)
continue;
const size_t begin = size_t(std::max<int64_t>(s,0));
const size_t size = std::min(size_t(e),v.size());
const float range = float(e-s);
const float diffV = i.endV-i.startV;
const float shift = i.startV;
const float endV = i.endV;
switch(i.shape) {
case DMUS_CURVES_LINEAR: {
for(size_t i=begin;i<size;++i) {
float val = float(i-s)/range;
v[i] = val*diffV+shift;
}
break;
}
case DMUS_CURVES_INSTANT: {
for(size_t i=begin;i<size;++i) {
v[i] = endV;
}
break;
}
case DMUS_CURVES_EXP: {
for(size_t i=begin;i<size;++i) {
float val = float(i-s)/range;
v[i] = std::pow(val,2.f)*diffV+shift;
}
break;
}
case DMUS_CURVES_LOG: {
for(size_t i=begin;i<size;++i) {
float val = float(i-s)/range;
v[i] = std::sqrt(val)*diffV+shift;
}
break;
}
case DMUS_CURVES_SINE: {
for(size_t i=begin;i<size;++i) {
float linear = float(i-s)/range;
float val = std::sin(float(M_PI)*linear*0.5f);
v[i] = val*diffV+shift;
}
break;
}
}
if(size>begin)
base = v[size-1];
}
}
| 24.221884 | 111 | 0.596185 | [
"shape",
"vector"
] |
f31c2aa4f45d8c2ce4705631fb3d20d4db10f0c3 | 2,604 | cpp | C++ | openstudiocore/src/model/test/GasEquipment_GTest.cpp | BIMDataHub/OpenStudio-1 | 13ec115b00aa6a2af1426ceb26446f05014c8c8d | [
"blessing"
] | 4 | 2015-05-02T21:04:15.000Z | 2015-10-28T09:47:22.000Z | openstudiocore/src/model/test/GasEquipment_GTest.cpp | BIMDataHub/OpenStudio-1 | 13ec115b00aa6a2af1426ceb26446f05014c8c8d | [
"blessing"
] | null | null | null | openstudiocore/src/model/test/GasEquipment_GTest.cpp | BIMDataHub/OpenStudio-1 | 13ec115b00aa6a2af1426ceb26446f05014c8c8d | [
"blessing"
] | 1 | 2020-11-12T21:52:36.000Z | 2020-11-12T21:52:36.000Z | /**********************************************************************
* Copyright (c) 2008-2015, Alliance for Sustainable Energy.
* All rights reserved.
*
* 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
**********************************************************************/
#include <gtest/gtest.h>
#include "ModelFixture.hpp"
#include "../Model_Impl.hpp"
#include "../Space.hpp"
#include "../SpaceType.hpp"
#include "../ThermalZone.hpp"
#include "../GasEquipment.hpp"
#include "../GasEquipment_Impl.hpp"
#include "../GasEquipmentDefinition.hpp"
#include "../GasEquipmentDefinition_Impl.hpp"
#include "../LifeCycleCost.hpp"
using namespace openstudio;
using namespace openstudio::model;
TEST_F(ModelFixture, GasEquipment)
{
Model model;
GasEquipmentDefinition definition(model);
GasEquipment gasEquipment(definition);
EXPECT_EQ(2u, model.numObjects());
}
TEST_F(ModelFixture, GasEquipment_Cost)
{
Model model;
GasEquipmentDefinition definition(model);
GasEquipment gasEquipment(definition);
EXPECT_EQ(2u, model.numObjects());
boost::optional<LifeCycleCost> cost = LifeCycleCost::createLifeCycleCost("Gas Hookup", definition, 10.0, "CostPerEach", "Construction");
ASSERT_TRUE(cost);
EXPECT_DOUBLE_EQ(0, cost->totalCost());
Space space(model);
gasEquipment.setSpace(space);
EXPECT_DOUBLE_EQ(10.0, cost->totalCost());
ThermalZone thermalZone(model);
space.setThermalZone(thermalZone);
thermalZone.setMultiplier(4);
EXPECT_DOUBLE_EQ(40.0, cost->totalCost());
SpaceType spaceType(model);
gasEquipment.setSpaceType(spaceType);
EXPECT_DOUBLE_EQ(0, cost->totalCost());
space.setSpaceType(spaceType);
EXPECT_DOUBLE_EQ(40.0, cost->totalCost());
GasEquipment gasEquipment2(definition);
gasEquipment2.setSpace(space);
EXPECT_DOUBLE_EQ(80.0, cost->totalCost());
}
| 31 | 139 | 0.686636 | [
"model"
] |
f31e4126c49393525ced1161fbe09f64a1f19ab5 | 7,496 | cpp | C++ | indra/llmath/tests/llbboxlocal_test.cpp | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | 1 | 2022-01-29T07:10:03.000Z | 2022-01-29T07:10:03.000Z | indra/llmath/tests/llbboxlocal_test.cpp | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | null | null | null | indra/llmath/tests/llbboxlocal_test.cpp | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | 1 | 2021-10-01T22:22:27.000Z | 2021-10-01T22:22:27.000Z | /**
* @file llbboxlocal_test.cpp
* @author Martin Reddy
* @date 2009-06-25
* @brief Test for llbboxlocal.cpp.
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "../test/lltut.h"
#include "../llbboxlocal.h"
namespace tut
{
struct LLBBoxLocalData
{
};
typedef test_group<LLBBoxLocalData> factory;
typedef factory::object object;
}
namespace
{
tut::factory llbboxlocal_test_factory("LLBBoxLocal");
}
namespace tut
{
template<> template<>
void object::test<1>()
{
//
// test the default constructor
//
LLBBoxLocal bbox1;
ensure_equals("Default bbox min", bbox1.getMin(), LLVector3(0.0f, 0.0f, 0.0f));
ensure_equals("Default bbox max", bbox1.getMax(), LLVector3(0.0f, 0.0f, 0.0f));
}
template<> template<>
void object::test<2>()
{
//
// test the non-default constructor
//
LLBBoxLocal bbox2(LLVector3(-1.0f, -2.0f, 0.0f), LLVector3(1.0f, 2.0f, 3.0f));
ensure_equals("Custom bbox min", bbox2.getMin(), LLVector3(-1.0f, -2.0f, 0.0f));
ensure_equals("Custom bbox max", bbox2.getMax(), LLVector3(1.0f, 2.0f, 3.0f));
}
template<> template<>
void object::test<3>()
{
//
// test the setMin()
//
// N.B. no validation is currently performed to ensure that the min
// and max vectors are actually the min/max values.
//
LLBBoxLocal bbox2;
bbox2.setMin(LLVector3(1.0f, 2.0f, 3.0f));
ensure_equals("Custom bbox min (2)", bbox2.getMin(), LLVector3(1.0f, 2.0f, 3.0f));
}
template<> template<>
void object::test<4>()
{
//
// test the setMax()
//
// N.B. no validation is currently performed to ensure that the min
// and max vectors are actually the min/max values.
//
LLBBoxLocal bbox2;
bbox2.setMax(LLVector3(10.0f, 20.0f, 30.0f));
ensure_equals("Custom bbox max (2)", bbox2.getMax(), LLVector3(10.0f, 20.0f, 30.0f));
}
template<> template<>
void object::test<5>()
{
//
// test the getCenter() method
//
ensure_equals("Default bbox center", LLBBoxLocal().getCenter(), LLVector3(0.0f, 0.0f, 0.0f));
LLBBoxLocal bbox1(LLVector3(-1.0f, -1.0f, -1.0f), LLVector3(0.0f, 0.0f, 0.0f));
ensure_equals("Custom bbox center", bbox1.getCenter(), LLVector3(-0.5f, -0.5f, -0.5f));
LLBBoxLocal bbox2(LLVector3(0.0f, 0.0f, 0.0f), LLVector3(-1.0f, -1.0f, -1.0f));
ensure_equals("Invalid bbox center", bbox2.getCenter(), LLVector3(-0.5f, -0.5f, -0.5f));
}
template<> template<>
void object::test<6>()
{
//
// test the getExtent() method
//
LLBBoxLocal bbox2(LLVector3(0.0f, 0.0f, 0.0f), LLVector3(-1.0f, -1.0f, -1.0f));
ensure_equals("Default bbox extent", LLBBoxLocal().getExtent(), LLVector3(0.0f, 0.0f, 0.0f));
LLBBoxLocal bbox3(LLVector3(-1.0f, -1.0f, -1.0f), LLVector3(1.0f, 2.0f, 0.0f));
ensure_equals("Custom bbox extent", bbox3.getExtent(), LLVector3(2.0f, 3.0f, 1.0f));
}
template<> template<>
void object::test<7>()
{
//
// test the addPoint() method
//
// N.B. if you create an empty bbox and then add points,
// the vector (0, 0, 0) will always be part of the bbox.
// (Fixing this would require adding a bool to the class size).
//
LLBBoxLocal bbox1;
bbox1.addPoint(LLVector3(-1.0f, -2.0f, -3.0f));
bbox1.addPoint(LLVector3(3.0f, 4.0f, 5.0f));
ensure_equals("Custom BBox center (1)", bbox1.getCenter(), LLVector3(1.0f, 1.0f, 1.0f));
ensure_equals("Custom BBox min (1)", bbox1.getMin(), LLVector3(-1.0f, -2.0f, -3.0f));
ensure_equals("Custom BBox max (1)", bbox1.getMax(), LLVector3(3.0f, 4.0f, 5.0f));
bbox1.addPoint(LLVector3(0.0f, 0.0f, 0.0f));
bbox1.addPoint(LLVector3(1.0f, 2.0f, 3.0f));
bbox1.addPoint(LLVector3(2.0f, 2.0f, 2.0f));
ensure_equals("Custom BBox center (2)", bbox1.getCenter(), LLVector3(1.0f, 1.0f, 1.0f));
ensure_equals("Custom BBox min (2)", bbox1.getMin(), LLVector3(-1.0f, -2.0f, -3.0f));
ensure_equals("Custom BBox max (2)", bbox1.getMax(), LLVector3(3.0f, 4.0f, 5.0f));
bbox1.addPoint(LLVector3(5.0f, 5.0f, 5.0f));
ensure_equals("Custom BBox center (3)", bbox1.getCenter(), LLVector3(2.0f, 1.5f, 1.0f));
ensure_equals("Custom BBox min (3)", bbox1.getMin(), LLVector3(-1.0f, -2.0f, -3.0f));
ensure_equals("Custom BBox max (3)", bbox1.getMax(), LLVector3(5.0f, 5.0f, 5.0f));
}
template<> template<>
void object::test<8>()
{
//
// test the addBBox() methods
//
// N.B. if you create an empty bbox and then add points,
// the vector (0, 0, 0) will always be part of the bbox.
// (Fixing this would require adding a bool to the class size).
//
LLBBoxLocal bbox2(LLVector3(1.0f, 1.0f, 1.0f), LLVector3(2.0f, 2.0f, 2.0f));
bbox2.addBBox(LLBBoxLocal(LLVector3(1.5f, 1.5f, 1.5f), LLVector3(3.0f, 3.0f, 3.0f)));
ensure_equals("Custom BBox center (4)", bbox2.getCenter(), LLVector3(2.0f, 2.0f, 2.0f));
ensure_equals("Custom BBox min (4)", bbox2.getMin(), LLVector3(1.0f, 1.0f, 1.0f));
ensure_equals("Custom BBox max (4)", bbox2.getMax(), LLVector3(3.0f, 3.0f, 3.0f));
bbox2.addBBox(LLBBoxLocal(LLVector3(-1.0f, -1.0f, -1.0f), LLVector3(0.0f, 0.0f, 0.0f)));
ensure_equals("Custom BBox center (5)", bbox2.getCenter(), LLVector3(1.0f, 1.0f, 1.0f));
ensure_equals("Custom BBox min (5)", bbox2.getMin(), LLVector3(-1.0f, -1.0f, -1.0f));
ensure_equals("Custom BBox max (5)", bbox2.getMax(), LLVector3(3.0f, 3.0f, 3.0f));
}
template<> template<>
void object::test<9>()
{
//
// test the expand() method
//
LLBBoxLocal bbox1;
bbox1.expand(0.0f);
ensure_equals("Zero-expanded Default BBox center", bbox1.getCenter(), LLVector3(0.0f, 0.0f, 0.0f));
LLBBoxLocal bbox2(LLVector3(1.0f, 2.0f, 3.0f), LLVector3(3.0f, 4.0f, 5.0f));
bbox2.expand(0.0f);
ensure_equals("Zero-expanded BBox center", bbox2.getCenter(), LLVector3(2.0f, 3.0f, 4.0f));
ensure_equals("Zero-expanded BBox min", bbox2.getMin(), LLVector3(1.0f, 2.0f, 3.0f));
ensure_equals("Zero-expanded BBox max", bbox2.getMax(), LLVector3(3.0f, 4.0f, 5.0f));
bbox2.expand(0.5f);
ensure_equals("Positive-expanded BBox center", bbox2.getCenter(), LLVector3(2.0f, 3.0f, 4.0f));
ensure_equals("Positive-expanded BBox min", bbox2.getMin(), LLVector3(0.5f, 1.5f, 2.5f));
ensure_equals("Positive-expanded BBox max", bbox2.getMax(), LLVector3(3.5f, 4.5f, 5.5f));
bbox2.expand(-1.0f);
ensure_equals("Negative-expanded BBox center", bbox2.getCenter(), LLVector3(2.0f, 3.0f, 4.0f));
ensure_equals("Negative-expanded BBox min", bbox2.getMin(), LLVector3(1.5f, 2.5f, 3.5f));
ensure_equals("Negative-expanded BBox max", bbox2.getMax(), LLVector3(2.5f, 3.5f, 4.5f));
}
}
| 32.171674 | 101 | 0.659552 | [
"object",
"vector"
] |
f32bdc7b863a17c86b46e5dd739210c0dd39be17 | 6,478 | cc | C++ | core/src/main/cpp/webrtc/modules/rtp_rtcp/source/rtcp_packet/nack_unittest.cc | sclwork/core | 65904846fcaa86dd67937a263dc6ae5882dd1f30 | [
"Apache-2.0"
] | 78 | 2016-06-23T03:01:49.000Z | 2022-03-03T03:15:49.000Z | core/src/main/cpp/webrtc/modules/rtp_rtcp/source/rtcp_packet/nack_unittest.cc | sclwork/core | 65904846fcaa86dd67937a263dc6ae5882dd1f30 | [
"Apache-2.0"
] | 8 | 2016-12-17T03:16:01.000Z | 2020-05-21T09:55:58.000Z | core/src/main/cpp/webrtc/modules/rtp_rtcp/source/rtcp_packet/nack_unittest.cc | sclwork/core | 65904846fcaa86dd67937a263dc6ae5882dd1f30 | [
"Apache-2.0"
] | 53 | 2016-06-05T13:34:42.000Z | 2021-12-22T10:44:03.000Z | /*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/rtp_rtcp/source/rtcp_packet/nack.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::ElementsAreArray;
using ::testing::Invoke;
using ::testing::UnorderedElementsAreArray;
using webrtc::rtcp::Nack;
using webrtc::RTCPUtility::RtcpCommonHeader;
using webrtc::RTCPUtility::RtcpParseCommonHeader;
namespace webrtc {
namespace {
const uint32_t kSenderSsrc = 0x12345678;
const uint32_t kRemoteSsrc = 0x23456789;
const uint16_t kList[] = {0, 1, 3, 8, 16};
const size_t kListLength = sizeof(kList) / sizeof(kList[0]);
const uint8_t kPacket[] = {0x81, 205, 0x00, 0x03, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0x00, 0x00, 0x80, 0x85};
const size_t kPacketLength = sizeof(kPacket);
const uint16_t kWrapList[] = {0xffdc, 0xffec, 0xfffe, 0xffff, 0x0000,
0x0001, 0x0003, 0x0014, 0x0064};
const size_t kWrapListLength = sizeof(kWrapList) / sizeof(kWrapList[0]);
const uint8_t kWrapPacket[] = {0x81, 205, 0x00, 0x06, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0xff, 0xdc, 0x80, 0x00,
0xff, 0xfe, 0x00, 0x17, 0x00, 0x14, 0x00, 0x00,
0x00, 0x64, 0x00, 0x00};
const size_t kWrapPacketLength = sizeof(kWrapPacket);
TEST(RtcpPacketNackTest, Create) {
Nack nack;
nack.From(kSenderSsrc);
nack.To(kRemoteSsrc);
nack.WithList(kList, kListLength);
rtc::Buffer packet = nack.Build();
EXPECT_EQ(kPacketLength, packet.size());
EXPECT_EQ(0, memcmp(kPacket, packet.data(), kPacketLength));
}
TEST(RtcpPacketNackTest, Parse) {
RtcpCommonHeader header;
EXPECT_TRUE(RtcpParseCommonHeader(kPacket, kPacketLength, &header));
EXPECT_EQ(kPacketLength, header.BlockSize());
Nack parsed;
EXPECT_TRUE(
parsed.Parse(header, kPacket + RtcpCommonHeader::kHeaderSizeBytes));
const Nack& const_parsed = parsed;
EXPECT_EQ(kSenderSsrc, const_parsed.sender_ssrc());
EXPECT_EQ(kRemoteSsrc, const_parsed.media_ssrc());
EXPECT_THAT(const_parsed.packet_ids(), ElementsAreArray(kList));
}
TEST(RtcpPacketNackTest, CreateWrap) {
Nack nack;
nack.From(kSenderSsrc);
nack.To(kRemoteSsrc);
nack.WithList(kWrapList, kWrapListLength);
rtc::Buffer packet = nack.Build();
EXPECT_EQ(kWrapPacketLength, packet.size());
EXPECT_EQ(0, memcmp(kWrapPacket, packet.data(), kWrapPacketLength));
}
TEST(RtcpPacketNackTest, ParseWrap) {
RtcpCommonHeader header;
EXPECT_TRUE(RtcpParseCommonHeader(kWrapPacket, kWrapPacketLength, &header));
EXPECT_EQ(kWrapPacketLength, header.BlockSize());
Nack parsed;
EXPECT_TRUE(
parsed.Parse(header, kWrapPacket + RtcpCommonHeader::kHeaderSizeBytes));
EXPECT_EQ(kSenderSsrc, parsed.sender_ssrc());
EXPECT_EQ(kRemoteSsrc, parsed.media_ssrc());
EXPECT_THAT(parsed.packet_ids(), ElementsAreArray(kWrapList));
}
TEST(RtcpPacketNackTest, BadOrder) {
// Does not guarantee optimal packing, but should guarantee correctness.
const uint16_t kUnorderedList[] = {1, 25, 13, 12, 9, 27, 29};
const size_t kUnorderedListLength =
sizeof(kUnorderedList) / sizeof(kUnorderedList[0]);
Nack nack;
nack.From(kSenderSsrc);
nack.To(kRemoteSsrc);
nack.WithList(kUnorderedList, kUnorderedListLength);
rtc::Buffer packet = nack.Build();
Nack parsed;
RtcpCommonHeader header;
EXPECT_TRUE(RtcpParseCommonHeader(packet.data(), packet.size(), &header));
EXPECT_TRUE(parsed.Parse(
header, packet.data() + RtcpCommonHeader::kHeaderSizeBytes));
EXPECT_EQ(kSenderSsrc, parsed.sender_ssrc());
EXPECT_EQ(kRemoteSsrc, parsed.media_ssrc());
EXPECT_THAT(parsed.packet_ids(), UnorderedElementsAreArray(kUnorderedList));
}
TEST(RtcpPacketNackTest, CreateFragmented) {
Nack nack;
const uint16_t kList[] = {1, 100, 200, 300, 400};
const uint16_t kListLength = sizeof(kList) / sizeof(kList[0]);
nack.From(kSenderSsrc);
nack.To(kRemoteSsrc);
nack.WithList(kList, kListLength);
class MockPacketReadyCallback : public rtcp::RtcpPacket::PacketReadyCallback {
public:
MOCK_METHOD2(OnPacketReady, void(uint8_t*, size_t));
} verifier;
class NackVerifier {
public:
explicit NackVerifier(std::vector<uint16_t> ids) : ids_(ids) {}
void operator()(uint8_t* data, size_t length) {
RtcpCommonHeader header;
EXPECT_TRUE(RtcpParseCommonHeader(data, length, &header));
EXPECT_EQ(length, header.BlockSize());
Nack nack;
EXPECT_TRUE(
nack.Parse(header, data + RtcpCommonHeader::kHeaderSizeBytes));
EXPECT_EQ(kSenderSsrc, nack.sender_ssrc());
EXPECT_EQ(kRemoteSsrc, nack.media_ssrc());
EXPECT_THAT(nack.packet_ids(), ElementsAreArray(ids_));
}
std::vector<uint16_t> ids_;
} packet1({1, 100, 200}), packet2({300, 400});
EXPECT_CALL(verifier, OnPacketReady(_, _))
.WillOnce(Invoke(packet1))
.WillOnce(Invoke(packet2));
const size_t kBufferSize = 12 + (3 * 4); // Fits common header + 3 nack items
uint8_t buffer[kBufferSize];
EXPECT_TRUE(nack.BuildExternalBuffer(buffer, kBufferSize, &verifier));
}
TEST(RtcpPacketNackTest, CreateFailsWithTooSmallBuffer) {
const uint16_t kList[] = {1};
const size_t kMinNackBlockSize = 16;
Nack nack;
nack.From(kSenderSsrc);
nack.To(kRemoteSsrc);
nack.WithList(kList, 1);
class Verifier : public rtcp::RtcpPacket::PacketReadyCallback {
public:
void OnPacketReady(uint8_t* data, size_t length) override {
ADD_FAILURE() << "Buffer should be too small.";
}
} verifier;
uint8_t buffer[kMinNackBlockSize - 1];
EXPECT_FALSE(
nack.BuildExternalBuffer(buffer, kMinNackBlockSize - 1, &verifier));
}
TEST(RtcpPacketNackTest, ParseFailsWithTooSmallBuffer) {
RtcpCommonHeader header;
EXPECT_TRUE(RtcpParseCommonHeader(kPacket, kPacketLength, &header));
header.payload_size_bytes--; // Damage the packet
Nack parsed;
EXPECT_FALSE(
parsed.Parse(header, kPacket + RtcpCommonHeader::kHeaderSizeBytes));
}
} // namespace
} // namespace webrtc
| 34.275132 | 80 | 0.717197 | [
"vector"
] |
f330d3301f03de05705d0607abb4db1c38af4f64 | 666 | hpp | C++ | plugins/common/wayfire/plugins/common/simple-texture.hpp | DurandA/wayfire | f7d3c51552684ac7527d58210d8ebdff2a4bbca1 | [
"MIT"
] | 1 | 2021-05-04T18:28:20.000Z | 2021-05-04T18:28:20.000Z | plugins/common/wayfire/plugins/common/simple-texture.hpp | paullinuxthemer/wayfire | b2e244949783e92e97f5197b0e29ae2ca2868b29 | [
"MIT"
] | null | null | null | plugins/common/wayfire/plugins/common/simple-texture.hpp | paullinuxthemer/wayfire | b2e244949783e92e97f5197b0e29ae2ca2868b29 | [
"MIT"
] | null | null | null | #pragma once
#include <wayfire/opengl.hpp>
#include <wayfire/nonstd/noncopyable.hpp>
namespace wf
{
struct simple_texture_t : public noncopyable_t
{
GLuint tex = -1;
int width = 0;
int height = 0;
/**
* Destroy the GL texture.
* This will call OpenGL::render_begin()/end() internally.
*/
void release()
{
if (this->tex == (GLuint)-1)
return;
OpenGL::render_begin();
GL_CALL(glDeleteTextures(1, &tex));
OpenGL::render_end();
this->tex = -1;
}
/** Auto-release the texture when the object is destroyed */
~simple_texture_t()
{
release();
}
};
}
| 19.028571 | 64 | 0.570571 | [
"object"
] |
f330f263b7afa8497aaecfdde447ab0c5aebc603 | 1,233 | cpp | C++ | main.cpp | mzient/serializer | d183294af043f5d9e09b4162c5d4f8d0ae3724d5 | [
"MIT"
] | null | null | null | main.cpp | mzient/serializer | d183294af043f5d9e09b4162c5d4f8d0ae3724d5 | [
"MIT"
] | null | null | null | main.cpp | mzient/serializer | d183294af043f5d9e09b4162c5d4f8d0ae3724d5 | [
"MIT"
] | null | null | null | /*
* File: main.cpp
* Author: michal
*
* Created on February 20, 2016, 10:47 PM
*/
#include <iostream>
#include <cstdint>
#include <stdio.h>
#include <tuple>
#include "Serialize.h"
#include "BinarySerializer.h"
using namespace std;
struct HexStream : Serialize::IOutputStream
{
void write(const void *data, size_t len) override
{
for (size_t i = 0; i < len; i++)
{
printf("%02x", ((uint8_t*)data)[i]);
}
printf(" ");
}
};
struct A : Serialize::IBinarySerializable
{
A(int x) : x(x) {}
virtual void serialize(Serialize::IOutputStream &out) const
{
binary(out) << x;
}
int x;
};
struct X : Serialize::IBinarySerializable
{
virtual void serialize(Serialize::IOutputStream &out) const
{
std::vector<int> x = { 1, 2, 3 };
binary(out) << x;
}
};
struct S
{
int x, y, z;
string s;
};
SERIALIZE_MEMBERS(Serialize::BinaryFormat, S, x, y, z, s);
struct SS
{
int a, b, c;
S s;
};
SERIALIZE_MEMBERS(Serialize::BinaryFormat, SS, a, b, c, s);
/*
*
*/
int main(int argc, char** argv)
{
HexStream hs;
SS s = { 101, 102, 103, { 1, 2, 3, "ala ma kota" } };
binary(hs) << s;
return 0;
}
| 16.223684 | 63 | 0.564477 | [
"vector"
] |
f335371750d43bf132097819bb3483e5fdd7b394 | 156,688 | cpp | C++ | runtime/test/generated/spec_V1_2/sub_v1_2.example.cpp | riscv-android-src/platform-packages-modules-NeuralNetworks | 32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5 | [
"Apache-2.0"
] | null | null | null | runtime/test/generated/spec_V1_2/sub_v1_2.example.cpp | riscv-android-src/platform-packages-modules-NeuralNetworks | 32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5 | [
"Apache-2.0"
] | null | null | null | runtime/test/generated/spec_V1_2/sub_v1_2.example.cpp | riscv-android-src/platform-packages-modules-NeuralNetworks | 32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5 | [
"Apache-2.0"
] | null | null | null | // Generated from sub_v1_2.mod.py
// DO NOT EDIT
// clang-format off
#include "TestHarness.h"
using namespace test_helper; // NOLINT(google-build-using-namespace)
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_none() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, -2.0f, 12.0f, -20.0f})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_1
};
return model;
}
const auto dummy_test_model_none = TestModelManager::get().add("sub_v1_2_none", get_test_model_none());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_none_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, -2.0f, 12.0f, -20.0f})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // placeholder
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param15
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // placeholder1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param16
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_1
};
return model;
}
const auto dummy_test_model_none_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_none_all_inputs_as_internal", get_test_model_none_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_relu() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({1})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 12.0f, 0.0f})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_1
};
return model;
}
const auto dummy_test_model_relu = TestModelManager::get().add("sub_v1_2_relu", get_test_model_relu());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_relu_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({1})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 12.0f, 0.0f})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // placeholder2
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param17
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // placeholder3
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param18
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_1
};
return model;
}
const auto dummy_test_model_relu_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_relu_all_inputs_as_internal", get_test_model_relu_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_relu1() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, -1.0f, 1.0f, -1.0f})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_1
};
return model;
}
const auto dummy_test_model_relu1 = TestModelManager::get().add("sub_v1_2_relu1", get_test_model_relu1());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_relu1_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, -1.0f, 1.0f, -1.0f})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // placeholder4
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param19
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // placeholder5
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param20
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_1
};
return model;
}
const auto dummy_test_model_relu1_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_relu1_all_inputs_as_internal", get_test_model_relu1_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_relu6() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({3})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 6.0f, 0.0f})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_1
};
return model;
}
const auto dummy_test_model_relu6 = TestModelManager::get().add("sub_v1_2_relu6", get_test_model_relu6());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_relu6_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({3})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 6.0f, 0.0f})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // placeholder6
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param21
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // placeholder7
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param22
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_1
};
return model;
}
const auto dummy_test_model_relu6_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_relu6_all_inputs_as_internal", get_test_model_relu6_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_float16_none() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f, -2.0f, 12.0f, -20.0f})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_none = TestModelManager::get().add("sub_v1_2_float16_none", get_test_model_float16_none());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_float16_none_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f, -2.0f, 12.0f, -20.0f})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // placeholder8
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param23
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // placeholder9
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param24
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_none_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_float16_none_all_inputs_as_internal", get_test_model_float16_none_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_float16_relu() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({1})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f, 0.0f, 12.0f, 0.0f})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_relu = TestModelManager::get().add("sub_v1_2_float16_relu", get_test_model_float16_relu());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_float16_relu_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({1})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f, 0.0f, 12.0f, 0.0f})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // placeholder10
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param25
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // placeholder11
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param26
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_relu_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_float16_relu_all_inputs_as_internal", get_test_model_float16_relu_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_float16_relu1() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f, -1.0f, 1.0f, -1.0f})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_relu1 = TestModelManager::get().add("sub_v1_2_float16_relu1", get_test_model_float16_relu1());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_float16_relu1_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f, -1.0f, 1.0f, -1.0f})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // placeholder12
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param27
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // placeholder13
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param28
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_relu1_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_float16_relu1_all_inputs_as_internal", get_test_model_float16_relu1_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_float16_relu6() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({3})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f, 0.0f, 6.0f, 0.0f})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_relu6 = TestModelManager::get().add("sub_v1_2_float16_relu6", get_test_model_float16_relu6());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_float16_relu6_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // input1
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // act
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({3})
}, { // output0
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f, 0.0f, 6.0f, 0.0f})
}, { // input0_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -4.0f, 8.0f, -16.0f})
}, { // placeholder14
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param29
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f, -2.0f, -4.0f, 4.0f})
}, { // placeholder15
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.0f})
}, { // param30
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_float16_relu6_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_float16_relu6_all_inputs_as_internal", get_test_model_float16_relu6_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_quant8() {
static TestModel model = {
.main = { // quant8
.operands = {{ // input01
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 4, 16, 2},
.numberOfConsumers = 1,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255})
}, { // input11
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 4, 16, 2},
.numberOfConsumers = 1,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({1, 88, 132, 233, 162, 39, 185, 237, 238, 159, 164, 76, 59, 144, 97, 94, 214, 196, 213, 221, 65, 116, 49, 222, 224, 63, 51, 118, 157, 106, 53, 45, 191, 58, 253, 71, 148, 254, 131, 40, 43, 57, 13, 128, 178, 30, 46, 226, 183, 67, 243, 44, 6, 192, 172, 29, 32, 210, 82, 170, 142, 19, 231, 127, 161, 146, 168, 195, 105, 69, 249, 246, 26, 151, 215, 190, 92, 245, 86, 4, 112, 109, 11, 50, 99, 96, 176, 117, 95, 244, 198, 177, 87, 169, 68, 153, 229, 5, 110, 89, 218, 137, 12, 7, 104, 54, 119, 21, 101, 155, 28, 211, 123, 34, 93, 2, 166, 230, 108, 42, 209, 75, 187, 14, 78, 41, 251, 240, 189, 115, 135, 252, 236, 60, 202, 70, 134, 100, 174, 9, 38, 33, 22, 17, 121, 201, 8, 239, 182, 47, 167, 179, 147, 173, 98, 152, 216, 203, 73, 150, 165, 223, 206, 138, 188, 199, 31, 74, 205, 242, 27, 125, 248, 81, 20, 255, 114, 139, 36, 61, 56, 145, 48, 16, 225, 83, 219, 62, 85, 126, 208, 0, 160, 171, 181, 102, 184, 23, 3, 140, 15, 250, 133, 113, 241, 141, 52, 163, 156, 80, 111, 90, 220, 143, 120, 84, 175, 217, 18, 186, 25, 79, 37, 154, 207, 180, 136, 64, 204, 158, 24, 193, 234, 72, 35, 129, 55, 232, 228, 149, 91, 122, 77, 212, 200, 235, 103, 124, 130, 247, 66, 10, 107, 227, 194, 197})
}, { // param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output01
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 4, 16, 2},
.numberOfConsumers = 0,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 15, 0, 0, 0, 0, 0, 7, 46, 0, 0, 26, 24, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 75, 0, 0, 71, 33, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 26, 0, 0, 92, 0, 10, 0, 0, 90, 96, 0, 51, 0, 86, 7, 0, 82, 0, 0, 79, 21, 113, 0, 0, 10, 77, 0, 46, 0, 109, 46, 84, 0, 0, 0, 14, 0, 0, 0, 73, 0, 65, 2, 37, 0, 130, 102, 108, 120, 126, 23, 0, 138, 0, 0, 102, 0, 0, 5, 0, 56, 3, 0, 0, 85, 9, 0, 0, 0, 25, 0, 0, 135, 93, 0, 0, 143, 46, 0, 92, 154, 0, 62, 38, 142, 118, 124, 36, 134, 167, 0, 102, 0, 125, 103, 63, 0, 191, 32, 22, 13, 93, 12, 174, 195, 59, 185, 0, 69, 90, 0, 64, 154, 44, 52, 129, 99, 121, 0, 70, 94, 131, 41, 0, 200, 33, 195, 142, 185, 69, 17, 45, 90, 163, 24, 71, 206, 38, 0, 161, 199, 106, 181, 5, 10, 90, 149, 119, 165, 31, 44, 10, 143, 123, 118, 2, 184, 241, 145, 26, 60, 58})
}},
.operations = {{
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {0, 1},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_quant8 = TestModelManager::get().add("sub_v1_2_quant8", get_test_model_quant8());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_quant8_all_inputs_as_internal() {
static TestModel model = {
.main = { // quant8
.operands = {{ // input01
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 4, 16, 2},
.numberOfConsumers = 1,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({})
}, { // input11
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 4, 16, 2},
.numberOfConsumers = 1,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({})
}, { // param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output01
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 4, 16, 2},
.numberOfConsumers = 0,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 15, 0, 0, 0, 0, 0, 7, 46, 0, 0, 26, 24, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 75, 0, 0, 71, 33, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 26, 0, 0, 92, 0, 10, 0, 0, 90, 96, 0, 51, 0, 86, 7, 0, 82, 0, 0, 79, 21, 113, 0, 0, 10, 77, 0, 46, 0, 109, 46, 84, 0, 0, 0, 14, 0, 0, 0, 73, 0, 65, 2, 37, 0, 130, 102, 108, 120, 126, 23, 0, 138, 0, 0, 102, 0, 0, 5, 0, 56, 3, 0, 0, 85, 9, 0, 0, 0, 25, 0, 0, 135, 93, 0, 0, 143, 46, 0, 92, 154, 0, 62, 38, 142, 118, 124, 36, 134, 167, 0, 102, 0, 125, 103, 63, 0, 191, 32, 22, 13, 93, 12, 174, 195, 59, 185, 0, 69, 90, 0, 64, 154, 44, 52, 129, 99, 121, 0, 70, 94, 131, 41, 0, 200, 33, 195, 142, 185, 69, 17, 45, 90, 163, 24, 71, 206, 38, 0, 161, 199, 106, 181, 5, 10, 90, 149, 119, 165, 31, 44, 10, 143, 123, 118, 2, 184, 241, 145, 26, 60, 58})
}, { // input01_new
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 4, 16, 2},
.numberOfConsumers = 1,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255})
}, { // placeholder16
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({0})
}, { // param31
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input11_new
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {2, 4, 16, 2},
.numberOfConsumers = 1,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({1, 88, 132, 233, 162, 39, 185, 237, 238, 159, 164, 76, 59, 144, 97, 94, 214, 196, 213, 221, 65, 116, 49, 222, 224, 63, 51, 118, 157, 106, 53, 45, 191, 58, 253, 71, 148, 254, 131, 40, 43, 57, 13, 128, 178, 30, 46, 226, 183, 67, 243, 44, 6, 192, 172, 29, 32, 210, 82, 170, 142, 19, 231, 127, 161, 146, 168, 195, 105, 69, 249, 246, 26, 151, 215, 190, 92, 245, 86, 4, 112, 109, 11, 50, 99, 96, 176, 117, 95, 244, 198, 177, 87, 169, 68, 153, 229, 5, 110, 89, 218, 137, 12, 7, 104, 54, 119, 21, 101, 155, 28, 211, 123, 34, 93, 2, 166, 230, 108, 42, 209, 75, 187, 14, 78, 41, 251, 240, 189, 115, 135, 252, 236, 60, 202, 70, 134, 100, 174, 9, 38, 33, 22, 17, 121, 201, 8, 239, 182, 47, 167, 179, 147, 173, 98, 152, 216, 203, 73, 150, 165, 223, 206, 138, 188, 199, 31, 74, 205, 242, 27, 125, 248, 81, 20, 255, 114, 139, 36, 61, 56, 145, 48, 16, 225, 83, 219, 62, 85, 126, 208, 0, 160, 171, 181, 102, 184, 23, 3, 140, 15, 250, 133, 113, 241, 141, 52, 163, 156, 80, 111, 90, 220, 143, 120, 84, 175, 217, 18, 186, 25, 79, 37, 154, 207, 180, 136, 64, 204, 158, 24, 193, 234, 72, 35, 129, 55, 232, 228, 149, 91, 122, 77, 212, 200, 235, 103, 124, 130, 247, 66, 10, 107, 227, 194, 197})
}, { // placeholder17
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.5f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({0})
}, { // param32
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {4, 5, 6},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {7, 8, 9},
.outputs = {1}
}, {
.type = TestOperationType::SUB,
.inputs = {0, 1, 2},
.outputs = {3}
}},
.inputIndexes = {4, 7},
.outputIndexes = {3}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_quant8_all_inputs_as_internal = TestModelManager::get().add("sub_v1_2_quant8_all_inputs_as_internal", get_test_model_quant8_all_inputs_as_internal());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_zero_sized() {
static TestModel model = {
.main = { // zero_sized
.operands = {{ // scores
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.9f, 0.1f})
}, { // roi
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 8},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 1.0f, 10.0f, 10.0f, 0.0f, 0.0f, 10.0f, 10.0f})
}, { // param1
.type = TestOperandType::TENSOR_INT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // param2
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f})
}, { // param3
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({-1})
}, { // param4
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // param5
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.4f})
}, { // param6
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f})
}, { // param7
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f})
}, { // scoresOut
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // roiOut
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // classesOut
.type = TestOperandType::TENSOR_INT32,
.dimensions = {0},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({})
}, { // batchSplitOut
.type = TestOperandType::TENSOR_INT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({})
}, { // in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 1, 1, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 2.0f})
}, { // param8
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // param9
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // param10
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f})
}, { // param11
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f})
}, { // param12
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // param13
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // layout
.type = TestOperandType::BOOL,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<bool8>({false})
}, { // featureMap
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 2, 2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // op
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 2.0f, 3.0f, 4.0f})
}, { // param14
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 2, 2, 2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}},
.operations = {{
.type = TestOperationType::BOX_WITH_NMS_LIMIT,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8},
.outputs = {9, 10, 11, 12}
}, {
.type = TestOperationType::ROI_ALIGN,
.inputs = {13, 10, 12, 14, 15, 16, 17, 18, 19, 20},
.outputs = {21}
}, {
.type = TestOperationType::SUB,
.inputs = {21, 22, 23},
.outputs = {24}
}},
.inputIndexes = {13},
.outputIndexes = {9, 11, 24}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_zero_sized = TestModelManager::get().add("sub_v1_2_zero_sized", get_test_model_zero_sized());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_zero_sized_relaxed() {
static TestModel model = {
.main = { // zero_sized
.operands = {{ // scores
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.9f, 0.1f})
}, { // roi
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 8},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 1.0f, 10.0f, 10.0f, 0.0f, 0.0f, 10.0f, 10.0f})
}, { // param1
.type = TestOperandType::TENSOR_INT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // param2
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f})
}, { // param3
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({-1})
}, { // param4
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // param5
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.4f})
}, { // param6
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f})
}, { // param7
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f})
}, { // scoresOut
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // roiOut
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // classesOut
.type = TestOperandType::TENSOR_INT32,
.dimensions = {0},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({})
}, { // batchSplitOut
.type = TestOperandType::TENSOR_INT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({})
}, { // in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 1, 1, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 2.0f})
}, { // param8
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // param9
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // param10
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f})
}, { // param11
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f})
}, { // param12
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // param13
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // layout
.type = TestOperandType::BOOL,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<bool8>({false})
}, { // featureMap
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 2, 2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // op
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f, 2.0f, 3.0f, 4.0f})
}, { // param14
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 2, 2, 2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}},
.operations = {{
.type = TestOperationType::BOX_WITH_NMS_LIMIT,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8},
.outputs = {9, 10, 11, 12}
}, {
.type = TestOperationType::ROI_ALIGN,
.inputs = {13, 10, 12, 14, 15, 16, 17, 18, 19, 20},
.outputs = {21}
}, {
.type = TestOperationType::SUB,
.inputs = {21, 22, 23},
.outputs = {24}
}},
.inputIndexes = {13},
.outputIndexes = {9, 11, 24}
},
.referenced = {},
.isRelaxed = true,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::UNKNOWN
};
return model;
}
const auto dummy_test_model_zero_sized_relaxed = TestModelManager::get().add("sub_v1_2_zero_sized_relaxed", get_test_model_zero_sized_relaxed());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_zero_sized_quant8() {
static TestModel model = {
.main = { // zero_sized
.operands = {{ // scores
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {1, 2},
.numberOfConsumers = 1,
.scale = 0.1f,
.zeroPoint = 128,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({137, 129})
}, { // roi
.type = TestOperandType::TENSOR_QUANT16_ASYMM,
.dimensions = {1, 8},
.numberOfConsumers = 1,
.scale = 0.125f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint16_t>({8, 8, 80, 80, 0, 0, 80, 80})
}, { // param1
.type = TestOperandType::TENSOR_INT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // param2
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f})
}, { // param3
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({-1})
}, { // param4
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // param5
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.4f})
}, { // param6
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({1.0f})
}, { // param7
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f})
}, { // scoresOut
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {0},
.numberOfConsumers = 0,
.scale = 0.1f,
.zeroPoint = 128,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({})
}, { // roiOut
.type = TestOperandType::TENSOR_QUANT16_ASYMM,
.dimensions = {0, 4},
.numberOfConsumers = 1,
.scale = 0.125f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint16_t>({})
}, { // classesOut
.type = TestOperandType::TENSOR_INT32,
.dimensions = {0},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({})
}, { // batchSplitOut
.type = TestOperandType::TENSOR_INT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({})
}, { // in
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {1, 1, 1, 2},
.numberOfConsumers = 1,
.scale = 0.1f,
.zeroPoint = 128,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({138, 148})
}, { // param8
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // param9
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // param10
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f})
}, { // param11
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({2.0f})
}, { // param12
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // param13
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // layout
.type = TestOperandType::BOOL,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<bool8>({false})
}, { // featureMap
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {0, 2, 2, 2},
.numberOfConsumers = 1,
.scale = 0.1f,
.zeroPoint = 128,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({})
}, { // op
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.1f,
.zeroPoint = 128,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({138, 148, 158, 168})
}, { // param14
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // out
.type = TestOperandType::TENSOR_QUANT8_ASYMM,
.dimensions = {0, 2, 2, 2},
.numberOfConsumers = 0,
.scale = 0.1f,
.zeroPoint = 128,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<uint8_t>({})
}},
.operations = {{
.type = TestOperationType::BOX_WITH_NMS_LIMIT,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8},
.outputs = {9, 10, 11, 12}
}, {
.type = TestOperationType::ROI_ALIGN,
.inputs = {13, 10, 12, 14, 15, 16, 17, 18, 19, 20},
.outputs = {21}
}, {
.type = TestOperationType::SUB,
.inputs = {21, 22, 23},
.outputs = {24}
}},
.inputIndexes = {13},
.outputIndexes = {9, 11, 24}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_zero_sized_quant8 = TestModelManager::get().add("sub_v1_2_zero_sized_quant8", get_test_model_zero_sized_quant8());
} // namespace generated_tests::sub_v1_2
namespace generated_tests::sub_v1_2 {
const TestModel& get_test_model_zero_sized_float16() {
static TestModel model = {
.main = { // zero_sized
.operands = {{ // scores
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.8999999761581421f, 0.10000000149011612f})
}, { // roi
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 8},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({1.0f, 1.0f, 10.0f, 10.0f, 0.0f, 0.0f, 10.0f, 10.0f})
}, { // param1
.type = TestOperandType::TENSOR_INT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // param2
.type = TestOperandType::FLOAT16,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.30000001192092896f})
}, { // param3
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({-1})
}, { // param4
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // param5
.type = TestOperandType::FLOAT16,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.4000000059604645f})
}, { // param6
.type = TestOperandType::FLOAT16,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({1.0f})
}, { // param7
.type = TestOperandType::FLOAT16,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({0.30000001192092896f})
}, { // scoresOut
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {0},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // roiOut
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {0, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // classesOut
.type = TestOperandType::TENSOR_INT32,
.dimensions = {0},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({})
}, { // batchSplitOut
.type = TestOperandType::TENSOR_INT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({})
}, { // in
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 1, 1, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({1.0f, 2.0f})
}, { // param8
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // param9
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({2})
}, { // param10
.type = TestOperandType::FLOAT16,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f})
}, { // param11
.type = TestOperandType::FLOAT16,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({2.0f})
}, { // param12
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // param13
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // layout
.type = TestOperandType::BOOL,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<bool8>({false})
}, { // featureMap
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {0, 2, 2, 2},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}, { // op
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {1, 2, 2, 1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({1.0f, 2.0f, 3.0f, 4.0f})
}, { // param14
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // out
.type = TestOperandType::TENSOR_FLOAT16,
.dimensions = {0, 2, 2, 2},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<_Float16>({})
}},
.operations = {{
.type = TestOperationType::BOX_WITH_NMS_LIMIT,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8},
.outputs = {9, 10, 11, 12}
}, {
.type = TestOperationType::ROI_ALIGN,
.inputs = {13, 10, 12, 14, 15, 16, 17, 18, 19, 20},
.outputs = {21}
}, {
.type = TestOperationType::SUB,
.inputs = {21, 22, 23},
.outputs = {24}
}},
.inputIndexes = {13},
.outputIndexes = {9, 11, 24}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_zero_sized_float16 = TestModelManager::get().add("sub_v1_2_zero_sized_float16", get_test_model_zero_sized_float16());
} // namespace generated_tests::sub_v1_2
| 52.845868 | 1,245 | 0.378057 | [
"model"
] |
f3369dbd0ec9353f9fe945673dc89d579704d168 | 765 | hpp | C++ | src/v2/hasher.hpp | fslobanov/veeam-signature | e981d56c81646f9f24e2e60cf2b807e7faa28bd8 | [
"MIT"
] | null | null | null | src/v2/hasher.hpp | fslobanov/veeam-signature | e981d56c81646f9f24e2e60cf2b807e7faa28bd8 | [
"MIT"
] | null | null | null | src/v2/hasher.hpp | fslobanov/veeam-signature | e981d56c81646f9f24e2e60cf2b807e7faa28bd8 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <functional>
#include <boost/asio.hpp>
#include <signature.hpp>
namespace signature2 {
class segment_hasher_t final
{
public:
using crc32_t = uint32_t;
using hash_t = hashed_segment_t;
public:
hash_t operator ()( segment_t && segment ) const noexcept;
private:
crc32_t compute_crc32( const void * memory, std::size_t size ) const noexcept;
};
class hasher_t final
{
public:
using callback_t = std::function< void( hashed_segment_t && segment ) >;
public:
explicit hasher_t( boost::asio::io_context & context, callback_t && callback ) noexcept;
void operator ()( segment_t && segment ) noexcept;
private:
boost::asio::io_context & context;
const callback_t callback;
};
}
| 17.790698 | 92 | 0.700654 | [
"vector"
] |
f336dd7d012c3895fa506372d07c749ea3f89687 | 2,297 | cpp | C++ | third_party/libigl/include/igl/launch_medit.cpp | chefmramos85/monster-mash | 239a41f6f178ca83c4be638331e32f23606b0381 | [
"Apache-2.0"
] | 1,125 | 2021-02-01T09:51:56.000Z | 2022-03-31T01:50:40.000Z | third_party/libigl/include/igl/launch_medit.cpp | ryan-cranfill/monster-mash | c1b906d996885f8a4011bdf7558e62e968e1e914 | [
"Apache-2.0"
] | 19 | 2021-02-01T12:36:30.000Z | 2022-03-19T14:02:50.000Z | third_party/libigl/include/igl/launch_medit.cpp | ryan-cranfill/monster-mash | c1b906d996885f8a4011bdf7558e62e968e1e914 | [
"Apache-2.0"
] | 148 | 2021-02-13T10:54:31.000Z | 2022-03-28T11:55:20.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// 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/.
#include "launch_medit.h"
#include "writeMESH.h"
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#define MEDIT_PATH "/opt/local/bin/medit"
#define TEMP_MESH_FILE "/var/tmp/temp.mesh"
#define TEMP_MEDIT_FILE "/var/tmp/temp.medit"
template <typename DerivedV, typename DerivedT, typename DerivedF>
IGL_INLINE int igl::launch_medit(
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedT> & T,
const Eigen::PlainObjectBase<DerivedF> & F,
const bool wait)
{
using namespace std;
// Build medit command, end with & so command returns without waiting
stringstream command;
command<<MEDIT_PATH<<" "<<TEMP_MESH_FILE<<" "<<TEMP_MEDIT_FILE;
if(!wait)
{
command<<" &";
}
bool mesh_saved = writeMESH(TEMP_MESH_FILE,V,T,F);
if(!mesh_saved)
{
return -1;
}
// Write default medit options
const string default_medit_file_contents =
"BackgroundColor 1 1 1\n"
"LineColor 0 0 0\n"
"WindowSize 1024 800\n"
"RenderMode shading + lines\n";
FILE * fp = fopen(TEMP_MEDIT_FILE,"w");
if(fp == NULL)
{
cerr<<"^"<<__FUNCTION__<<": Could not write to "<<TEMP_MEDIT_FILE<<endl;
return -1;
}
fprintf(fp,"%s",default_medit_file_contents.c_str());
fclose(fp);
try
{
return system(command.str().c_str());
}catch(int e)
{
(void)e;
cerr<<"^"<<__FUNCTION__<<": Calling to medit crashed..."<<endl;
return -1;
}
// Could clean up and delete these files but not really worth it
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
template int igl::launch_medit<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, bool);
#endif
| 32.352113 | 374 | 0.673923 | [
"mesh",
"geometry"
] |
f33976b7369fa0d193663eb2550562c1342d9de1 | 3,642 | cpp | C++ | Second Set/Third Exercise/main.cpp | ManosL/Object-Oriented-Programming-2017-18 | bc48941e58ae1dcbc4c7c51557e9a00c49f7800d | [
"MIT"
] | null | null | null | Second Set/Third Exercise/main.cpp | ManosL/Object-Oriented-Programming-2017-18 | bc48941e58ae1dcbc4c7c51557e9a00c49f7800d | [
"MIT"
] | null | null | null | Second Set/Third Exercise/main.cpp | ManosL/Object-Oriented-Programming-2017-18 | bc48941e58ae1dcbc4c7c51557e9a00c49f7800d | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <vector>
#include <string>
#include "Artifact.h"
using namespace std;
static const time_t CURRENT_YEAR = 2018; //I make this define's for better understanding of my program
static const size_t MIN_LENGTH = 150;
static const size_t MAX_LENGTH = 300;
static const size_t MIN_WIDTH = 150;
static const size_t MAX_WIDTH = 300;
static const size_t MIN_VOLUME = 150;
static const size_t MAX_VOLUME = 300;
void auction(const vector<Artifact*>&,const mMovement&,const mCondition&);
string num_to_string(const int&);
int main(int argc,char* argv[]){
vector<Artifact*> artifacts;
int artifact_number;
mMovement auction_movement;
mCondition auction_condition;
srand(time(NULL));
if(argc != 4){ //If the user don't give enough arguments
cout<<"Wrong input"<<endl;
cout<<"Right format of input"<<endl;
cout<<"<number of artifacts> <movement value> <condition value>"<<endl;
return -1;
}
if(atoi(argv[1]) <= 0){ //If the user give invalid number of artifacts
cout<<"Wrong input"<<endl;
cout<<"Number of artifacts should take a number bigger than 0."<<endl;
return -1;
}
else{
artifact_number = atoi(argv[1]);
}
//If the user give wrong values
if(strcmp(argv[2],"impressionism") && strcmp(argv[2],"expressionism") && strcmp(argv[2],"naturalism")){
cout<<"Wrong input"<<endl;
cout<<"Movement should take these values: impressionism,expressionism or naturalism."<<endl;
return -1;
}
else{
if(!strcmp(argv[2],"impressionism")) auction_movement = IMPRESSIONISM;
else
if(!strcmp(argv[2],"expressionism")) auction_movement = EXPRESSIONISM;
else
if(!strcmp(argv[2],"naturalism")) auction_movement = NATURALISM;
}
if(strcmp(argv[3],"bad") && strcmp(argv[3],"good") && strcmp(argv[3],"excellent")){
cout<<"Wrong input"<<endl;
cout<<"Condition should take these values: bad,good or excellent."<<endl;
return -1;
}
else{
if(!strcmp(argv[3],"bad")) auction_condition = BAD;
else
if(!strcmp(argv[3],"good")) auction_condition = GOOD;
else
if(!strcmp(argv[3],"excellent")) auction_condition = EXCELLENT;
}
for(int i = 0;i < artifact_number;i++){
string current = num_to_string(i + 1); //I need this to have the creator name as Creator1,Creator2, etc.
mMovement move = (mMovement) (rand() % 3);
mCondition cond = (mCondition) (rand() % 3);
if(rand() % 2 == 0){
pTechnique tech = (pTechnique) (rand() % 3);
artifacts.push_back(new Painting("Creator"+current,rand()%CURRENT_YEAR,move,cond,(rand()%(MAX_LENGTH - MIN_LENGTH))+ MIN_LENGTH,(rand()%(MAX_WIDTH - MIN_WIDTH))+MIN_WIDTH,tech));
}
else{
sMaterial material = (sMaterial) (rand() % 3);
artifacts.push_back(new Sculpture("Creator"+current,rand()%CURRENT_YEAR,move,cond,(rand()%(MAX_VOLUME-MIN_VOLUME))+MIN_VOLUME,material));
}
}
auction(artifacts,auction_movement,auction_condition); //Runs the auction function
for(int i = 0;i < artifact_number;i++){ //Deletes the artifacts
delete artifacts[i];
}
return 0;
}
void auction(const vector<Artifact*>& artifacts,const mMovement& movement,const mCondition& condition){
const size_t size = artifacts.size();
for(int i = 0;i < size;i++){ //Does the necessary fields
artifacts[i]->getIndex();
artifacts[i]->getInfo();
cout<<"Evaluate returned: "<<artifacts[i]->evaluate(movement,condition)<<endl<<endl;
}
return;
}
string num_to_string(const int& num){
int curr_num = num;
string result;
while(curr_num != 0){
result.insert(result.begin(),(char) ((curr_num % 10) + 48));
curr_num /= 10;
}
return result;
}
| 28.904762 | 181 | 0.690829 | [
"vector"
] |
f33f58f751a5f90263dc2979d8b72c7dd688ea64 | 18,801 | cc | C++ | src/candidate_processor.cc | vejnar/chromap | f0ff121845f727b2142f04983211233f27302d13 | [
"MIT"
] | null | null | null | src/candidate_processor.cc | vejnar/chromap | f0ff121845f727b2142f04983211233f27302d13 | [
"MIT"
] | null | null | null | src/candidate_processor.cc | vejnar/chromap | f0ff121845f727b2142f04983211233f27302d13 | [
"MIT"
] | null | null | null | #include "candidate_processor.h"
#include <cinttypes>
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
namespace chromap {
void CandidateProcessor::GenerateCandidates(
int error_threshold, const Index &index,
MappingMetadata &mapping_metadata) const {
const std::vector<std::pair<uint64_t, uint64_t>> &minimizers =
mapping_metadata.minimizers_;
std::vector<uint64_t> &positive_hits = mapping_metadata.positive_hits_;
std::vector<uint64_t> &negative_hits = mapping_metadata.negative_hits_;
std::vector<Candidate> &positive_candidates =
mapping_metadata.positive_candidates_;
std::vector<Candidate> &negative_candidates =
mapping_metadata.negative_candidates_;
uint32_t &repetitive_seed_length = mapping_metadata.repetitive_seed_length_;
repetitive_seed_length = 0;
int repetitive_seed_count = index.CollectSeedHits(
max_seed_frequencies_[0], max_seed_frequencies_[0], minimizers,
repetitive_seed_length, positive_hits, negative_hits, false);
bool use_high_frequency_minimizers = false;
if (positive_hits.size() + negative_hits.size() == 0) {
positive_hits.clear();
negative_hits.clear();
repetitive_seed_length = 0;
repetitive_seed_count = index.CollectSeedHits(
max_seed_frequencies_[1], max_seed_frequencies_[0], minimizers,
repetitive_seed_length, positive_hits, negative_hits, true);
use_high_frequency_minimizers = true;
if (positive_hits.size() == 0 || negative_hits.size() == 0) {
use_high_frequency_minimizers = false;
}
}
int num_required_seeds = minimizers.size() - repetitive_seed_count;
num_required_seeds = num_required_seeds > 1 ? num_required_seeds : 1;
num_required_seeds = num_required_seeds > min_num_seeds_required_for_mapping_
? min_num_seeds_required_for_mapping_
: num_required_seeds;
if (use_high_frequency_minimizers) {
num_required_seeds = min_num_seeds_required_for_mapping_;
}
// std::cerr << "Normal positive gen on one dir\n";
GenerateCandidatesOnOneDirection(error_threshold, num_required_seeds,
minimizers.size(), positive_hits,
positive_candidates);
// std::cerr << "Normal negative gen on one dir\n";
GenerateCandidatesOnOneDirection(error_threshold, num_required_seeds,
minimizers.size(), negative_hits,
negative_candidates);
// fprintf(stderr, "p+n: %d\n", positive_candidates->size() +
// negative_candidates->size()) ;
}
// Return 0 if it supplements normally. Return 1 if the supplement could be too
// aggressive, and MAPQ needs setting to 0.
int CandidateProcessor::SupplementCandidates(
int error_threshold, uint32_t search_range, const Index &index,
PairedEndMappingMetadata &paired_end_mapping_metadata) const {
std::vector<Candidate> augment_positive_candidates1;
std::vector<Candidate> augment_positive_candidates2;
std::vector<Candidate> augment_negative_candidates1;
std::vector<Candidate> augment_negative_candidates2;
int ret = 0;
for (int mate = 0; mate <= 1; ++mate) {
std::vector<std::pair<uint64_t, uint64_t>> *minimizers;
std::vector<uint64_t> *positive_hits;
std::vector<uint64_t> *negative_hits;
std::vector<Candidate> *positive_candidates;
std::vector<Candidate> *negative_candidates;
std::vector<Candidate> *mate_positive_candidates;
std::vector<Candidate> *mate_negative_candidates;
std::vector<Candidate> *augment_positive_candidates;
std::vector<Candidate> *augment_negative_candidates;
uint32_t *repetitive_seed_length;
if (mate == 0) {
minimizers = &paired_end_mapping_metadata.mapping_metadata1_.minimizers_;
positive_hits =
&paired_end_mapping_metadata.mapping_metadata1_.positive_hits_;
negative_hits =
&paired_end_mapping_metadata.mapping_metadata1_.negative_hits_;
positive_candidates =
&paired_end_mapping_metadata.mapping_metadata1_.positive_candidates_;
negative_candidates =
&paired_end_mapping_metadata.mapping_metadata1_.negative_candidates_;
mate_positive_candidates =
&paired_end_mapping_metadata.mapping_metadata2_.positive_candidates_;
mate_negative_candidates =
&paired_end_mapping_metadata.mapping_metadata2_.negative_candidates_;
augment_positive_candidates = &augment_positive_candidates1;
augment_negative_candidates = &augment_negative_candidates1;
repetitive_seed_length = &paired_end_mapping_metadata.mapping_metadata1_
.repetitive_seed_length_;
} else {
minimizers = &paired_end_mapping_metadata.mapping_metadata2_.minimizers_;
positive_hits =
&paired_end_mapping_metadata.mapping_metadata2_.positive_hits_;
negative_hits =
&paired_end_mapping_metadata.mapping_metadata2_.negative_hits_;
positive_candidates =
&paired_end_mapping_metadata.mapping_metadata2_.positive_candidates_;
negative_candidates =
&paired_end_mapping_metadata.mapping_metadata2_.negative_candidates_;
mate_positive_candidates =
&paired_end_mapping_metadata.mapping_metadata1_.positive_candidates_;
mate_negative_candidates =
&paired_end_mapping_metadata.mapping_metadata1_.negative_candidates_;
augment_positive_candidates = &augment_positive_candidates2;
augment_negative_candidates = &augment_negative_candidates2;
repetitive_seed_length = &paired_end_mapping_metadata.mapping_metadata2_
.repetitive_seed_length_;
}
uint32_t mm_count = minimizers->size();
bool augment_flag = true;
uint32_t candidate_num = positive_candidates->size();
for (uint32_t i = 0; i < candidate_num; ++i) {
if ((*positive_candidates)[i].count >= mm_count / 2) {
augment_flag = false;
break;
}
}
candidate_num = negative_candidates->size();
if (augment_flag) {
for (uint32_t i = 0; i < candidate_num; ++i) {
if ((*negative_candidates)[i].count >= mm_count / 2) {
augment_flag = false;
break;
}
}
}
if (augment_flag) {
positive_hits->clear();
negative_hits->clear();
positive_hits->reserve(max_seed_frequencies_[0]);
negative_hits->reserve(max_seed_frequencies_[0]);
int positive_rescue_result = 0;
int negative_rescue_result = 0;
if (mate_positive_candidates->size() > 0) {
positive_rescue_result =
GenerateCandidatesFromRepetitiveReadWithMateInfo(
error_threshold, index, *minimizers, *repetitive_seed_length,
*negative_hits, *augment_negative_candidates,
*mate_positive_candidates, kNegative, search_range);
}
if (mate_negative_candidates->size() > 0) {
negative_rescue_result =
GenerateCandidatesFromRepetitiveReadWithMateInfo(
error_threshold, index, *minimizers, *repetitive_seed_length,
*positive_hits, *augment_positive_candidates,
*mate_negative_candidates, kPositive, search_range);
}
// If one of the strand did not supplement due to too many best candidate,
// and the filtered strand have better best candidates,
// and there is no candidate directly from minimizers,
// then we remove the supplement
if (((positive_rescue_result < 0 && negative_rescue_result > 0 &&
-positive_rescue_result >= negative_rescue_result) ||
(positive_rescue_result > 0 && negative_rescue_result < 0 &&
positive_rescue_result <= -negative_rescue_result)) &&
positive_candidates->size() + negative_candidates->size() == 0) {
// augment_positive_candidates->clear();
// augment_negative_candidates->clear();
ret = 1;
}
}
}
if (augment_positive_candidates1.size() > 0) {
MergeCandidates(
error_threshold,
paired_end_mapping_metadata.mapping_metadata1_.positive_candidates_,
augment_positive_candidates1,
paired_end_mapping_metadata.mapping_metadata1_
.positive_candidates_buffer_);
}
if (augment_negative_candidates1.size() > 0) {
MergeCandidates(
error_threshold,
paired_end_mapping_metadata.mapping_metadata1_.negative_candidates_,
augment_negative_candidates1,
paired_end_mapping_metadata.mapping_metadata1_
.negative_candidates_buffer_);
}
if (augment_positive_candidates2.size() > 0) {
MergeCandidates(
error_threshold,
paired_end_mapping_metadata.mapping_metadata2_.positive_candidates_,
augment_positive_candidates2,
paired_end_mapping_metadata.mapping_metadata2_
.positive_candidates_buffer_);
}
if (augment_negative_candidates2.size() > 0) {
MergeCandidates(
error_threshold,
paired_end_mapping_metadata.mapping_metadata2_.negative_candidates_,
augment_negative_candidates2,
paired_end_mapping_metadata.mapping_metadata2_
.negative_candidates_buffer_);
}
return ret;
}
void CandidateProcessor::ReduceCandidatesForPairedEndRead(
uint32_t mapping_positions_distance,
PairedEndMappingMetadata &paired_end_mapping_metadata) const {
const std::vector<Candidate> &positive_candidates1 =
paired_end_mapping_metadata.mapping_metadata1_
.positive_candidates_buffer_;
const std::vector<Candidate> &negative_candidates1 =
paired_end_mapping_metadata.mapping_metadata1_
.negative_candidates_buffer_;
const std::vector<Candidate> &positive_candidates2 =
paired_end_mapping_metadata.mapping_metadata2_
.positive_candidates_buffer_;
const std::vector<Candidate> &negative_candidates2 =
paired_end_mapping_metadata.mapping_metadata2_
.negative_candidates_buffer_;
std::vector<Candidate> &filtered_positive_candidates1 =
paired_end_mapping_metadata.mapping_metadata1_.positive_candidates_;
std::vector<Candidate> &filtered_negative_candidates1 =
paired_end_mapping_metadata.mapping_metadata1_.negative_candidates_;
std::vector<Candidate> &filtered_positive_candidates2 =
paired_end_mapping_metadata.mapping_metadata2_.positive_candidates_;
std::vector<Candidate> &filtered_negative_candidates2 =
paired_end_mapping_metadata.mapping_metadata2_.negative_candidates_;
ReduceCandidatesForPairedEndReadOnOneDirection(
mapping_positions_distance, positive_candidates1, negative_candidates2,
filtered_positive_candidates1, filtered_negative_candidates2);
ReduceCandidatesForPairedEndReadOnOneDirection(
mapping_positions_distance, negative_candidates1, positive_candidates2,
filtered_negative_candidates1, filtered_positive_candidates2);
}
int CandidateProcessor::GenerateCandidatesFromRepetitiveReadWithMateInfo(
int error_threshold, const Index &index,
const std::vector<std::pair<uint64_t, uint64_t>> &minimizers,
uint32_t &repetitive_seed_length, std::vector<uint64_t> &hits,
std::vector<Candidate> &candidates,
const std::vector<Candidate> &mate_candidates, const Direction direction,
uint32_t search_range) const {
int max_seed_count = index.CollectSeedHitsFromRepetitiveReadWithMateInfo(
error_threshold, minimizers, repetitive_seed_length, hits,
mate_candidates, direction, search_range,
min_num_seeds_required_for_mapping_, max_seed_frequencies_[0]);
GenerateCandidatesOnOneDirection(error_threshold, /*num_seeds_required=*/1,
minimizers.size(), hits, candidates);
return max_seed_count;
}
void CandidateProcessor::GenerateCandidatesOnOneDirection(
int error_threshold, int num_seeds_required, uint32_t num_minimizers,
std::vector<uint64_t> &hits, std::vector<Candidate> &candidates) const {
hits.emplace_back(UINT64_MAX);
if (hits.size() > 0) {
int minimizer_count = 1;
// The number of seeds with the exact same reference position.
int equal_count = 1;
int best_equal_count = 1;
uint64_t previous_hit = hits[0];
uint32_t previous_reference_id = previous_hit >> 32;
uint32_t previous_reference_position = previous_hit;
uint64_t best_local_hit = hits[0];
for (uint32_t pi = 1; pi < hits.size(); ++pi) {
uint32_t current_reference_id = hits[pi] >> 32;
uint32_t current_reference_position = hits[pi];
#ifdef LI_DEBUG
printf("%s: %d %d\n", __func__, current_reference_id,
current_reference_position);
#endif
if (current_reference_id != previous_reference_id ||
current_reference_position >
previous_reference_position + error_threshold ||
((uint32_t)minimizer_count >= num_minimizers &&
current_reference_position >
(uint32_t)best_local_hit + error_threshold)) {
if (minimizer_count >= num_seeds_required) {
Candidate candidate;
candidate.position = best_local_hit;
candidate.count = best_equal_count;
candidates.push_back(candidate);
}
minimizer_count = 1;
equal_count = 1;
best_equal_count = 1;
best_local_hit = hits[pi];
} else {
if (hits[pi] == best_local_hit) {
++equal_count;
++best_equal_count;
} else if (hits[pi] == previous_hit) {
++equal_count;
if (equal_count > best_equal_count) {
best_local_hit = previous_hit;
best_equal_count = equal_count;
}
} else {
equal_count = 1;
}
++minimizer_count;
}
previous_hit = hits[pi];
previous_reference_id = current_reference_id;
previous_reference_position = current_reference_position;
}
}
}
// Merge c1 and c2 into buffer and then swap the results into c1.
void CandidateProcessor::MergeCandidates(int error_threshold,
std::vector<Candidate> &c1,
std::vector<Candidate> &c2,
std::vector<Candidate> &buffer) const {
if (c1.size() == 0) {
c1.swap(c2);
return;
}
uint32_t i, j;
uint32_t size1, size2;
size1 = c1.size();
size2 = c2.size();
buffer.clear();
#ifdef LI_DEBUG
for (i = 0; i < size1; ++i)
printf("c1: %d %d %d\n", (int)(c1[i].position >> 32), (int)c1[i].position,
c1[i].count);
for (i = 0; i < size2; ++i)
printf("c2: %d %d %d\n", (int)(c2[i].position >> 32), (int)c2[i].position,
c2[i].count);
#endif
i = 0;
j = 0;
while (i < size1 && j < size2) {
if (c1[i].position == c2[j].position) {
if (buffer.empty() ||
c1[i].position > buffer.back().position + error_threshold) {
if (c1[i].count > c2[j].count) {
buffer.push_back(c1[i]);
} else {
buffer.push_back(c2[j]);
}
}
++i, ++j;
} else if (c1[i].position < c2[j].position) {
if (buffer.empty() ||
c1[i].position > buffer.back().position + error_threshold) {
buffer.push_back(c1[i]);
}
++i;
} else {
if (buffer.empty() ||
c2[j].position > buffer.back().position + error_threshold) {
buffer.push_back(c2[j]);
}
++j;
}
}
while (i < size1) {
if (buffer.empty() ||
c1[i].position > buffer.back().position + error_threshold) {
buffer.push_back(c1[i]);
}
++i;
}
while (j < size2) {
if (buffer.empty() ||
c2[j].position > buffer.back().position + error_threshold) {
buffer.push_back(c2[j]);
}
++j;
}
c1.swap(buffer);
}
void CandidateProcessor::ReduceCandidatesForPairedEndReadOnOneDirection(
uint32_t mapping_positions_distance,
const std::vector<Candidate> &candidates1,
const std::vector<Candidate> &candidates2,
std::vector<Candidate> &filtered_candidates1,
std::vector<Candidate> &filtered_candidates2) const {
uint32_t i1 = 0;
uint32_t i2 = 0;
int num_unpaired_candidate1 = 0;
int num_unpaired_candidate2 = 0;
int num_unpaired_candidate_threshold = 5;
int max_candidate_count1 = 6;
int max_candidate_count2 = 6;
uint32_t previous_end_i2 = i2;
#ifdef LI_DEBUG
for (uint32_t i = 0; i < candidates1.size(); ++i)
printf("%s 0: %d %d:%d\n", __func__, i,
(int)(candidates1[i].position >> 32), (int)candidates1[i].position);
for (uint32_t i = 0; i < candidates2.size(); ++i)
printf("%s 1: %d %d:%d\n", __func__, i,
(int)(candidates2[i].position >> 32), (int)candidates2[i].position);
#endif
while (i1 < candidates1.size() && i2 < candidates2.size()) {
if (candidates1[i1].position >
candidates2[i2].position + mapping_positions_distance) {
if (i2 >= previous_end_i2 &&
num_unpaired_candidate2 < num_unpaired_candidate_threshold &&
(candidates1[i1].position >> 32) ==
(candidates2[i2].position >> 32) &&
candidates2[i2].count >= max_candidate_count2) {
filtered_candidates2.emplace_back(candidates2[i2]);
++num_unpaired_candidate2;
}
++i2;
} else if (candidates2[i2].position >
candidates1[i1].position + mapping_positions_distance) {
if (num_unpaired_candidate1 < num_unpaired_candidate_threshold &&
(candidates1[i1].position >> 32) ==
(candidates2[i2].position >> 32) &&
candidates1[i1].count >= max_candidate_count1) {
filtered_candidates1.emplace_back(candidates1[i1]);
++num_unpaired_candidate1;
}
++i1;
} else {
// ok, find a pair, we store current ni2 somewhere and keep looking until
// we go out of the range, then we go back and then move to next pi1 and
// keep doing the similar thing.
filtered_candidates1.emplace_back(candidates1[i1]);
if (candidates1[i1].count > max_candidate_count1) {
max_candidate_count1 = candidates1[i1].count;
}
uint32_t current_i2 = i2;
while (current_i2 < candidates2.size() &&
candidates2[current_i2].position <=
candidates1[i1].position + mapping_positions_distance) {
if (current_i2 >= previous_end_i2) {
filtered_candidates2.emplace_back(candidates2[current_i2]);
if (candidates2[current_i2].count > max_candidate_count2) {
max_candidate_count2 = candidates2[current_i2].count;
}
}
++current_i2;
}
previous_end_i2 = current_i2;
++i1;
}
}
}
} // namespace chromap
| 39.332636 | 80 | 0.682145 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.