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
f9e0cda2aa42e26a1c2bf2b3cacaa68418ce4272
1,032
cpp
C++
best_approach_for_some_algorithm/get_all_factor.cpp
utkarshrai2811/data-structure-and-algorithms
445a153afb31dcd8e11a54f7f4a84f93c80180ea
[ "Apache-2.0" ]
53
2020-09-26T19:44:33.000Z
2021-09-30T20:38:52.000Z
best_approach_for_some_algorithm/get_all_factor.cpp
utkarshrai2811/data-structure-and-algorithms
445a153afb31dcd8e11a54f7f4a84f93c80180ea
[ "Apache-2.0" ]
197
2020-08-25T18:13:56.000Z
2021-06-19T07:26:19.000Z
best_approach_for_some_algorithm/get_all_factor.cpp
utkarshrai2811/data-structure-and-algorithms
445a153afb31dcd8e11a54f7f4a84f93c80180ea
[ "Apache-2.0" ]
204
2020-08-24T09:21:02.000Z
2022-02-13T06:13:42.000Z
// time complexity of this algo is sqrt(n); /* written by pankaj kumar. */ #include<algorithm> #include<string.h> #include<iostream> #include<vector> #include<cmath> #include<set> using namespace std; typedef long long ll ; typedef vector<int> vi; typedef vector<pair<int,int>> vpi; typedef vector<ll> vl; typedef vector<pair<ll,ll>> vpl; typedef vector<string> vs; typedef set<string> ss; typedef set<int> si; typedef set<ll> sl; typedef set<pair<int,int>> spi; typedef set<pair<ll,ll>> spl; // macros #define pan cin.tie(0);cout.tie(0);ios_base::sync_with_stdio(0); #define mod 1000000007; #define phi 1.618 #define line cout<<endl; /* ascii value A=65,Z=90,a=97,z=122 */ int main() { int a,count=0; cout<<"Enter two number : "; cin>>a; cout<<"List of all factor of "<<a<<"is : "; for(int i=1;i<=sqrt(a);i++) { if(a%i==0) { if(a/i==i) { count++; cout<<i<<" "; } else { count+=2; cout<<a/i<<" "<<i<<" "; } } } line; cout<<"Hence total no of factor of "<<a<<" is "<<count<<endl; }
18.428571
64
0.625969
[ "vector" ]
f9e9b89c0c778a1fc97fc4a6067b6fb40f36a7ec
4,637
cpp
C++
ros/srrg_ros_wrappers/laser_message_listener.cpp
pet1330/spqrel_navigation
af0c0797404770c8c97825e081d41069d9c40cc9
[ "MIT" ]
28
2017-06-27T07:45:35.000Z
2022-02-19T03:34:18.000Z
ros/srrg_ros_wrappers/laser_message_listener.cpp
pet1330/spqrel_navigation
af0c0797404770c8c97825e081d41069d9c40cc9
[ "MIT" ]
12
2017-07-22T22:09:05.000Z
2021-07-30T10:20:45.000Z
ros/srrg_ros_wrappers/laser_message_listener.cpp
pet1330/spqrel_navigation
af0c0797404770c8c97825e081d41069d9c40cc9
[ "MIT" ]
18
2017-07-09T12:12:38.000Z
2022-01-27T22:37:42.000Z
#include "laser_message_listener.h" #include <srrg_messages/laser_message.h> #include <srrg_types/defs.h> namespace srrg_core_ros { using namespace std; using namespace srrg_core; LaserMessageListener::LaserMessageListener(ros::NodeHandle* nh, SensorMessageSorter* sorter_, tf::TransformListener* listener_, const std::string& odom_frame_id, const std::string& base_link_frame_id) { _node_handle = nh; _deque_length = 5; _imu_interpolator = 0; _listener = listener_; _sorter = sorter_; _base_link_frame_id = base_link_frame_id; _odom_frame_id = odom_frame_id; _laser_offset.setIdentity(); _verbose = 0; } void LaserMessageListener::subscribe(const std::string& laser_topic) { _laser_topic = laser_topic; _laser_subscriber = _node_handle->subscribe<sensor_msgs::LaserScan>(_laser_topic, 1, &LaserMessageListener::laserCallback, this); cerr << "subscribing to topic: " << _laser_topic << endl; } void LaserMessageListener::laserCallback(const sensor_msgs::LaserScanConstPtr& in_msg) { _laser_deque.push_back(*in_msg); if (_laser_deque.size()<_deque_length){ return; } sensor_msgs::LaserScan msg = _laser_deque.front(); _laser_deque.pop_front(); if (_listener) { tf::StampedTransform transform; try{ _listener->waitForTransform(_odom_frame_id, _base_link_frame_id, msg.header.stamp, ros::Duration(0.1) ); _listener->lookupTransform (_odom_frame_id, _base_link_frame_id, msg.header.stamp, transform); } catch (tf::TransformException ex){ ROS_ERROR("%s",ex.what()); } Eigen::Quaternionf q; q.x() = transform.getRotation().x(); q.y() = transform.getRotation().y(); q.z() = transform.getRotation().z(); q.w() = transform.getRotation().w(); _odom_pose.linear()=q.toRotationMatrix(); _odom_pose.translation()=Eigen::Vector3f(transform.getOrigin().x(), transform.getOrigin().y(), transform.getOrigin().z()); } LaserMessage* scan_msg=new LaserMessage(_laser_topic, msg.header.frame_id, msg.header.seq, msg.header.stamp.toSec()); // getting offset if (_listener) { char buffer[1024]; buffer[0] = 0; tf::StampedTransform transform; try{ _listener->waitForTransform(_base_link_frame_id, msg.header.frame_id, msg.header.stamp, ros::Duration(0.1) ); _listener->lookupTransform (_base_link_frame_id, msg.header.frame_id, msg.header.stamp, transform); } catch (tf::TransformException ex){ ROS_ERROR("%s",ex.what()); return; } Eigen::Quaternionf q; q.x() = transform.getRotation().x(); q.y() = transform.getRotation().y(); q.z() = transform.getRotation().z(); q.w() = transform.getRotation().w(); _laser_offset.linear()=q.toRotationMatrix(); _laser_offset.translation()=Eigen::Vector3f(transform.getOrigin().x(), transform.getOrigin().y(), transform.getOrigin().z()); } scan_msg->setOffset(_laser_offset); // fill in stuff scan_msg->setMinAngle(msg.angle_min); scan_msg->setMaxAngle(msg.angle_max); scan_msg->setAngleIncrement(msg.angle_increment); scan_msg->setMinRange(msg.range_min); scan_msg->setMaxRange(msg.range_max); scan_msg->setTimeIncrement(msg.time_increment); scan_msg->setScanTime(msg.scan_time); std::vector<float> ranges; ranges.resize(msg.ranges.size()); for (size_t i = 0; i < msg.ranges.size(); i++){ if ((msg.ranges[i] < msg.range_min) || std::isnan(msg.ranges[i])) ranges[i]=0; else if (msg.ranges[i] > msg.range_max) ranges[i]=msg.range_max; else ranges[i]=msg.ranges[i]; } scan_msg->setRanges(ranges); std::vector<float> intensities; intensities.resize(msg.intensities.size()); for (size_t i = 0; i < msg.intensities.size(); i++) intensities[i]=msg.intensities[i]; scan_msg->setIntensities(intensities); if (_imu_interpolator && _listener) { Eigen::Isometry3f imu = Eigen::Isometry3f::Identity(); Eigen::Quaternionf q_imu; if (!_imu_interpolator->getOrientation(q_imu, msg.header.stamp.toSec())) return; imu.linear() = q_imu.toRotationMatrix(); if (_verbose) cerr << "[li]"; scan_msg->setImu(imu); } else if (_listener) { scan_msg->setOdometry(_odom_pose); if (_verbose) cerr << "[lo]"; } else { if (_verbose) cerr << "[lx]"; } _sorter->insertMessage(scan_msg); } }
30.11039
133
0.646539
[ "vector", "transform" ]
f9ed383fcd44f1b2a9bb23af5331ff20492b2bdc
12,164
cpp
C++
draw.cpp
rocksdanister/floppybird
b9455c7da73cf5866483e5eb4b2dadceb5147a2a
[ "MIT" ]
5
2020-04-27T07:42:51.000Z
2021-09-25T11:45:45.000Z
draw.cpp
rocksdanister/floppybird
b9455c7da73cf5866483e5eb4b2dadceb5147a2a
[ "MIT" ]
null
null
null
draw.cpp
rocksdanister/floppybird
b9455c7da73cf5866483e5eb4b2dadceb5147a2a
[ "MIT" ]
8
2017-03-26T16:24:05.000Z
2022-01-21T03:44:22.000Z
#include <GL/glut.h> #include <stdio.h> #include <floppy.h> #include <iostream> #include <vector> #include <string> #include <SOIL/SOIL.h> #include <math.h> using namespace std; struct bricks { int x,y; int objdisp; }obj; vector<bricks> obstacleBrick; unsigned char* image; static GLuint texBird[4],texBac[2],texObj[3]; int width, height,score; float skyX,treeX,treeX2,groundX; int birdPhys,tmp,highscore,insidebrick,gameover,prevy; double syncBird; unsigned int i,j; void init() { glShadeModel(GL_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //............BIRD............... glGenTextures(4,texBird); glBindTexture(GL_TEXTURE_2D, texBird[0]); //texture 1 active glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/bird/frame-1.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); glBindTexture(GL_TEXTURE_2D, texBird[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/bird/frame-2.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); glBindTexture(GL_TEXTURE_2D, texBird[2]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/bird/frame-3.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); glBindTexture(GL_TEXTURE_2D, texBird[3]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/bird/frame-4.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); //.......BACKGROUND............. glGenTextures(2,texBac); glBindTexture(GL_TEXTURE_2D, texBac[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/background/cloud.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); glBindTexture(GL_TEXTURE_2D, texBac[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/background/ground.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); //..OBJECTS glGenTextures(3,texObj); glBindTexture(GL_TEXTURE_2D, texObj[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/objects/trees_near.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); glBindTexture(GL_TEXTURE_2D, texObj[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/objects/brick.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); glBindTexture(GL_TEXTURE_2D, texObj[2]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); image = SOIL_load_image( "res/objects/trees_far.png", &width, &height, 0, SOIL_LOAD_RGBA ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ); SOIL_free_image_data( image ); glEnable(GL_TEXTURE_2D); } GLuint base; void initialiseList() { base=glGenLists(6); glListBase(base); } void update(double temp) { syncBird+=temp; if(syncBird>=120) // bird winganimation running at 6fps { birdPhys++; if(birdPhys==3) birdPhys=0; syncBird-=120; } } void updateSynchronised() { if(gameover==0) { groundX-=4; if(groundX<-resX) groundX=0; skyX-=0.75; if(skyX<-resX) skyX=0; treeX-=2; if(treeX<-resX) treeX=0; treeX2-=1.75; if(treeX2<-resX) treeX2=0; } } void staticBird() { glNewList(base+0, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(0,resY/2,0); glTexCoord2f(1.0, 0.0); glVertex3f(30,resY/2,0); glTexCoord2f(1.0, -1.0); glVertex3f(30,(resY/2)+30,0); glTexCoord2f(0.0, -1.0); glVertex3f(0,(resY/2)+30,0); glEnd(); glEndList(); } void staticGround() { glNewList(base+1, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(0,0,0); glTexCoord2f(1.0, 0.0); glVertex3f(resX*2,0,0); glTexCoord2f(1.0, -1.0); glVertex3f(resX*2,(resY*10)/100,0); glTexCoord2f(0.0, -1.0); glVertex3f(0,(resY*10)/100,0); glEnd(); glEndList(); } void staticSky() { glNewList(base+2, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(0,0,0); glTexCoord2f(1.0, 0.0); glVertex3f(resX*2,0,0); glTexCoord2f(1.0, -1.0); glVertex3f(resX*2,resY,0); glTexCoord2f(0.0, -1.0); glVertex3f(0,resY,0); glEnd(); glEndList(); } void staticTrees() { glNewList(base+3, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(0,0,0); glTexCoord2f(1.0, 0.0); glVertex3f(resX*2,0,0); glTexCoord2f(1.0, -1.0); glVertex3f(resX*2,resY,0); glTexCoord2f(0.0, -1.0); glVertex3f(0,resY,0); glEnd(); glEndList(); } void staticTrees_2() { glNewList(base+5, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(0,0,0); glTexCoord2f(1.0, 0.0); glVertex3f(resX*2,0,0); glTexCoord2f(1.0, -1.0); glVertex3f(resX*2,resY,0); glTexCoord2f(0.0, -1.0); glVertex3f(0,resY,0); glEnd(); glEndList(); } void staticBrick() { //... BOTTOM BRICK glNewList(base+4, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(resX,-resY/2,0); glTexCoord2f(1.0, 0.0); glVertex3f(resX+50,-resY/2,0); glTexCoord2f(1.0, -1.0); glVertex3f(resX+50,resY/2-38,0); glTexCoord2f(0.0, -1.0); glVertex3f(resX,resY/2-38,0); glEnd(); //.... TOP BRICK glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(resX,resY+resY/2,0); glTexCoord2f(1.0, 0.0); glVertex3f(resX+50,resY+resY/2,0); glTexCoord2f(1.0, -1.0); glVertex3f(resX+50,resY/2+38,0); glTexCoord2f(0.0, -1.0); glVertex3f(resX,resY/2+38,0); glEnd(); glEndList(); } int hit1,hit2; void resetFunc() { if(gameover==0) { highscore=(highscore<score)?score:highscore; hit1=0;hit2=0; movementY=0; groundX=0; skyX=0; treeX=0; treeX2=0; obstacleBrick.clear(); score=0; insidebrick=0; startFlag=0; } else { gameoverAnimation(); } } void adjustBrick() //.... GOD MODE { int delta; for(i=0;i<obstacleBrick.size()&&i==0;i++) { delta=(movementY+(resY/2)+10) - ( ((resY/2))+ obstacleBrick[i].y); if(delta<0) delta*=-1; if( (movementY+(resY/2)+10) <= ( ((resY/2))+ obstacleBrick[i].y) ) { obstacleBrick[i].y+=-delta; } else { obstacleBrick[i].y+=delta; } } } void hitDetection() { if(gameover==0) { for(i=0;i<obstacleBrick.size();i++) { //Closest Brick X Further Brick X if( (resX+obstacleBrick[i].objdisp)<=30 && (resX+obstacleBrick[i].objdisp)>=-50 ) { insidebrick=1; //Bottom Brick Y original=(movementY+resY/2) Top Brick Y original=(movementY+resY/2+25) if( (movementY+(resY/2)+10) >= ( ((resY/2)-38)+ obstacleBrick[i].y) && (movementY+(resY/2)+30-5) <= ( ((resY/2)+38) +obstacleBrick[i].y) ) { hit1++; } else { hit2++; } } if(hit2>=1) { gameover=1; resetFunc(); } if(movementY<-(resY/2-30)) { if(god==0) { gameover=1; resetFunc(); } } } } } GLvoid *font_style = GLUT_STROKE_ROMAN; void renderStrokeFont(int x,int y,int z,const char* temp) { glPushMatrix(); glTranslatef(x,y,z); glLineWidth(2); glScalef(0.1,0.1,0.1); const char *c; for (c=temp; *c != '\0'; c++) { glutStrokeCharacter(font_style, *c); } glPopMatrix(); } int opt1; void draw() { glClearColor (1.0, 1.0, 1.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(opt1==0) { init(); initialiseList(); staticBrick(); staticGround(); staticBird(); staticSky(); staticTrees(); staticTrees_2(); opt1=1; } else { //...SKY glPushMatrix(); glTranslatef(skyX,0,0); glBindTexture(GL_TEXTURE_2D, texBac[0]); glCallList(base+2); glPopMatrix(); //...SCORE & TEXT glColor3f(0.5,0.5,0.5); string str2=">FLOPPY BIRD >Movement: SPACEBAR >Exit: ESC "; if(startFlag==0) { const char * t2 = str2.c_str(); renderStrokeFont(100,400,1,t2); } string str="Score: "+to_string(score)+" HighScore: "+to_string(highscore); const char * c = str.c_str(); renderStrokeFont(10,resY-25,0,c); glColor3f(1,1,1); //..TREES glPushMatrix(); glTranslatef(treeX2,0,0); glBindTexture(GL_TEXTURE_2D, texObj[2]); glCallList(base+5); glPopMatrix(); glPushMatrix(); glTranslatef(treeX,0,0); glBindTexture(GL_TEXTURE_2D, texObj[0]); glCallList(base+3); glPopMatrix(); if(startFlag==1) { //..BRICK GENERATION if(gameover==0) { if(tmp==75) { tmp=0; obj.x=0; obj.y= -100+rand()%200; if( abs(obj.y-prevy)>100) { if(prevy<0) obj.y-=50; else if(prevy>0) obj.y+=50; } obj.objdisp=0; obstacleBrick.push_back(obj); prevy=obj.y; } else { tmp++; } } //..BRICK for(j=0;j<obstacleBrick.size();j++) { if(obstacleBrick[j].objdisp<-(resX+60)) { score++;hit1=0;hit2=0;insidebrick=0; obstacleBrick.erase(obstacleBrick.begin()+j); } if(gameover==0) obstacleBrick[j].objdisp-=4; glPushMatrix(); glTranslatef(obstacleBrick[j].objdisp,obstacleBrick[j].y,0); glBindTexture(GL_TEXTURE_2D, texObj[1]); glCallList(base+4); glPopMatrix(); } } //..GROUND glPushMatrix(); glTranslatef(groundX,0,0); glBindTexture(GL_TEXTURE_2D, texBac[1]); glCallList(base+1); glPopMatrix(); //...BIRD glPushMatrix(); glTranslatef(movementX,movementY,0); glBindTexture(GL_TEXTURE_2D, texBird[birdPhys]); glCallList(base+0); glPopMatrix(); } if(god==1) adjustBrick(); hitDetection(); //glFinish(); glutSwapBuffers(); }
25.394572
141
0.692042
[ "vector" ]
f9fb23794d0ce4f4e1acda70ba956f87b1a61f05
984
cpp
C++
Sid's Contests/LeetCode contests/Weekly Contest 251/Sum of Digits of String after Convert.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/LeetCode contests/Weekly Contest 251/Sum of Digits of String after Convert.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/LeetCode contests/Weekly Contest 251/Sum of Digits of String after Convert.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA void convert(string s, vector<int> &a) { for(int i = 0; i < s.length(); i++) { int ch = (char)(s[i] - 'a'); ch++; a.push_back(ch); } } int sumDigits(int x) { int sum = 0; while(x) { sum += x%10; x = x/10; } return sum; } int getLucky(string s, int k) { vector<int> a; convert(s, a); // for(int i = 0; i < a.size(); i++) // cout << a[i] << " "; int sum = 0; for(int i = 0; i < a.size(); i++) { int x = sumDigits(a[i]); sum += x; } k--; while(k != 0) { sum = sumDigits(sum); k--; } return sum; } };
21.391304
69
0.382114
[ "vector" ]
e60246f2b79bce5f717e1e6d283882147edba303
7,969
cpp
C++
src/Library/Shaders/SSS/SubSurfaceScatteringShaderOp.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
1
2018-12-20T19:31:02.000Z
2018-12-20T19:31:02.000Z
src/Library/Shaders/SSS/SubSurfaceScatteringShaderOp.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
src/Library/Shaders/SSS/SubSurfaceScatteringShaderOp.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
////////////////////////////////////////////////////////////////////// // // SubSurfaceScatteringShaderOp.cpp - Implementation of the SubSurfaceScatteringShaderOp class // // Author: Aravind Krishnaswamy // Date of Birth: February 18, 2005 // Tabs: 4 // Comments: // // License Information: Please see the attached LICENSE.TXT file // ////////////////////////////////////////////////////////////////////// #include "pch.h" #include "SubSurfaceScatteringShaderOp.h" #include "../../Utilities/GeometricUtilities.h" #include "../../Utilities/stl_utils.h" #include "../../Sampling/HaltonPoints.h" using namespace RISE; using namespace RISE::Implementation; SubSurfaceScatteringShaderOp::SubSurfaceScatteringShaderOp( const unsigned int numPoints_, const Scalar error_, const unsigned int maxPointsPerNode_, const unsigned char maxDepth_, const Scalar irrad_scale_, const bool multiplyBSDF_, const bool regenerate_, const IShader& shader_, const ISubSurfaceExtinctionFunction& extinction_, const bool cache_, const bool low_discrepancy_ ) : numPoints( numPoints_ ), error( error_ ), maxPointsPerNode( maxPointsPerNode_ ), maxDepth( maxDepth_ ), irrad_scale( irrad_scale_ ), multiplyBSDF( multiplyBSDF_ ), regenerate( regenerate_ ), shader( shader_ ), extinction( extinction_ ), cache( cache_ ), low_discrepancy( low_discrepancy_ ) { extinction.addref(); shader.addref(); } SubSurfaceScatteringShaderOp::~SubSurfaceScatteringShaderOp( ) { PointSetMap::iterator i, e; for( i=pointsets.begin(), e=pointsets.end(); i!=e; i++ ) { delete i->second; } pointsets.clear(); extinction.release(); shader.release(); } //! Tells the shader to apply shade to the given intersection point void SubSurfaceScatteringShaderOp::PerformOperation( const RuntimeContext& rc, ///< [in] Runtime context const RayIntersection& ri, ///< [in] Intersection information const IRayCaster& caster, ///< [in] The Ray Caster to use for all ray casting needs const IRayCaster::RAY_STATE& rs, ///< [in] Current ray state RISEPel& c, ///< [in/out] Resultant color from op const IORStack* const ior_stack, ///< [in/out] Index of refraction stack const ScatteredRayContainer* pScat ///< [in] Scattering information ) const { c = RISEPel(0.0); const IScene* pScene = caster.GetAttachedScene(); // If these three things don't exist, then we can't do anything for this object if( !pScene ) { return; } // Only do stuff on a normal pass or on final gather if( rc.pass != RuntimeContext::PASS_NORMAL && rs.type == rs.eRayView ) { return; } // Lets check our rasterizer state to see if we even need to do work! if( cache ) { if( !rc.StateCache_HasStateChanged( this, c, ri.pObject, ri.geometric.rast ) ) { // State hasn't changed, use the value already there return; } } // Lets check our internal map and see if we have already setup a point set for this object PointSetMap::iterator it = pointsets.find( ri.pObject ); PointSetOctree* ps = 0; if( it == pointsets.end() ) { // Grab the mutex, we should only create this once per object create_mutex.lock(); // Once grabbed, check again, just in case someone else made one PointSetMap::iterator again = pointsets.find( ri.pObject ); if( again == pointsets.end() ) { // There is no point set ready, so we need to create one GlobalLog()->PrintEasyInfo( "SubSurfaceScatteringShaderOp:: Generating point sample set for object" ); PointSetOctree::PointSet points; BoundingBox bbox( Point3(INFINITY,INFINITY,INFINITY), Point3(-INFINITY,-INFINITY,-INFINITY) ); // Since we are uniformly sampling, we just divide the overall surface area by the number of sample points // const Scalar sample_area = ri.pObject->GetArea() / Scalar(numPoints); // Use a halton point sequence to make sure the sampling points are distributed in a good way MultiHalton mh; for( unsigned int i=0; i<numPoints; i++ ) { // Ask the object for a uniform random point PointSetOctree::SamplePoint sp; Vector3 normal; Point3 random_variables; if( low_discrepancy ) { random_variables = Point3( mh.mod1(mh.halton(0,i)), mh.mod1(mh.halton(1,i)), mh.mod1(mh.halton(2,i)) ); } else { random_variables = Point3( rc.random.CanonicalRandom(), rc.random.CanonicalRandom(), rc.random.CanonicalRandom() ); } ri.pObject->UniformRandomPoint( &sp.ptPosition, &normal, 0, random_variables ); // We may want in the future to move the point in (away from the surface) if we decide to add the option of occluders // sp.ptPosition = Point3Ops::mkPoint3( sp.ptPosition, normal*NEARZERO ); // move the sample points slightly away from the surface // Now compute the irradiance for this point using the BDF RayIntersection newri( ri ); newri.geometric.ray = Ray( sp.ptPosition, -normal ); newri.geometric.bHit = true; newri.geometric.ptIntersection = sp.ptPosition; newri.geometric.vNormal = normal; // Advance the ray for the purpose of shading, this should help reduce errors newri.geometric.ray.Advance( 1e-8 ); shader.Shade( rc, newri, caster, rs, sp.irrad, ior_stack ); // Discard points that have no illumination if( ColorMath::MaxValue(sp.irrad) > 0 ) { // sp.irrad = sp.irrad * sample_area; // remember we are integrating over surface area sp.irrad = sp.irrad * irrad_scale; points.push_back( sp ); bbox.Include( sp.ptPosition ); } } // bbox.Grow( NEARZERO ); // Grow for error tolerance bbox.EnsureBoxHasVolume(); ps = new PointSetOctree( bbox, maxPointsPerNode ); if( points.size() < 1 ) { GlobalLog()->PrintEasyError( "SubSurfaceScatteringShaderOp:: Not a single sample point could be generated" ); } if( !ps->AddElements( points, maxDepth ) ) { GlobalLog()->PrintEasyError( "SubSurfaceScatteringShaderOp:: Fatal error while creating irradiance sample set" ); } pointsets[ri.pObject] = ps; } else { // Some other thread just set it ps = again->second; } create_mutex.unlock(); } else { // There is already a point set, so we can just do our approximation now ps = it->second; } // We have a list of points that are part of our sample, // we must query all the points that are within one path length of us and evaluate how much light // gets here from there ps->Evaluate( c, ri.geometric.ptIntersection, extinction, error, multiplyBSDF?ri.pMaterial->GetBSDF():0, ri.geometric ); // Account for the integration over area // c = c * (1.0/Scalar(ri.pObject->GetArea())); // Since we know each point samples the area of the surface equally, we can just do this to save time c = c * (1.0/Scalar(numPoints)); if( ri.pMaterial->GetBSDF() && multiplyBSDF ) { c = c*PI; } if( cache ) { // Add the result to the rasterizer state cache rc.StateCache_SetState( this, c, ri.pObject, ri.geometric.rast ); } } //! Tells the shader to apply shade to the given intersection point for the given wavelength /// \return Amplitude of spectral function Scalar SubSurfaceScatteringShaderOp::PerformOperationNM( const RuntimeContext& rc, ///< [in] Runtime context const RayIntersection& ri, ///< [in] Intersection information const IRayCaster& caster, ///< [in] The Ray Caster to use for all ray casting needs const IRayCaster::RAY_STATE& rs, ///< [in] Current ray state const Scalar caccum, ///< [in] Current value for wavelength const Scalar nm, ///< [in] Wavelength to shade const IORStack* const ior_stack, ///< [in/out] Index of refraction stack const ScatteredRayContainer* pScat ///< [in] Scattering information ) const { Scalar c=0; //! \TODO To be implemented return c; } void SubSurfaceScatteringShaderOp::ResetRuntimeData() const { if( regenerate ) { PointSetMap::iterator i, e; for( i=pointsets.begin(), e=pointsets.end(); i!=e; i++ ) { delete i->second; } pointsets.clear(); } }
33.910638
134
0.689422
[ "object" ]
e60a3cba29a84161d7a125c96396104134f41f6a
1,469
hpp
C++
src/root-lib/world-units.hpp
snailbaron/root
e3e997e746ac001650513f4d9b466f8dfcf52075
[ "MIT" ]
null
null
null
src/root-lib/world-units.hpp
snailbaron/root
e3e997e746ac001650513f4d9b466f8dfcf52075
[ "MIT" ]
null
null
null
src/root-lib/world-units.hpp
snailbaron/root
e3e997e746ac001650513f4d9b466f8dfcf52075
[ "MIT" ]
null
null
null
#pragma once #include "geometry.hpp" #include "units.hpp" using Length = units::Length<float>; constexpr Length operator "" _m(long double meters) { return Length{static_cast<float>(meters)}; } constexpr Length operator "" _m(unsigned long long meters) { return Length{static_cast<float>(meters)}; } using Position = geometry::Vector<units::Length<float>>; using WorldRect = geometry::Vector<units::Length<float>>; using Vector2 = geometry::Vector<float>; using Speed = units::Speed<float>; constexpr Speed operator "" _mps(long double mps) { return Speed{static_cast<float>(mps)}; } constexpr Speed operator "" _mps(unsigned long long mps) { return Speed{static_cast<float>(mps)}; } using Velocity = geometry::Vector<units::Speed<float>>; using AbsoluteAcceleration = units::Acceleration<float>; constexpr AbsoluteAcceleration operator "" _mps2(long double mps2) { return AbsoluteAcceleration{static_cast<float>(mps2)}; } constexpr AbsoluteAcceleration operator "" _mps2(unsigned long long mps2) { return AbsoluteAcceleration{static_cast<float>(mps2)}; } using Acceleration = geometry::Vector<units::Acceleration<float>>; using Force = Acceleration; using AbsoluteForce = AbsoluteAcceleration; using Time = units::Time<float>; constexpr Time operator "" _s(long double seconds) { return Time{static_cast<float>(seconds)}; } constexpr Time operator "" _s(unsigned long long seconds) { return Time{static_cast<float>(seconds)}; }
26.709091
73
0.748809
[ "geometry", "vector" ]
e615ed48d97c72dd40d48c5dfb24237584342939
1,851
hpp
C++
series2_workbench/hyp_sys_1d/include/ancse/cfl_condition.hpp
BeatHubmann/19H-AdvNCSE
3979f768da933de82bd6ab29bbf31ea9fc31e501
[ "MIT" ]
1
2020-01-05T22:38:47.000Z
2020-01-05T22:38:47.000Z
series2_workbench/hyp_sys_1d/include/ancse/cfl_condition.hpp
BeatHubmann/19H-AdvNCSE
3979f768da933de82bd6ab29bbf31ea9fc31e501
[ "MIT" ]
null
null
null
series2_workbench/hyp_sys_1d/include/ancse/cfl_condition.hpp
BeatHubmann/19H-AdvNCSE
3979f768da933de82bd6ab29bbf31ea9fc31e501
[ "MIT" ]
1
2019-12-08T20:43:27.000Z
2019-12-08T20:43:27.000Z
#ifndef HYPSYS1D_CFL_CONDITION_HPP #define HYPSYS1D_CFL_CONDITION_HPP #include <cmath> #include <limits> #include <memory> #include <Eigen/Dense> #include <ancse/includes.hpp> #include <ancse/grid.hpp> #include <ancse/model.hpp> #include <ancse/dg_handler.hpp> /// Interface for computing CFL restricted timesteps. class CFLCondition { public: virtual ~CFLCondition() = default; /// Compute the largest time-step satisfying the CFL condition. virtual double operator()(const Eigen::MatrixXd &u) const = 0; }; class FVMCFLCondition : public CFLCondition { public: FVMCFLCondition(const Grid& grid, const std::shared_ptr<Model>& model, double cfl_number); virtual double operator() (const Eigen::MatrixXd& u) const override; private: Grid grid; std::shared_ptr<Model> model; double cfl_number; }; class DGCFLCondition: public CFLCondition { public: DGCFLCondition(const Grid& grid, const std::shared_ptr<Model>& model, const DGHandler& dg_handler, double cfl_number); virtual double operator() (const Eigen::MatrixXd& u) const override; private: Grid grid; std::shared_ptr<Model> model; DGHandler dg_handler; double cfl_number; }; /// make CFL condition for FVM std::shared_ptr<CFLCondition> make_cfl_condition(const Grid &grid, const std::shared_ptr<Model> &model, double cfl_number); /// make CFL condition for DG std::shared_ptr<CFLCondition> make_cfl_condition(const Grid &grid, const std::shared_ptr<Model> &model, const DGHandler &dg_handler, double cfl_number); #endif // HYPSYS1D_CFL_CONDITION_HPP
26.442857
76
0.636953
[ "model" ]
e621ed01cb560e9c8a5a295385e3fae8f015247c
1,912
cpp
C++
leetcode/problems/medium/898-bitwise-ors-of-subarrays.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/898-bitwise-ors-of-subarrays.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/898-bitwise-ors-of-subarrays.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Bitwise ORs of Subarrays We have an array arr of non-negative integers. For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j]. Return the number of possible results. Results that occur more than once are only counted once in the final answer Example 1: Input: arr = [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: arr = [1,1,2] Output: 3 Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. These yield the results 1, 1, 2, 1, 3, 3. There are 3 unique values, so the answer is 3. Example 3: Input: arr = [1,2,4] Output: 6 Explanation: The possible results are 1, 2, 3, 4, 6, and 7. Constraints: 1 <= nums.length <= 5 * 104 0 <= nums[i] <= 109 */ // AC class Solution { public: int subarrayBitwiseORs(vector<int>& arr) { // (a1) // (a2) (a2 a1) // (a3) (a3 a2) (a3 a2 a1) // (a4) (a4 a3) (a4 a3 a2) (a4 a3 a2 a1) // ... vector<int> ans; int left = 0, right = 0; for(int a : arr) { ans.emplace_back(a); for(int i = left; i < right; i++) { int x = a | ans[i]; if(x != ans.back()) { ans.emplace_back(x); } } left = right; right = (int) ans.size(); } return (int) unordered_set<int>(ans.begin(), ans.end()).size(); } }; // TLE class Solution { public: int subarrayBitwiseORs(vector<int>& arr) { set<int> ans, cur; for(int a : arr) { set<int> cur2; for(int b : cur) cur2.insert(a | b); cur2.insert(a); cur = cur2; ans.insert(cur.begin(), cur.end()); } return (int) ans.size(); } };
24.831169
192
0.521444
[ "vector" ]
e6220f74965b6eb6bc62d1a5090d117dd114f481
1,830
hpp
C++
MSCKF/dynamicVectorReference.hpp
michael-fonder/fonder_thesis-2016
59631865169857f935a52ffd89a07243fe00e7d1
[ "MIT" ]
26
2016-09-22T08:41:10.000Z
2022-02-17T02:49:45.000Z
MSCKF/dynamicVectorReference.hpp
michael-fonder/fonder_thesis-2016
59631865169857f935a52ffd89a07243fe00e7d1
[ "MIT" ]
4
2016-09-06T11:25:16.000Z
2018-05-31T12:29:50.000Z
MSCKF/dynamicVectorReference.hpp
michael-fonder/fonder_thesis-2016
59631865169857f935a52ffd89a07243fe00e7d1
[ "MIT" ]
19
2016-08-30T07:17:51.000Z
2018-11-08T07:29:18.000Z
#ifndef DYNAMIC_VECTOR_REFERENCE #define DYNAMIC_VECTOR_REFERENCE #include <stdio.h> #include <stdint.h> #include <unordered_map> #include <vector> #include "dynamicVector.hpp" //#include "dynamicVector.h" template <typename Object> class DynamicVectorReference : public DynamicVector<Object> { public : //DynamicVectorReference(const DynamicVectorReference<Object> &toCopy); Object* push_back(Object* toInsert); void remove(std::unordered_set<Object*> &toRemove); }; // template <typename Object> // DynamicVectorReference<Object>::DynamicVectorReference(const DynamicVectorReference<Object> &toCopy) // { // this->objectVec =toCopy.objectVec; // this->indexMap = toCopy.indexMap; // } // Constant template <typename Object> Object* DynamicVectorReference<Object>::push_back(Object* toInsert) { this->indexMap.insert({toInsert, this->objectVec.size()}); this->objectVec.push_back(toInsert); return toInsert; } // Linear in container size whatever the size of the given set of element to remove // => more efficient to remove one big set than several small ones template <typename Object> void DynamicVectorReference<Object>::remove(std::unordered_set<Object*> &toRemove) { // Remove element and its references in data structures int end = -1; for(int i=this->objectVec.size()-1; i>=-1; --i) { if(i>=0 && toRemove.find(this->objectVec[i]) != toRemove.end()) { if(end<0) end = i+1; this->objectVec.erase(this->objectVec.begin()+i); } // else if(i<0 || (end>=0 && toRemove.find(this->objectVec[i]) == toRemove.end())) // { // this->objectVec.erase(this->objectVec.begin()+i+1, this->objectVec.begin()+end); // end = -1; // } } // Rebuild indexMap this->indexMap.clear(); for(int32_t i=0; i<this->objectVec.size(); ++i) this->indexMap.insert({this->objectVec[i], i}); } #endif
27.727273
103
0.710929
[ "object", "vector" ]
e623329a289b3a0ae32ea856fbf01c52aa67cf17
1,940
hpp
C++
addons/medical/configs/vehicles/Medication.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/medical/configs/vehicles/Medication.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/medical/configs/vehicles/Medication.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
class SOCOMD_MorphineItem : Item_Base_F { scope=SCOPE_PUBLIC; scopeCurator=SCOPE_PUBLIC; displayName="Morphine 10mg/1mL Ampoule"; icon="\z\socomd\addons\data\icon\VPN.paa"; vehicleClass="Items"; class TransportItems { TRANSPORT_ITEM(SOCOMD_morphine,1) }; }; class SOCOMD_epinephrineItem : Item_Base_F { scope=SCOPE_PUBLIC; scopeCurator=SCOPE_PUBLIC; displayName="Adrenaline 1mg/1mL Ampoule"; icon="\z\socomd\addons\data\icon\VPN.paa"; vehicleClass="Items"; class TransportItems { TRANSPORT_ITEM(SOCOMD_epinephrine,1) }; }; class SOCOMD_fentanylItem : Item_Base_F { scope=SCOPE_PUBLIC; scopeCurator=SCOPE_PUBLIC; displayName="Fentanyl 100mcg/2mL"; icon="\z\socomd\addons\data\icon\VPN.paa"; vehicleClass="Items"; class TransportItems { TRANSPORT_ITEM(SOCOMD_fentanyl,1) }; }; class SOCOMD_naloxonelItem : Item_Base_F { scope=2; scopeCurator=2; displayName="Naloxone 1.6mg/4mL"; author="Monk"; icon="\z\socomd\addons\data\icon\VPN.paa"; vehicleClass="Items"; class TransportItems { TRANSPORT_ITEM(SOCOMD_naloxone,1) }; }; class SOCOMD_ketamineItem : Item_Base_F { scope=2; scopeCurator=2; displayName="Naloxone 1.6mg/4mL"; author="Monk"; icon="\z\socomd\addons\data\icon\VPN.paa"; vehicleClass="Items"; class TransportItems { TRANSPORT_ITEM(SOCOMD_ketamine,1) }; }; class Leaflet_05_F; class SOCOMD_ApapLitter : Leaflet_05_F { hiddenSelectionsTextures[]= { "\z\socomd\addons\data\icon\apap_litter.paa" }; }; class SOCOMD_ApapItem : Item_Base_F { scope=2; scopeCurator=2; displayName="Paracetemol 1g"; icon="\z\socomd\addons\data\icon\apap.paa"; model="\A3\Structures_F_EPA\Items\Medical\PainKillers_F.p3d"; vehicleClass="Items"; class TransportItems { TRANSPORT_ITEM(SOCOMD_Apap,1) }; };
25.526316
65
0.682474
[ "model" ]
e625d959615e5b3d6e2cd6baff395c5b6f529552
4,701
hpp
C++
src/methods/naive_bayes/gaussian_naive_bayes.hpp
zhaoqi19/Machine-Learning-algorithms-practices
bde826466cf8a23f232db222a1068b867aaa5a90
[ "MIT" ]
null
null
null
src/methods/naive_bayes/gaussian_naive_bayes.hpp
zhaoqi19/Machine-Learning-algorithms-practices
bde826466cf8a23f232db222a1068b867aaa5a90
[ "MIT" ]
null
null
null
src/methods/naive_bayes/gaussian_naive_bayes.hpp
zhaoqi19/Machine-Learning-algorithms-practices
bde826466cf8a23f232db222a1068b867aaa5a90
[ "MIT" ]
null
null
null
#ifndef METHODS_NAIVE_BAYES_GAUSSIAN_NAIVE_BAYES_HPP #define METHODS_NAIVE_BAYES_GAUSSIAN_NAIVE_BAYES_HPP #include "../../prereqs.hpp" #include "../../core.hpp" #include "base.hpp" using namespace openml; namespace openml { namespace naive_bayes { template<typename DataType> class GaussianNB: public BaseNB<DataType> { private: // define matrix and vector Eigen type using MatType = Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>; using VecType = Eigen::Matrix<DataType, Eigen::Dynamic, 1>; using IdxType = Eigen::Vector<Eigen::Index, Eigen::Dynamic>; double var_smoothing_; protected: /** * @param means Matrix of shape [n_classes, n_feature], * measn of each feature for different class * @param vars Matrix of shape [n_classes, n_feature], * variances of each feature for different class */ MatType mean_; MatType var_; /** * compute log posterior prbabilty, P(c|x) = P(c)P(x|c) * log(P(c|x)) = log(P(C)) + log(P(x|c)) for all rows x of X, * as an array-like of shape (n_classes, n_samples). */ const MatType joint_log_likelihood(const MatType& X) const { std::size_t num_samples = X.rows(); MatType jll(num_samples, this->num_classes_); jll.setZero(); VecType log_prior = this->prior_prob_.array().log(); MatType lp = utils::repeat<MatType>(log_prior.transpose(), num_samples, 0); for (std::size_t i = 0; i < this->num_classes_; i++) { auto val = var_.row(i) * 2.0 * M_PI; VecType sum_log_var = math::sum<MatType, VecType>(val.array().log().matrix()) * (-0.5); MatType repeated_sum_log_var = utils::repeat<MatType>(sum_log_var, num_samples, 0); MatType X_minus_mean = X.array() - utils::repeat<MatType>(mean_.row(i), num_samples, 0).array(); MatType X_minus_mean_squared = X_minus_mean.array().square(); MatType repeated_var = utils::repeat<MatType>(var_.row(i), num_samples, 0); MatType X_minus_mean_div_var = X_minus_mean_squared.array() / repeated_var.array(); VecType ll = repeated_sum_log_var.array() - 0.5 * math::sum<MatType, VecType>(X_minus_mean_div_var, 1).array(); jll.col(i) = ll.array() + lp.array(); } return jll; }; /** * Compute Gaussian mean and variance */ void update_mean_variance(const MatType& X, const VecType& y) { std::size_t num_samples = X.rows(), num_features = X.cols(); MatType mean(num_features, this->num_classes_); MatType var(num_features, this->num_classes_); MatType X_y(num_samples, num_features + 1); X_y = utils::hstack<MatType>(X, y); std::size_t new_i = 0; for (auto& label : this->label_map_) { MatType partial_X_y(label.second, num_features + 1); std::vector<std::size_t> keep_rows; for (std::size_t i = 0; i < X_y.rows(); ++i) { if (X_y(i, num_features) == label.first) { keep_rows.push_back(i); } } IdxType keep_cols = IdxType::LinSpaced(X_y.cols(), 0, X_y.cols()); partial_X_y = X_y(keep_rows, keep_cols); mean.col(new_i) = math::mean<MatType, VecType>(partial_X_y.leftCols(num_features), 0); var.col(new_i) = math::var<MatType, VecType>(partial_X_y.leftCols(num_features), 0); new_i++; } mean_ = mean.transpose(); var_ = var.transpose(); } public: /** * @param var_smoothing float, default=1e-9 * Portion of the largest variance of all features. */ GaussianNB(): BaseNB<DataType>(), var_smoothing_(1e-9){}; explicit GaussianNB(double var_smoothing) : BaseNB<DataType>(), var_smoothing_(var_smoothing){}; ~GaussianNB() {}; /** * Fit the model with X. * @param X array-like of shape (num_samples, num_features) * Training data, where num_samples is the number of * samples and num_features is the number of features. */ void fit(const MatType& X, const VecType& y) { this->compute_prior_prob(y); this->update_mean_variance(X, y); var_ = var_.array() + var_smoothing_ * var_.maxCoeff(); }; /** get the mean attributes */ const VecType get_mean() const { return mean_; } /** get the var attributes */ const VecType get_var() const { return var_; } }; } // naive_bayes } // openml #endif /*METHODS_NAIVE_BAYES_GAUSSIAN_NAIVE_BAYES_HPP*/
33.820144
123
0.604127
[ "shape", "vector", "model" ]
e63243f4823eb9f093c9d08021e7ce89a7cc51b7
1,875
cpp
C++
Engine/Application.cpp
lowysole/BugEngine
aa40f7fd2dcf13b01d2542666ad7dd899fee07c1
[ "MIT" ]
null
null
null
Engine/Application.cpp
lowysole/BugEngine
aa40f7fd2dcf13b01d2542666ad7dd899fee07c1
[ "MIT" ]
null
null
null
Engine/Application.cpp
lowysole/BugEngine
aa40f7fd2dcf13b01d2542666ad7dd899fee07c1
[ "MIT" ]
null
null
null
#pragma once #include "Application.h" #include "ModuleWindow.h" #include "ModuleRender.h" #include "ModuleInput.h" #include "ModuleCamera.h" #include "ModuleProgram.h" #include "ModuleTexture.h" #include "ModuleEditor.h" #include "ModuleDebugDraw.h" #include "Model.h" #include "leak.h" using namespace std; Application::Application() { modules.reserve(9); modules.push_back(window = new ModuleWindow()); modules.push_back(camera = new ModuleCamera()); modules.push_back(renderer = new ModuleRender()); modules.push_back(input = new ModuleInput()); modules.push_back(program = new ModuleProgram()); modules.push_back(texture = new ModuleTexture()); modules.push_back(model = new Model()); modules.push_back(debug_draw = new ModuleDebugDraw()); modules.push_back(editor = new ModuleEditor()); } Application::~Application() { for (vector<Module*>::iterator it = modules.begin(); it != modules.end(); ++it) { delete* it; } } bool Application::Init() { bool ret = true; for (vector<Module*>::iterator it = modules.begin(); it != modules.end() && ret; ++it) ret = (*it)->Init(); return ret; } update_status Application::Update() { update_status ret = UPDATE_CONTINUE; for (vector<Module*>::iterator it = modules.begin(); it != modules.end() && ret == UPDATE_CONTINUE; ++it) ret = (*it)->PreUpdate(); for (vector<Module*>::iterator it = modules.begin(); it != modules.end() && ret == UPDATE_CONTINUE; ++it) ret = (*it)->Update(); for (vector<Module*>::iterator it = modules.begin(); it != modules.end() && ret == UPDATE_CONTINUE; ++it) ret = (*it)->PostUpdate(); return ret; } bool Application::CleanUp() { bool ret = true; for (vector<Module*>::reverse_iterator it = modules.rbegin(); it != modules.rend() && ret; ++it) ret = (*it)->CleanUp(); return ret; }
25.684932
107
0.653867
[ "vector", "model" ]
e635330e19dd471b2e794414af7ce3a29e1e38e0
1,929
cpp
C++
Code Forces/Code forces 43B - Letter.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
28
2017-11-08T11:52:11.000Z
2021-07-16T06:30:02.000Z
Code Forces/Code forces 43B - Letter.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
null
null
null
Code Forces/Code forces 43B - Letter.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
30
2017-09-01T09:14:27.000Z
2021-04-12T12:08:56.000Z
// Author: Sofen Hoque Anonta #Problm: #include <iostream> #include <cstdio> #include <climits> #include <map> #include <vector> #include <cmath> #include <queue> #include <algorithm> #include <utility> #include <string> #include <cstring> //using namespace std; using namespace std; namespace { typedef long long LL; typedef vector<int> vint; typedef pair<int,int> pint; typedef unsigned long long ULL; int CC_; #define sf scanf #define pf printf #define PP cin.get(); #define NL cout<<endl; template <class T>void DA(T i,T e){while(i!=e){cout<<"Con>>( "<<++CC_<<" ) "<<*i++<<endl;}} template <class T>void DA(T* x, int l){for(int i=0; i<l;i++)cout<<"["<<i<<"]>> "<<x[i]<<endl;} #define DC(x_) cout<<">>> "<<#x_<<"\n";DA(x_.begin(), x_.end()); #define DD(x_) cout<<">>>>( "<<++CC_<<" ) "<<#x_<<": "<<x_<<endl; #define SS printf(">_<LOOOOOK@MEEEEEEEEEEEEEEE<<( %d )>>\n",++CC_); const double EPS= 1E-9; const double PI= 2*acos(0.0); const long long MOD= 1000000007; } int heading_freq[128]; int msg_freq[128]; void solve(){ string heading, msg; getline(cin, heading); getline(cin, msg); int len = heading.size(); for(int i= 0; i<len; i++){ char ch = heading[i]; if(ch != ' '){ heading_freq[ch]++; } } len = msg.size(); for(int i= 0; i<len; i++){ char ch = msg[i]; if(ch != ' '){ msg_freq[ch]++; } } bool flag = true; for(char ch= 'a'; ch <= 'z'; ch++){ if(heading_freq[ch] < msg_freq[ch]){ flag= false; break; } } for(char ch= 'A'; ch <= 'Z'; ch++){ if(heading_freq[ch] < msg_freq[ch]){ flag= false; break; } } cout<< (flag ? "YES" : "NO") <<endl; } int main(){ // ios_base::sync_with_stdio(false); // cin.tie(NULL); // freopen("F:/input.txt", "r", stdin); solve(); return 0; }
19.886598
94
0.536029
[ "vector" ]
e63a16faa9bf963c38d385dfc4071b04eb43ee0b
169
cpp
C++
Week-2/Day-12-singleNonDuplicate.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
1
2020-05-02T04:21:54.000Z
2020-05-02T04:21:54.000Z
Week-2/Day-12-singleNonDuplicate.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
null
null
null
Week-2/Day-12-singleNonDuplicate.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
null
null
null
class Solution { public: int singleNonDuplicate(vector<int>& nums) { int ans = 0; for(int i : nums) ans ^= i; return ans; } };
18.777778
48
0.497041
[ "vector" ]
e63f44e90334caa31a1a3ee9a6d9eeea2faec874
33,806
cpp
C++
pangolin/display.cpp
akramhussein/SimpleHDR
818ff433789737a8431ae9e891c366562e37bcd6
[ "MIT" ]
1
2018-09-18T09:28:42.000Z
2018-09-18T09:28:42.000Z
pangolin/display.cpp
akramhussein/SimpleHDR
818ff433789737a8431ae9e891c366562e37bcd6
[ "MIT" ]
null
null
null
pangolin/display.cpp
akramhussein/SimpleHDR
818ff433789737a8431ae9e891c366562e37bcd6
[ "MIT" ]
null
null
null
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2011 Steven Lovegrove, Richard Newcombe * * 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 <iostream> #include <sstream> #include <map> #include <boost/function.hpp> #include <boost/foreach.hpp> #define foreach BOOST_FOREACH #include "platform.h" #include "display.h" #include "display_internal.h" #include "simple_math.h" using namespace std; namespace pangolin { const int panal_v_margin = 6; typedef boost::ptr_unordered_map<string,PangolinGl> ContextMap; // Map of active contexts ContextMap contexts; // Context active for current thread __thread PangolinGl* context = 0; PangolinGl::PangolinGl() : quit(false), mouse_state(0), activeDisplay(0) { } void BindToContext(std::string name) { ContextMap::iterator ic = contexts.find(name); if( ic == contexts.end() ) { // Create and add if not found ic = contexts.insert( name,new PangolinGl ).first; context = ic->second; View& dc = context->base; dc.left = 0.0; dc.bottom = 0.0; dc.top = 1.0; dc.right = 1.0; dc.aspect = 0; dc.handler = &StaticHandler; context->is_fullscreen = false; #ifdef HAVE_GLUT process::Resize( glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT) ); #else process::Resize(640,480); #endif //HAVE_GLUT }else{ context = ic->second; } } void Quit() { context->quit = true; } bool ShouldQuit() { #ifdef HAVE_GLUT return context->quit || !glutGetWindow(); #else return context->quit; #endif } bool HadInput() { if( context->had_input > 0 ) { --context->had_input; return true; } return false; } bool HasResized() { if( context->has_resized > 0 ) { --context->has_resized; return true; } return false; } void RenderViews() { DisplayBase().Render(); } View& DisplayBase() { return context->base; } View& CreateDisplay() { int iguid = rand(); std::stringstream ssguid; ssguid << iguid; return Display(ssguid.str()); } View& Display(const std::string& name) { // Get / Create View boost::ptr_unordered_map<std::string,View>::iterator vi = context->named_managed_views.find(name); if( vi != context->named_managed_views.end() ) { return *(vi->second); }else{ View * v = new View(); bool inserted = context->named_managed_views.insert(name, v).second; if(!inserted) throw exception(); v->handler = &StaticHandler; context->base.views.push_back(v); return *v; } } void RegisterKeyPressCallback(int key, boost::function<void(void)> func) { context->keypress_hooks[key] = func; } namespace process { unsigned int last_x; unsigned int last_y; void Keyboard( unsigned char key, int x, int y) { context->had_input = context->is_double_buffered ? 2 : 1; // Force coords to match OpenGl Window Coords y = context->base.v.h - y; if( key == GLUT_KEY_ESCAPE) { context->quit = true; } #ifdef HAVE_CVARS else if(key == '`') { context->console.ToggleConsole(); // Force refresh for several frames whilst panel opens/closes context->had_input = 60*2; }else if(context->console.IsOpen()) { // Direct input to console if( key > 128 ) { context->console.SpecialFunc(key - 128 ); }else{ context->console.KeyboardFunc(key); } } #endif // HAVE_CVARS #ifdef HAVE_GLUT else if( key == GLUT_KEY_TAB) { if( context->is_fullscreen ) { glutReshapeWindow(context->windowed_size[0],context->windowed_size[1]); context->is_fullscreen = false; }else{ glutFullScreen(); context->is_fullscreen = true; } } #endif // HAVE_GLUT else if(context->keypress_hooks.find(key) != context->keypress_hooks.end() ) { context->keypress_hooks[key](); } else if(context->activeDisplay && context->activeDisplay->handler) { context->activeDisplay->handler->Keyboard(*(context->activeDisplay),key,x,y,true); } } void KeyboardUp(unsigned char key, int x, int y) { // Force coords to match OpenGl Window Coords y = context->base.v.h - y; if(context->activeDisplay && context->activeDisplay->handler) { context->activeDisplay->handler->Keyboard(*(context->activeDisplay),key,x,y,false); } } void SpecialFunc(int key, int x, int y) { Keyboard(key+128,x,y); } void SpecialFuncUp(int key, int x, int y) { KeyboardUp(key+128,x,y); } void Mouse( int button_raw, int state, int x, int y) { last_x = x; last_y = y; const MouseButton button = (MouseButton)(1 << button_raw); const bool pressed = (state == 0); context->had_input = context->is_double_buffered ? 2 : 1; // Force coords to match OpenGl Window Coords y = context->base.v.h - y; const bool fresh_input = (context->mouse_state == 0); if( pressed ) { context->mouse_state |= button; }else{ context->mouse_state &= ~button; } if(fresh_input) { context->base.handler->Mouse(context->base,button,x,y,pressed,context->mouse_state); }else if(context->activeDisplay && context->activeDisplay->handler) { context->activeDisplay->handler->Mouse(*(context->activeDisplay),button,x,y,pressed,context->mouse_state); } } void MouseMotion( int x, int y) { last_x = x; last_y = y; context->had_input = context->is_double_buffered ? 2 : 1; // Force coords to match OpenGl Window Coords y = context->base.v.h - y; if( context->activeDisplay) { if( context->activeDisplay->handler ) context->activeDisplay->handler->MouseMotion(*(context->activeDisplay),x,y,context->mouse_state); }else{ context->base.handler->MouseMotion(context->base,x,y,context->mouse_state); } } void PassiveMouseMotion(int x, int y) { last_x = x; last_y = y; } void Resize( int width, int height ) { if( !context->is_fullscreen ) { context->windowed_size[0] = width; context->windowed_size[1] = width; } // TODO: Fancy display managers seem to cause this to mess up? context->had_input = 20; //context->is_double_buffered ? 2 : 1; context->has_resized = 20; //context->is_double_buffered ? 2 : 1; Viewport win(0,0,width,height); context->base.Resize(win); } void Scroll(float x, float y) { cout << "Scroll: " << x << ", " << y << endl; if(x==0) { Mouse(y>0?3:4,0, last_x, last_y); context->mouse_state &= !MouseWheelUp; context->mouse_state &= !MouseWheelDown; } } void Zoom(float m) { cout << "Zoom: " << m << endl; } } #ifdef HAVE_GLUT void PangoGlutRedisplay() { glutPostRedisplay(); // RenderViews(); // FinishGlutFrame(); } void TakeGlutCallbacks() { glutKeyboardFunc(&process::Keyboard); glutKeyboardUpFunc(&process::KeyboardUp); glutReshapeFunc(&process::Resize); glutMouseFunc(&process::Mouse); glutMotionFunc(&process::MouseMotion); glutPassiveMotionFunc(&process::PassiveMouseMotion); glutSpecialFunc(&process::SpecialFunc); glutSpecialUpFunc(&process::SpecialFuncUp); #ifdef HAVE_APPLE_OPENGL_FRAMEWORK glutDisplayFunc(&PangoGlutRedisplay); // Attempt to register special smooth scroll callback // https://github.com/nanoant/osxglut typedef void (*glutScrollFunc_t)(void (*)(float, float)); glutScrollFunc_t glutScrollFunc = (glutScrollFunc_t)glutGetProcAddress("glutScrollFunc"); if(glutScrollFunc) { glutScrollFunc(&process::Scroll); } typedef void (*glutZoomFunc_t)(void (*)(float)); glutZoomFunc_t glutZoomFunc = (glutZoomFunc_t)glutGetProcAddress("glutZoomFunc"); if(glutZoomFunc) { cout << "Registering zoom func" << endl; glutZoomFunc(&process::Zoom); } #endif } void CreateGlutWindowAndBind(string window_title, int w, int h, unsigned int mode) { #ifdef HAVE_FREEGLUT if( glutGet(GLUT_INIT_STATE) == 0) #endif { int argc = 0; glutInit(&argc, 0); glutInitDisplayMode(mode); } glutInitWindowSize(w,h); glutCreateWindow(window_title.c_str()); BindToContext(window_title); #ifdef HAVE_FREEGLUT glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif context->is_double_buffered = mode & GLUT_DOUBLE; TakeGlutCallbacks(); } void FinishGlutFrame() { RenderViews(); DisplayBase().Activate(); Viewport::DisableScissor(); #ifdef HAVE_CVARS context->console.RenderConsole(); #endif // HAVE_CVARS SwapGlutBuffersProcessGlutEvents(); } void SwapGlutBuffersProcessGlutEvents() { glutSwapBuffers(); #ifdef HAVE_FREEGLUT glutMainLoopEvent(); #endif #ifdef HAVE_GLUT_APPLE_FRAMEWORK glutCheckLoop(); #endif } #endif // HAVE_GLUT void Viewport::Activate() const { glViewport(l,b,w,h); } void Viewport::Scissor() const { glEnable(GL_SCISSOR_TEST); glScissor(l,b,w,h); } void Viewport::ActivateAndScissor() const { glViewport(l,b,w,h); glEnable(GL_SCISSOR_TEST); glScissor(l,b,w,h); } void Viewport::DisableScissor() { glDisable(GL_SCISSOR_TEST); } bool Viewport::Contains(int x, int y) const { return l <= x && x < (l+w) && b <= y && y < (b+h); } Viewport Viewport::Inset(int i) const { return Viewport(l+i, b+i, w-2*i, h-2*i); } Viewport Viewport::Inset(int horiz, int vert) const { return Viewport(l+horiz, b+vert, w-horiz, h-vert); } void OpenGlMatrix::Load() const { glLoadMatrixd(m); } void OpenGlMatrix::Multiply() const { glMultMatrixd(m); } void OpenGlMatrix::SetIdentity() { m[0] = 1.0f; m[1] = 0.0f; m[2] = 0.0f; m[3] = 0.0f; m[4] = 0.0f; m[5] = 1.0f; m[6] = 0.0f; m[7] = 0.0f; m[8] = 0.0f; m[9] = 0.0f; m[10] = 1.0f; m[11] = 0.0f; m[12] = 0.0f; m[13] = 0.0f; m[14] = 0.0f; m[15] = 1.0f; } void OpenGlRenderState::Apply() const { // Apply any stack matrices we have for(map<OpenGlStack,OpenGlMatrix>::const_iterator i = stacks.begin(); i != stacks.end(); ++i ) { glMatrixMode(i->first); i->second.Load(); } // Leave in MODEVIEW mode glMatrixMode(GL_MODELVIEW); } OpenGlRenderState::OpenGlRenderState() { } OpenGlRenderState::OpenGlRenderState(const OpenGlMatrix& projection_matrix) { stacks[GlProjectionStack] = projection_matrix; stacks[GlModelViewStack] = IdentityMatrix(); } OpenGlRenderState::OpenGlRenderState(const OpenGlMatrix& projection_matrix, const OpenGlMatrix& modelview_matrx) { stacks[GlProjectionStack] = projection_matrix; stacks[GlModelViewStack] = modelview_matrx; } void OpenGlRenderState::ApplyIdentity() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void OpenGlRenderState::ApplyWindowCoords() { context->base.v.Activate(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, context->base.v.w, 0, context->base.v.h); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } OpenGlRenderState& OpenGlRenderState::SetProjectionMatrix(OpenGlMatrix spec) { stacks[GlProjectionStack] = spec; return *this; } OpenGlRenderState& OpenGlRenderState::SetModelViewMatrix(OpenGlMatrix spec) { stacks[GlModelViewStack] = spec; return *this; } OpenGlRenderState& OpenGlRenderState::Set(OpenGlMatrixSpec spec) { stacks[spec.type] = spec; return *this; } OpenGlMatrix& OpenGlRenderState::GetProjectionMatrix() { return stacks[GlProjectionStack]; } OpenGlMatrix OpenGlRenderState::GetProjectionMatrix() const { std::map<OpenGlStack,OpenGlMatrix>::const_iterator i = stacks.find(GlProjectionStack); if( i == stacks.end() ) { return IdentityMatrix(); }else{ return i->second; } } OpenGlMatrix& OpenGlRenderState::GetModelViewMatrix() { return stacks[GlModelViewStack]; } OpenGlMatrix OpenGlRenderState::GetModelViewMatrix() const { std::map<OpenGlStack,OpenGlMatrix>::const_iterator i = stacks.find(GlModelViewStack); if( i == stacks.end() ) { return IdentityMatrix(); }else{ return i->second; } } int AttachAbs( int low, int high, Attach a) { if( a.unit == Pixel ) return low + a.p; if( a.unit == ReversePixel ) return high - a.p; return low + a.p * (high - low); } float AspectAreaWithinTarget(double target, double test) { if( test < target ) return test / target; else return target / test; } void View::Resize(const Viewport& p) { // Compute Bounds based on specification v.l = AttachAbs(p.l,p.r(),left); v.b = AttachAbs(p.b,p.t(),bottom); int r = AttachAbs(p.l,p.r(),right); int t = AttachAbs(p.b,p.t(),top); // Make sure left and right, top and bottom are correct order if( t < v.b ) swap(t,v.b); if( r < v.l ) swap(r,v.l); v.w = r - v.l; v.h = t - v.b; vp = v; // Adjust based on aspect requirements if( aspect != 0 ) { const float current_aspect = (float)v.w / (float)v.h; if( aspect > 0 ) { // Fit to space if( current_aspect < aspect ) { //Adjust height const int nh = (int)(v.w / aspect); v.b += vlock == LockBottom ? 0 : (vlock == LockCenter ? (v.h-nh)/2 : (v.h-nh) ); v.h = nh; }else if( current_aspect > aspect ) { //Adjust width const int nw = (int)(v.h * aspect); v.l += hlock == LockLeft? 0 : (hlock == LockCenter ? (v.w-nw)/2 : (v.w-nw) ); v.w = nw; } }else{ // Overfit double true_aspect = -aspect; if( current_aspect < true_aspect ) { //Adjust width const int nw = (int)(v.h * true_aspect); v.l += hlock == LockLeft? 0 : (hlock == LockCenter ? (v.w-nw)/2 : (v.w-nw) ); v.w = nw; }else if( current_aspect > true_aspect ) { //Adjust height const int nh = (int)(v.w / true_aspect); v.b += vlock == LockBottom ? 0 : (vlock == LockCenter ? (v.h-nh)/2 : (v.h-nh) ); v.h = nh; } } } ResizeChildren(); } void View::ResizeChildren() { if( layout == LayoutOverlay ) { foreach(View* i, views) i->Resize(v); }else if( layout == LayoutVertical ) { // Allocate space incrementally Viewport space = v.Inset(panal_v_margin); int num_children = 0; foreach(View* i, views ) { num_children++; if(scroll_offset > num_children ) { i->show = false; }else{ i->show = true; i->Resize(space); space.h = i->v.b - panal_v_margin - space.b; } } }else if(layout == LayoutHorizontal ) { // Allocate space incrementally const int margin = 8; Viewport space = v.Inset(margin); foreach(View* i, views ) { i->Resize(space); space.w = i->v.l + margin + space.l; } }else if(layout == LayoutEqual ) { // TODO: Make this neater, and make fewer assumptions! if( views.size() > 0 ) { const double this_a = abs(v.aspect()); const double child_a = abs(views[0]->aspect); double a = views.size()*child_a; double area = AspectAreaWithinTarget(this_a, a); int cols = views.size()-1; for(; cols > 0; --cols) { const int rows = views.size() / cols + (views.size() % cols == 0 ? 0 : 1); const double na = cols * child_a / rows; const double new_area = views.size()*AspectAreaWithinTarget(this_a,na)/(rows*cols); if( new_area <= area ) break; area = new_area; a = na; } cols++; const int rows = views.size() / cols + (views.size() % cols == 0 ? 0 : 1); int cw,ch; if( a > this_a ) { cw = v.w / cols; ch = cw / child_a; //v.h / rows; }else{ ch = v.h / rows; cw = ch * child_a; } for( unsigned int i=0; i< views.size(); ++i ) { int c = i % cols; int r = i / cols; Viewport space(v.l + c*cw, v.t() - (r+1)*ch, cw,ch); views[i]->Resize(space); } } } } void View::Render() { if(!extern_draw_function.empty()) { extern_draw_function(*this); } RenderChildren(); } void View::RenderChildren() { foreach(View* v, views) if(v->show) v->Render(); } void View::Activate() const { v.Activate(); } void View::ActivateAndScissor() const { vp.Scissor(); v.Activate(); } void View::ActivateScissorAndClear() const { vp.Scissor(); v.Activate(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void View::Activate(const OpenGlRenderState& state ) const { v.Activate(); state.Apply(); } void View::ActivateAndScissor(const OpenGlRenderState& state) const { vp.Scissor(); v.Activate(); state.Apply(); } void View::ActivateScissorAndClear(const OpenGlRenderState& state ) const { vp.Scissor(); v.Activate(); state.Apply(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } GLfloat View::GetClosestDepth(int x, int y, int radius) const { glReadBuffer(GL_FRONT); const int zl = (radius*2+1); const int zsize = zl*zl; GLfloat zs[zsize]; glReadPixels(x-radius,y-radius,zl,zl,GL_DEPTH_COMPONENT,GL_FLOAT,zs); const GLfloat mindepth = *(std::min_element(zs,zs+zsize)); return mindepth; } void View::GetObjectCoordinates(const OpenGlRenderState& cam_state, double winx, double winy, double winzdepth, double& x, double& y, double& z) const { const GLint viewport[4] = {v.l,v.b,v.w,v.h}; const OpenGlMatrix proj = cam_state.GetProjectionMatrix(); const OpenGlMatrix mv = cam_state.GetModelViewMatrix(); gluUnProject(winx, winy, winzdepth, mv.m, proj.m, viewport, &x, &y, &z); } void View::GetCamCoordinates(const OpenGlRenderState& cam_state, double winx, double winy, double winzdepth, double& x, double& y, double& z) const { const GLint viewport[4] = {v.l,v.b,v.w,v.h}; const OpenGlMatrix proj = cam_state.GetProjectionMatrix(); gluUnProject(winx, winy, winzdepth, Identity4d, proj.m, viewport, &x, &y, &z); } View& View::SetFocus() { context->activeDisplay = this; return *this; } View& View::SetBounds(Attach bottom, Attach top, Attach left, Attach right, bool keep_aspect) { SetBounds(top,bottom,left,right,0.0); aspect = keep_aspect ? v.aspect() : 0; return *this; } View& View::SetBounds(Attach bottom, Attach top, Attach left, Attach right, double aspect) { this->left = left; this->top = top; this->right = right; this->bottom = bottom; this->aspect = aspect; this->Resize(context->base.v); return *this; } View& View::SetAspect(double aspect) { this->aspect = aspect; this->Resize(context->base.v); return *this; } View& View::SetLock(Lock horizontal, Lock vertical ) { vlock = vertical; hlock = horizontal; return *this; } View& View::SetLayout(Layout l) { layout = l; return *this; } View& View::AddDisplay(View& child) { // detach child from any other view, and add to this vector<View*>::iterator f = std::find( context->base.views.begin(), context->base.views.end(), &child ); if( f != context->base.views.end() ) context->base.views.erase(f); views.push_back(&child); return *this; } View& View::operator[](int i) { return *views[i]; } View& View::SetHandler(Handler* h) { handler = h; return *this; } View& View::SetDrawFunction(const boost::function<void(View&)>& drawFunc) { extern_draw_function = drawFunc; return *this; } View* FindChild(View& parent, int x, int y) { // Find in reverse order to mirror draw order for( vector<View*>::const_reverse_iterator i = parent.views.rbegin(); i != parent.views.rend(); ++i ) if( (*i)->show && (*i)->vp.Contains(x,y) ) return (*i); return 0; } void Handler::Keyboard(View& d, unsigned char key, int x, int y, bool pressed) { View* child = FindChild(d,x,y); if( child) { context->activeDisplay = child; if( child->handler) child->handler->Keyboard(*child,key,x,y,pressed); } } void Handler::Mouse(View& d, MouseButton button, int x, int y, bool pressed, int button_state) { View* child = FindChild(d,x,y); if( child ) { context->activeDisplay = child; if( child->handler) child->handler->Mouse(*child,button,x,y,pressed,button_state); } } void Handler::MouseMotion(View& d, int x, int y, int button_state) { View* child = FindChild(d,x,y); if( child ) { context->activeDisplay = child; if( child->handler) child->handler->MouseMotion(*child,x,y,button_state); } } void HandlerScroll::Mouse(View& d, MouseButton button, int x, int y, bool pressed, int button_state) { if( button == button_state && (button == MouseWheelUp || button == MouseWheelDown) ) { if( button == MouseWheelUp) d.scroll_offset -= 1; if( button == MouseWheelDown) d.scroll_offset += 1; d.scroll_offset = max(0, min(d.scroll_offset, (int)d.views.size()) ); d.ResizeChildren(); }else{ Handler::Mouse(d,button,x,y,pressed,button_state); } } void Handler3D::Keyboard(View&, unsigned char key, int x, int y, bool pressed) { // TODO: hooks for reset / changing mode (perspective / ortho etc) } void Handler3D::Mouse(View& display, MouseButton button, int x, int y, bool pressed, int button_state) { // mouse down last_pos[0] = x; last_pos[1] = y; double T_nc[3*4]; LieSetIdentity(T_nc); if( pressed && cam_state->stacks.find(GlProjectionStack) != cam_state->stacks.end() ) { const GLfloat mindepth = display.GetClosestDepth(x,y,hwin); last_z = mindepth != 1 ? mindepth : last_z; if( last_z != 1 ) { display.GetCamCoordinates(*cam_state, x, y, last_z, rot_center[0], rot_center[1], rot_center[2]); }else{ SetZero<3,1>(rot_center); } if( button == MouseWheelUp || button == MouseWheelDown) { LieSetIdentity(T_nc); const double t[] = { 0,0,(button==MouseWheelUp?1:-1)*100*tf}; LieSetTranslation<>(T_nc,t); if( !(button_state & MouseButtonRight) && !(rot_center[0]==0 && rot_center[1]==0 && rot_center[2]==0) ) { LieSetTranslation<>(T_nc,rot_center); MatMul<3,1>(T_nc+(3*3),(button==MouseWheelUp?-1.0:1.0)/5.0); } OpenGlMatrix& spec = cam_state->stacks[GlModelViewStack]; LieMul4x4bySE3<>(spec.m,T_nc,spec.m); } } } // Direction vector for each AxisDirection enum const static GLdouble AxisDirectionVector[][3] = { {0,0,0}, {-1,0,0}, {1,0,0}, {0,-1,0}, {0,1,0}, {0,0,-1}, {0,0,1} }; void Handler3D::MouseMotion(View& display, int x, int y, int button_state) { const int delta[2] = {(x-last_pos[0]),(y-last_pos[1])}; const float mag = delta[0]*delta[0] + delta[1]*delta[1]; // TODO: convert delta to degrees based of fov // TODO: make transformation with respect to cam spec if( mag < 50*50 ) { OpenGlMatrix& mv = cam_state->GetModelViewMatrix(); const GLdouble* up = AxisDirectionVector[enforce_up]; double T_nc[3*4]; LieSetIdentity(T_nc); bool rotation_changed = false; if( button_state == MouseButtonMiddle ) { // Middle Drag: in plane translate Rotation<>(T_nc,-delta[1]*0.01, -delta[0]*0.01, 0.0); }else if( button_state == MouseButtonLeft ) { // Left Drag: in plane translate if( last_z != 1 ) { GLdouble np[3]; display.GetCamCoordinates(*cam_state,x,y,last_z, np[0], np[1], np[2]); const double t[] = { np[0] - rot_center[0], np[1] - rot_center[1], 0}; LieSetTranslation<>(T_nc,t); std::copy(np,np+3,rot_center); }else{ const double t[] = { -10*delta[0]*tf, 10*delta[1]*tf, 0}; LieSetTranslation<>(T_nc,t); } }else if( button_state == (MouseButtonLeft | MouseButtonRight) ) { // Left and Right Drag: in plane rotate about object // Rotation<>(T_nc,0.0,0.0, delta[0]*0.01); double T_2c[3*4]; Rotation<>(T_2c,0.0,0.0, delta[0]*0.01); double mrotc[3]; MatMul<3,1>(mrotc, rot_center, -1.0); LieApplySO3<>(T_2c+(3*3),T_2c,mrotc); double T_n2[3*4]; LieSetIdentity<>(T_n2); LieSetTranslation<>(T_n2,rot_center); LieMulSE3(T_nc, T_n2, T_2c ); rotation_changed = true; }else if( button_state == MouseButtonRight) { double aboutx = -0.01 * delta[1]; double abouty = 0.01 * delta[0]; if(enforce_up) { // Special case if view direction is parallel to up vector const double updotz = mv.m[2]*up[0] + mv.m[6]*up[1] + mv.m[10]*up[2]; if(updotz > 0.98) aboutx = std::min(aboutx,0.0); if(updotz <-0.98) aboutx = std::max(aboutx,0.0); // Module rotation around y so we don't spin too fast! abouty *= (1-0.6*abs(updotz)); } // Right Drag: object centric rotation double T_2c[3*4]; Rotation<>(T_2c, aboutx, abouty, 0.0); double mrotc[3]; MatMul<3,1>(mrotc, rot_center, -1.0); LieApplySO3<>(T_2c+(3*3),T_2c,mrotc); double T_n2[3*4]; LieSetIdentity<>(T_n2); LieSetTranslation<>(T_n2,rot_center); LieMulSE3(T_nc, T_n2, T_2c ); rotation_changed = true; } LieMul4x4bySE3<>(mv.m,T_nc,mv.m); if(enforce_up != AxisNone && rotation_changed) { EnforceUpT_cw(mv.m, up); } } last_pos[0] = x; last_pos[1] = y; } // Use OpenGl's default frame of reference OpenGlMatrixSpec ProjectionMatrix(int w, int h, double fu, double fv, double u0, double v0, double zNear, double zFar ) { return ProjectionMatrixRUB_BottomLeft(w,h,fu,fv,u0,v0,zNear,zFar); } OpenGlMatrixSpec ProjectionMatrixOrthographic(double t, double b, double l, double r, double n, double f ) { OpenGlMatrixSpec P; P.type = GlProjectionStack; std::fill_n(P.m,4*4,0); P.m[0] = 2/(r-l); P.m[1] = 0; P.m[2] = 0; P.m[3] = 0; P.m[4] = 0; P.m[5] = 2/(t-b); P.m[6] = 0; P.m[7] = 0; P.m[8] = 0; P.m[9] = 0; P.m[10] = -2/(f-n); P.m[11] = 0; P.m[12] = -(r+l)/(r-l); P.m[13] = -(t+b)/(t-b); P.m[14] = -(f+n)/(f-n); P.m[15] = 1; return P; } // Camera Axis: // X - Right, Y - Up, Z - Back // Image Origin: // Bottom Left // Caution: Principal point defined with respect to image origin (0,0) at // top left of top-left pixel (not center, and in different frame // of reference to projection function image) OpenGlMatrixSpec ProjectionMatrixRUB_BottomLeft(int w, int h, double fu, double fv, double u0, double v0, double zNear, double zFar ) { // http://www.songho.ca/opengl/gl_projectionmatrix.html const double L = +(u0) * zNear / -fu; const double T = +(v0) * zNear / fv; const double R = -(w-u0) * zNear / -fu; const double B = -(h-v0) * zNear / fv; OpenGlMatrixSpec P; P.type = GlProjectionStack; std::fill_n(P.m,4*4,0); P.m[0*4+0] = 2 * zNear / (R-L); P.m[1*4+1] = 2 * zNear / (T-B); P.m[2*4+2] = -(zFar +zNear) / (zFar - zNear); P.m[2*4+0] = (R+L)/(R-L); P.m[2*4+1] = (T+B)/(T-B); P.m[2*4+3] = -1.0; P.m[3*4+2] = -(2*zFar*zNear)/(zFar-zNear); return P; } // Camera Axis: // X - Right, Y - Down, Z - Forward // Image Origin: // Top Left // Pricipal point specified with image origin (0,0) at top left of top-left pixel (not center) OpenGlMatrixSpec ProjectionMatrixRDF_TopLeft(int w, int h, double fu, double fv, double u0, double v0, double zNear, double zFar ) { // http://www.songho.ca/opengl/gl_projectionmatrix.html const double L = -(u0) * zNear / fu; const double R = +(w-u0) * zNear / fu; const double T = -(v0) * zNear / fv; const double B = +(h-v0) * zNear / fv; OpenGlMatrixSpec P; P.type = GlProjectionStack; std::fill_n(P.m,4*4,0); P.m[0*4+0] = 2 * zNear / (R-L); P.m[1*4+1] = 2 * zNear / (T-B); P.m[2*4+0] = (R+L)/(L-R); P.m[2*4+1] = (T+B)/(B-T); P.m[2*4+2] = (zFar +zNear) / (zFar - zNear); P.m[2*4+3] = 1.0; P.m[3*4+2] = (2*zFar*zNear)/(zNear - zFar); return P; } // Camera Axis: // X - Right, Y - Down, Z - Forward // Image Origin: // Bottom Left // Pricipal point specified with image origin (0,0) at top left of top-left pixel (not center) OpenGlMatrixSpec ProjectionMatrixRDF_BottomLeft(int w, int h, double fu, double fv, double u0, double v0, double zNear, double zFar ) { // http://www.songho.ca/opengl/gl_projectionmatrix.html const double L = -(u0) * zNear / fu; const double R = +(w-u0) * zNear / fu; const double B = -(v0) * zNear / fv; const double T = +(h-v0) * zNear / fv; OpenGlMatrixSpec P; P.type = GlProjectionStack; std::fill_n(P.m,4*4,0); P.m[0*4+0] = 2 * zNear / (R-L); P.m[1*4+1] = 2 * zNear / (T-B); P.m[2*4+0] = (R+L)/(L-R); P.m[2*4+1] = (T+B)/(B-T); P.m[2*4+2] = (zFar +zNear) / (zFar - zNear); P.m[2*4+3] = 1.0; P.m[3*4+2] = (2*zFar*zNear)/(zNear - zFar); return P; } OpenGlMatrix ModelViewLookAt(double ex, double ey, double ez, double lx, double ly, double lz, double ux, double uy, double uz) { OpenGlMatrix mat; GLdouble* m = mat.m; const double u_o[3] = {ux,uy,uz}; GLdouble x[3], y[3]; GLdouble z[] = {ex - lx, ey - ly, ez - lz}; Normalise<3>(z); CrossProduct(x,u_o,z); CrossProduct(y,z,x); Normalise<3>(x); Normalise<3>(y); #define M(row,col) m[col*4+row] M(0,0) = x[0]; M(0,1) = x[1]; M(0,2) = x[2]; M(1,0) = y[0]; M(1,1) = y[1]; M(1,2) = y[2]; M(2,0) = z[0]; M(2,1) = z[1]; M(2,2) = z[2]; M(3,0) = 0.0; M(3,1) = 0.0; M(3,2) = 0.0; M(0,3) = -(M(0,0)*ex + M(0,1)*ey + M(0,2)*ez); M(1,3) = -(M(1,0)*ex + M(1,1)*ey + M(1,2)*ez); M(2,3) = -(M(2,0)*ex + M(2,1)*ey + M(2,2)*ez); M(3,3) = 1.0; #undef M return mat; } OpenGlMatrix ModelViewLookAt(double ex, double ey, double ez, double lx, double ly, double lz, AxisDirection up) { const double* u = AxisDirectionVector[up]; return ModelViewLookAt(ex,ey,ez,lx,ly,lz,u[0],u[1],u[2]); } OpenGlMatrix IdentityMatrix() { OpenGlMatrix P; std::fill_n(P.m,4*4,0); for( int i=0; i<4; ++i ) P.m[i*4+i] = 1; return P; } OpenGlMatrixSpec IdentityMatrix(OpenGlStack type) { OpenGlMatrixSpec P; P.type = type; std::fill_n(P.m,4*4,0); for( int i=0; i<4; ++i ) P.m[i*4+i] = 1; return P; } OpenGlMatrixSpec negIdentityMatrix(OpenGlStack type) { OpenGlMatrixSpec P; P.type = type; std::fill_n(P.m,4*4,0); for( int i=0; i<4; ++i ) P.m[i*4+i] = -1; P.m[3*4+3] =1; return P; } void DrawTextureToViewport(GLuint texid) { OpenGlRenderState::ApplyIdentity(); glBindTexture(GL_TEXTURE_2D, texid); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2d(-1,-1); glTexCoord2f(1, 0); glVertex2d(1,-1); glTexCoord2f(1, 1); glVertex2d(1,1); glTexCoord2f(0, 1); glVertex2d(-1,1); glEnd(); glDisable(GL_TEXTURE_2D); } }
26.535322
152
0.588682
[ "render", "object", "vector" ]
e6545afe8678e42ac757503b6b3b2b190ed03bfb
12,972
cc
C++
util/CoordAxes.cc
erikleitch/cpputil
6dbd4bdbaaa60d911d166b68fdad6af6afd04963
[ "MIT" ]
1
2018-11-01T05:15:31.000Z
2018-11-01T05:15:31.000Z
util/CoordAxes.cc
erikleitch/cpputil
6dbd4bdbaaa60d911d166b68fdad6af6afd04963
[ "MIT" ]
null
null
null
util/CoordAxes.cc
erikleitch/cpputil
6dbd4bdbaaa60d911d166b68fdad6af6afd04963
[ "MIT" ]
2
2017-05-02T19:35:55.000Z
2018-03-07T00:54:51.000Z
#include "gcp/util/CoordAxes.h" #include "gcp/util/Debug.h" #include "gcp/util/Exception.h" #include "gcp/util/LogStream.h" using namespace gcp::util; using namespace std; /**....................................................................... * Private initialization method */ void CoordAxes::privateConstructor() { // Default to 1-dimensions nEl_.resize(1); } /**....................................................................... * Constructor. */ CoordAxes::CoordAxes() { privateConstructor(); setAxis(0, 1); // Set the default axis to have 1 element } /**....................................................................... * Constructor. */ CoordAxes::CoordAxes(unsigned nel0) { privateConstructor(); setAxis(0, nel0); } /**....................................................................... * Constructor. */ CoordAxes::CoordAxes(unsigned nel0, unsigned nel1) { privateConstructor(); setAxis(0, nel0); setAxis(1, nel1); } /**....................................................................... * Constructor. */ CoordAxes::CoordAxes(unsigned nel0, unsigned nel1, unsigned nel2) { privateConstructor(); setAxis(0, nel0); setAxis(1, nel1); setAxis(2, nel2); } /**....................................................................... * Copy constructor */ CoordAxes::CoordAxes(CoordAxes* regAxes) { *this = *regAxes; } /**....................................................................... * Reset this object */ void CoordAxes::reset() { nEl_.resize(0); } /**....................................................................... * Method for setting arbitrary axes */ void CoordAxes::setAxis(unsigned iAxis, unsigned nEl) { // Do nothing if the number of elements for this axis is zero if(nEl > 0) { // If the requested axis is greater than the current number of axes, // resize the array unsigned nAxisOld = nEl_.size(); if((signed)iAxis > (signed)(nEl_.size()-1)) { nEl_.resize(iAxis+1); // Quietly set any axes which weren't specified to unity size for(unsigned iAxis=nAxisOld; iAxis < nEl_.size(); iAxis++) nEl_[iAxis] = 1; } // And set the number of elements for this axis nEl_[iAxis] = nEl; } } /**....................................................................... * Destructor. */ CoordAxes::~CoordAxes() {} /**....................................................................... * Return the number of axes in this register */ unsigned int CoordAxes::nAxis() { return nEl_.size(); } /**....................................................................... * Return the number of elements in this register */ unsigned int CoordAxes::nEl(int axis) { unsigned nEl; if(axis < 0) { nEl=nEl_[0]; for(unsigned i=1; i < nEl_.size(); i++) nEl *= nEl_[i]; } else { if(axis > nEl_.size()-1) { return 0; } nEl = nEl_[axis]; } return nEl; } /**....................................................................... * Return the element offset of the specified coordinate from the * start of the register array */ unsigned int CoordAxes::elementOffsetOf(Coord& coord) { // Check validity of this coordinate for this axis description checkValidityOf(coord); // Else compute the element offset of the requested coordinate unsigned offset = coord.getIndex(0); for(unsigned iAxis=1; iAxis < nAxis(); iAxis++) offset = offset * nEl_[iAxis] + (coord.nAxis() > iAxis ? coord.getIndex(iAxis) : 0); return offset; } /**....................................................................... * Return the element offset of the specified coordinate from the * start of the register array */ unsigned int CoordAxes::elementOffsetOf(Coord* coord) { if(coord==0) return 0; // If coord is NULL, we don't want to pass it on directly Coord refCoord(coord); return elementOffsetOf(refCoord); } /**....................................................................... * Check the validity of a coordinate for this axis descriptor */ void CoordAxes::checkValidityOf(Coord& coord) { if(coord.nAxis() > nAxis()) { ThrowError("Coordinate " << coord << " has invalid number of axes (" << coord.nAxis() << ") for this axis description: " << (*this)); } for(unsigned iAxis=0; iAxis < coord.nAxis(); iAxis++) { unsigned index = coord.getIndex(iAxis); if(index > nEl_[iAxis]-1) { ThrowError("Index " << index << " is out of range for axis " << iAxis); } } } /**....................................................................... * Return a vector of byte ranges associated with the * specified input coordinate range. */ std::vector<Range<unsigned> > CoordAxes::getRanges(CoordRange coordRange) { // Check if the range contains valid data if(!rangeIsValid(coordRange)) ThrowSimpleError("Range " << coordRange << " does not contain valid data"); // The range will be considered consistent with this axis // description even if indices for fewer than nAxis() are specified. // We assume that an axis in the range for which indices have not // been specified should default to the whole range for that axis. // fillRange() will fill out any missing dimensions in the range // object with the full range. Note that since coordRange is copied // on input to this method, the input argument is not modified on // return to the caller. fillRange(coordRange); // Declare the vector of 1-D ranges we will return std::vector<Range<unsigned> > ranges; // Get the start and stop coordinates in the range object Coord start = coordRange.startCoord(); Coord stop = coordRange.stopCoord(); // If the range is to be interpreted as a contiguous range, only one // range should be returned, containing the element offset of the // start and stop coordinates if(coordRange.isContiguous()) { Range<unsigned> range(elementOffsetOf(start), elementOffsetOf(stop)); ranges.push_back(range); // Else the range may be a list of non-contiguous element ranges } else { computeRanges(ranges, 0, start, stop, 0); } return ranges; } /**....................................................................... * Return a vector of byte ranges associated with the * specified input coordinate range. */ std::vector<Range<unsigned> > CoordAxes::getRanges(CoordRange* coordRange) { CoordRange tmpRange(coordRange); return getRanges(tmpRange); } /**....................................................................... * Recursive method for computing multidimensional ranges. */ void CoordAxes::computeRanges(std::vector<Range<unsigned> >& ranges, unsigned iAxis, Coord& start, Coord& stop, unsigned offset) { unsigned iStart = start.getIndex(iAxis); unsigned iStop = stop.getIndex(iAxis); unsigned index; // If this is the fastest changing (highest) dimension, add the new // range. if(iAxis==nAxis()-1) { addNewRange(ranges, offset + iStart, offset + iStop); } else { for(unsigned i=iStart; i <= iStop; i++) computeRanges(ranges, iAxis+1, start, stop, (offset + i) * nEl(iAxis+1)); } } /**....................................................................... * Add a new range */ void CoordAxes::addNewRange(std::vector<Range<unsigned> >& ranges, unsigned startIndex, unsigned stopIndex) { // If the vector is already populated, see if the current range can // be appended to the last one if(ranges.size() > 0) { // If the current start index is the next index, just expand the // current range Range<unsigned>* range = &(ranges.at(ranges.size()-1)); if(range->stop()+1 == startIndex) range->setStop(stopIndex); // Else create a new one else { Range<unsigned> range(startIndex, stopIndex); ranges.push_back(range); } // Else create a new one } else { Range<unsigned> range(startIndex, stopIndex); ranges.push_back(range); } } /**....................................................................... * Find a vector element matching the stop index */ std::vector<Range<unsigned> >::iterator CoordAxes::findStopIndex(std::vector<Range<unsigned> >& ranges, unsigned index) { std::vector<Range<unsigned> >::iterator range; for(range=ranges.begin(); range < ranges.end(); range++) { cout << ((*range).stop()+1) << ", " << index << endl; if((*range).stop()+1 == index) break; } return range; } /**....................................................................... * Check if a coordinate range is consistent with this axis * specifier */ bool CoordAxes::rangeIsValid(CoordRange& range) { // First check if the range contains valid data if(!range.isValid()) { ReportError("Range is not valid"); return false; } // Now check the number of axes in the range. For now, we will // consider this consistent if the number of axes specified in the // range are less than or equal to the number of axes in this // object. if(range.nAxis() > nAxis()) { ReportError("Number of axes in the range exceeds that in the axis description"); return false; } // Now check that none of the ranges exceeds our axis dimension for(unsigned iAxis=0; iAxis < range.nAxis(); iAxis++) { if(range.startIndex(iAxis) > nEl(iAxis)-1) { ReportError("Start index (" << range.startIndex(iAxis) << ") for axis: " << iAxis << " exceeds the maximum " << "(" << (nEl(iAxis)-1) << ")" << " for this axis"); return false; } if(range.stopIndex(iAxis) > nEl(iAxis)-1) { ReportError("Stop index (" << range.stopIndex(iAxis) << ") for axis: " << iAxis << " exceeds the maximum " << "(" << (nEl(iAxis)-1) << ")" << " for this axis"); return false; } } // The range is consistent with our axis specifications return true; } /**....................................................................... * Check if a coordinate range is consistent with this axis * specifier */ bool CoordAxes::rangeIsValid(CoordRange* range) { if(range == 0) return true; else return rangeIsValid(*range); } /**....................................................................... * Print a range to stdout */ ostream& gcp::util::operator<<(std::ostream& os, CoordAxes axes) { for(unsigned i=0; i < axes.nAxis(); i++) { os << "[0"; if(axes.nEl(i) > 1) os << "-" << axes.nEl(i)-1; os << "]"; } return os; } /**....................................................................... * Given an element offset, return the coordinate corresponding to it. */ Coord CoordAxes::coordOf(unsigned iEl) { Coord coord; // To convert from element offset to coordinate in each axis, we // need the number of fastest-changing axis elements per element of // each axis. Cache these values up front: std::vector<unsigned> nel; nel.resize(nAxis()); unsigned nelPerElement = 1; for(int iAxis=nAxis()-1; iAxis >= 0; iAxis--) { nel[iAxis] = nelPerElement; nelPerElement *= nEl(iAxis); } // Now loop through, computing the index for each dimension for(int iAxis=0; iAxis < nAxis(); iAxis++) { coord.setIndex(iAxis, iEl/nel[iAxis]); iEl = iEl % nel[iAxis]; } return coord; } /**....................................................................... * A range will be considered consistent with this axis description * even if indices for fewer than nAxis() are specified. We assume * that an axis in the range for which indices have not been * specified should default to the whole range for that axis. * * This method fills out any missing dimensions in the range object * with the full range for that axis. */ void CoordAxes::fillRange(CoordRange& range) { for(unsigned iAxis=range.nAxis(); iAxis < nAxis(); iAxis++) { range.setStartIndex(iAxis, 0); range.setStopIndex(iAxis, nEl(iAxis)-1); } } /**....................................................................... * Return the total number of elements specified in a range object */ unsigned CoordAxes::nEl(CoordRange& coordRange) { return nEl(&coordRange); } /**....................................................................... * Return the total number of elements specified in a range object */ unsigned CoordAxes::nEl(CoordRange* coordRange) { vector<Range<unsigned> > ranges = getRanges(coordRange); unsigned nEl=0; for(unsigned i=0; i < ranges.size(); i++) nEl += (ranges[i].stop() - ranges[i].start() + 1); return nEl; } /** * An operator for testing equality of two Axes */ bool CoordAxes::operator==(CoordAxes& axes) { if(axes.nAxis() != nAxis()) return false; else { for(unsigned iAxis=0; iAxis < nAxis(); iAxis++) if(axes.nEl(iAxis) != nEl(iAxis)) return false; } return true; }
26.419552
84
0.558434
[ "object", "vector" ]
e664a26dca301d82d6ca8b57212e80a3cd4a9f14
4,814
cpp
C++
src/controller/parkselector.cpp
bdmendes/feup-cal-parking
57e793d32a176c43c93bbf03a1b863bbe5b7a3e3
[ "MIT" ]
null
null
null
src/controller/parkselector.cpp
bdmendes/feup-cal-parking
57e793d32a176c43c93bbf03a1b863bbe5b7a3e3
[ "MIT" ]
null
null
null
src/controller/parkselector.cpp
bdmendes/feup-cal-parking
57e793d32a176c43c93bbf03a1b863bbe5b7a3e3
[ "MIT" ]
null
null
null
#include <stdexcept> #include "parkselector.h" #include "../algorithms/search.hpp" #include "../algorithms/shortestdistance.hpp" static std::vector<Node<MapPoint>*> candidateParks(const Graph<MapPoint>& graph, Node<MapPoint>* point, double maxDistance){ if (point->getElement().isPark()) return {}; std::vector<Node<MapPoint>*> parks; for (const auto& node: graph.getNodes()){ if (node->getElement().isPark() && node->getElement().euclideanDistance(point->getElement()) <= maxDistance){ std::vector<Node<MapPoint>*> targets = {graph.findNode(node->getElement())}; auto found = dfsFromNode(point, targets, graph); if (!found.empty()){ parks.push_back(node); } } } return parks; } static double parkEvaluation(Graph<MapPoint>& graph, Node<MapPoint>* point, Node<MapPoint>* park, Node<MapPoint>* sourceNode, Node<MapPoint>* endNode, float i, float j, float k, double maxEuclideanDistance){ if (!park->getElement().isPark()) { throw std::invalid_argument("Node is not a park"); } if (i+j+k < 0.99 || i+j+k > 1.01){ throw std::invalid_argument("Factors must add up to 1"); } auto parkFields = park->getElement().getParkFields(); double priceEval = parkFields.fixedPrice + (((double)parkFields.capacity-parkFields.freeSpots)/parkFields.capacity)*parkFields.capacityTaxFactor; if (priceEval > 10) priceEval = 10; // relax price evaluation priceEval /= 10; AStar(park->getElement(), graph, endNode->getElement()); double distanceToDestiny = distance(getAStarPath(graph, park->getElement(), endNode->getElement())); auto fromSourceDist = sourceNode->getElement().euclideanDistance(endNode->getElement()); if (distanceToDestiny > 10*fromSourceDist) distanceToDestiny = 10*fromSourceDist; distanceToDestiny /= 10*fromSourceDist; AStar(point->getElement(), graph, park->getElement()); double walkDistance = distance(getAStarPath(graph, point->getElement(), park->getElement())); if (walkDistance > 10*maxEuclideanDistance) walkDistance = 10*maxEuclideanDistance; walkDistance /= 10*maxEuclideanDistance; return i*priceEval + j*walkDistance + k*distanceToDestiny; } std::vector<Node<MapPoint>*> getPathAfterParkReplacement(Graph<MapPoint>& graph, const std::vector<Node<MapPoint>*>& stopPoints, Node<MapPoint>* sourceNode, Node<MapPoint>* endNode, std::vector<bool> shallPark, float iFactor, float jFactor, float kFactor, double maxEuclideanDistance){ if (stopPoints.size() != shallPark.size()){ throw std::invalid_argument("Whether to stop on each park must be specified"); } auto finalPath = stopPoints; for (int i = 0; i < stopPoints.size(); i++){ if (!shallPark.at(i)) continue; auto parks = candidateParks(graph, stopPoints.at(i), maxEuclideanDistance); if (parks.empty()) continue; Node<MapPoint>* bestPark = parks.at(0); double bestEval = parkEvaluation(graph, stopPoints.at(i), bestPark, sourceNode, endNode, iFactor, jFactor, kFactor, maxEuclideanDistance); for (int j = 1; j < parks.size(); j++){ double eval = parkEvaluation(graph, stopPoints.at(i), parks.at(j), sourceNode, endNode, iFactor, jFactor, kFactor, maxEuclideanDistance); if (eval < bestEval){ bestEval = eval; bestPark = parks.at(i); } } finalPath.at(i) = bestPark; } return finalPath; } std::vector<std::vector<Node<MapPoint>*>> getWalkPaths(Graph<MapPoint>& graph, const std::vector<Node<MapPoint>*>& stopPoints, const std::vector<Node<MapPoint>*>& actualStops){ if (stopPoints.size() != actualStops.size()){ throw std::invalid_argument("Stopping vector size does not make sense"); } std::vector<std::vector<Node<MapPoint>*>> paths; paths.resize(stopPoints.size(), {}); for (int i = 0; i < stopPoints.size(); i++){ if (stopPoints.at(i)->getElement() == actualStops.at(i)->getElement() || stopPoints.at(i)->getElement().isPark()){ continue; } else { dijkstra(stopPoints.at(i)->getElement(), graph); paths.at(i) = getDijkstraPath(graph, stopPoints.at(i)->getElement(), actualStops.at(i)->getElement()); } } for (int i = 0; i < paths.size(); i++){ if (paths.at(i).empty()) continue; if (paths.at(i).at(0)->getElement() != stopPoints.at(i)->getElement() || paths.at(i).at(paths.at(i).size()-1)->getElement() != actualStops.at(i)->getElement()){ throw std::logic_error("Error calculating walk paths"); } } return paths; }
48.626263
152
0.636477
[ "vector" ]
e670c9481b2f37d694d27a5aab4a16edfb9c3e90
1,203
cpp
C++
aws-cpp-sdk-medialive/source/model/FrameCaptureCdnSettings.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-medialive/source/model/FrameCaptureCdnSettings.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-medialive/source/model/FrameCaptureCdnSettings.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/medialive/model/FrameCaptureCdnSettings.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace MediaLive { namespace Model { FrameCaptureCdnSettings::FrameCaptureCdnSettings() : m_frameCaptureS3SettingsHasBeenSet(false) { } FrameCaptureCdnSettings::FrameCaptureCdnSettings(JsonView jsonValue) : m_frameCaptureS3SettingsHasBeenSet(false) { *this = jsonValue; } FrameCaptureCdnSettings& FrameCaptureCdnSettings::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("frameCaptureS3Settings")) { m_frameCaptureS3Settings = jsonValue.GetObject("frameCaptureS3Settings"); m_frameCaptureS3SettingsHasBeenSet = true; } return *this; } JsonValue FrameCaptureCdnSettings::Jsonize() const { JsonValue payload; if(m_frameCaptureS3SettingsHasBeenSet) { payload.WithObject("frameCaptureS3Settings", m_frameCaptureS3Settings.Jsonize()); } return payload; } } // namespace Model } // namespace MediaLive } // namespace Aws
20.05
84
0.76808
[ "model" ]
e6794406ea55c56778d2f17682dada8abdd35e63
1,198
cpp
C++
27. LeetCode Problems/valid_sudoku.cpp
shivank911/Hacktoberfest2021-DSA
ac2d3d30c34b1a42003b6bd4dec13249e4e58458
[ "MIT" ]
1
2021-10-06T10:29:51.000Z
2021-10-06T10:29:51.000Z
27. LeetCode Problems/valid_sudoku.cpp
shivank911/Hacktoberfest2021-DSA
ac2d3d30c34b1a42003b6bd4dec13249e4e58458
[ "MIT" ]
null
null
null
27. LeetCode Problems/valid_sudoku.cpp
shivank911/Hacktoberfest2021-DSA
ac2d3d30c34b1a42003b6bd4dec13249e4e58458
[ "MIT" ]
1
2021-10-04T00:11:49.000Z
2021-10-04T00:11:49.000Z
//Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: //Points to be kept in mind: //Each row must contain the digits 1-9 without repetition. //Each column must contain the digits 1-9 without repetition. //Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { unordered_set<string> st; for(int i = 0; i<9; i++) { for(int j = 0; j<9; j++) { if(board[i][j] != '.') { string row = "r"+ to_string(i)+string(1,board[i][j]); string col = "c"+ to_string(j)+string(1,board[i][j]); string box = "b"+to_string(i/3)+ to_string(j/3)+string(1,board[i][j]); if(st.find(row)!=st.end() || st.find(col)!=st.end()|| st.find(box)!=st.end()) return false; st.insert(row); st.insert(col); st.insert(box); } } } return true; } };
33.277778
122
0.504174
[ "vector" ]
e67b50e401fcb582fdb64346efaf050072117944
381
cpp
C++
DigDug/FireBehaviour.cpp
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
2
2021-03-19T13:29:36.000Z
2021-04-13T23:37:10.000Z
DigDug/FireBehaviour.cpp
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
null
null
null
DigDug/FireBehaviour.cpp
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
null
null
null
#include "pch.h" #include "PumpBehaviour.h" #include "TaizoBehaviour.h" void kd::PumpBehaviour::Initialize() { /*void (*callback)(GameObject*) = &kd::PumpBehaviour::TriggerEnter; GetGameObject()->SetCollisionCallback(callback);*/ } void kd::PumpBehaviour::Update() {} void kd::PumpBehaviour::Render() const {} //void kd::PumpBehaviour::TriggerEnter(GameObject* other) //{ //}
22.411765
68
0.71916
[ "render" ]
e67d0597a4dc6b4ddaec2eed0fa1c42cc3a14b46
2,093
cpp
C++
epublib/src/main/jni/NativeFormats/zlibrary/text/src/fonts/FontManager.cpp
zhupeipei/NovelReader
8eed755ed6da162d7f52fdf23d1bad8c63b01b10
[ "MIT" ]
2
2021-07-30T02:36:46.000Z
2021-09-04T23:04:43.000Z
epublib/src/main/jni/NativeFormats/zlibrary/text/src/fonts/FontManager.cpp
zhupeipei/NovelReader
8eed755ed6da162d7f52fdf23d1bad8c63b01b10
[ "MIT" ]
null
null
null
epublib/src/main/jni/NativeFormats/zlibrary/text/src/fonts/FontManager.cpp
zhupeipei/NovelReader
8eed755ed6da162d7f52fdf23d1bad8c63b01b10
[ "MIT" ]
2
2021-06-03T08:59:58.000Z
2021-07-30T04:42:53.000Z
/* * Copyright (C) 2004-2015 FBReader.ORG Limited <contact@fbreader.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include <ZLStringUtil.h> #include "FontManager.h" std::string FontManager::put(const std::string &family, shared_ptr<FontEntry> entry) { shared_ptr<FontEntry> existing = myEntries[family]; if (existing.isNull() || *existing == *entry) { myEntries[family] = entry; return family; } for (std::map<std::string,shared_ptr<FontEntry> >::const_iterator it = myEntries.begin(); it != myEntries.end(); ++it) { if (*it->second == *entry) { return it->first; } } for (int i = 1; i < 1000; ++i) { std::string indexed = family + "#"; ZLStringUtil::appendNumber(indexed, i); if (myEntries[indexed].isNull()) { myEntries[indexed] = entry; return indexed; } } return std::string(); } int FontManager::familyListIndex(const std::vector<std::string> &familyList) { std::vector<std::vector<std::string> >::const_iterator it = std::find(myFamilyLists.begin(), myFamilyLists.end(), familyList); if (it == myFamilyLists.end()) { myFamilyLists.push_back(familyList); return myFamilyLists.size() - 1; } else { return it - myFamilyLists.begin(); } } const std::map<std::string,shared_ptr<FontEntry> > &FontManager::entries() const { return myEntries; } const std::vector<std::vector<std::string> > &FontManager::familyLists() const { return myFamilyLists; }
31.238806
121
0.70473
[ "vector" ]
e680475f0630b21cc04e9f55fff525e63aad446e
6,408
cc
C++
tools/re2c/src/codegen/go_construct.cc
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
5
2021-07-31T03:34:09.000Z
2021-08-31T21:43:50.000Z
tools/re2c/src/codegen/go_construct.cc
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
4
2021-09-02T00:05:17.000Z
2021-09-07T14:56:12.000Z
tools/re2c/src/codegen/go_construct.cc
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
1
2021-09-28T19:03:39.000Z
2021-09-28T19:03:39.000Z
#include <stddef.h> #include "src/util/c99_stdint.h" #include <string> #include <utility> #include <vector> #include "src/codegen/bitmap.h" #include "src/codegen/go.h" #include "src/conf/opt.h" #include "src/globals.h" #include "src/ir/adfa/adfa.h" #include "src/util/allocate.h" namespace re2c { static uint32_t unmap (Span * new_span, const Span * old_span, uint32_t old_nspans, const State * x); Cases::Cases (const Span * span, uint32_t span_size) : def (span_size == 0 ? NULL : span[span_size - 1].to) , cases (new Case[span_size]) , cases_size (0) { for (uint32_t i = 0, lb = 0; i < span_size; ++ i) { add (lb, span[i].ub, span[i].to); lb = span[i].ub; } } void Cases::add (uint32_t lb, uint32_t ub, State * to) { for (uint32_t i = 0; i < cases_size; ++i) { if (cases[i].to == to) { cases[i].ranges.push_back (std::make_pair (lb, ub)); return; } } cases[cases_size].ranges.push_back (std::make_pair (lb, ub)); cases[cases_size].to = to; ++cases_size; } Cond::Cond (const std::string & cmp, uint32_t val) : compare (cmp) , value (val) {} Binary::Binary (const Span * s, uint32_t n, const State * next) : cond (NULL) , thn (NULL) , els (NULL) { const uint32_t l = n / 2; const uint32_t h = n - l; cond = new Cond ("<=", s[l - 1].ub - 1); thn = new If (l > 4 ? If::BINARY : If::LINEAR, &s[0], l, next); els = new If (h > 4 ? If::BINARY : If::LINEAR, &s[l], h, next); } Linear::Linear (const Span * s, uint32_t n, const State * next) : branches () { for (;;) { const State *bg = s[0].to; while (n >= 3 && s[2].to == bg && (s[1].ub - s[0].ub) == 1) { if (s[1].to == next && n == 3) { branches.push_back (std::make_pair (new Cond ("!=", s[0].ub), bg)); return ; } else { branches.push_back (std::make_pair (new Cond ("==", s[0].ub), s[1].to)); } n -= 2; s += 2; } if (n == 1) { if (next == NULL || s[0].to != next) { branches.push_back (std::make_pair (static_cast<const Cond *> (NULL), s[0].to)); } return; } else if (n == 2 && bg == next) { branches.push_back (std::make_pair (new Cond (">=", s[0].ub), s[1].to)); return; } else { branches.push_back (std::make_pair (new Cond ("<=", s[0].ub - 1), bg)); n -= 1; s += 1; } } } If::If (type_t t, const Span * sp, uint32_t nsp, const State * next) : type (t) , info () { switch (type) { case BINARY: info.binary = new Binary (sp, nsp, next); break; case LINEAR: info.linear = new Linear (sp, nsp, next); break; } } SwitchIf::SwitchIf (const Span * sp, uint32_t nsp, const State * next) : type (IF) , info () { if ((!opts->sFlag && nsp > 2) || (nsp > 8 && (sp[nsp - 2].ub - sp[0].ub <= 3 * (nsp - 2)))) { type = SWITCH; info.cases = new Cases (sp, nsp); } else if (nsp > 5) { info.ifs = new If (If::BINARY, sp, nsp, next); } else { info.ifs = new If (If::LINEAR, sp, nsp, next); } } GoBitmap::GoBitmap (const Span * span, uint32_t nSpans, const Span * hspan, uint32_t hSpans, const BitMap * bm, const State * bm_state, const State * next) : bitmap (bm) , bitmap_state (bm_state) , hgo (NULL) , lgo (NULL) { Span * bspan = allocate<Span> (nSpans); uint32_t bSpans = unmap (bspan, span, nSpans, bm_state); lgo = bSpans == 0 ? NULL : new SwitchIf (bspan, bSpans, next); // if there are any low spans, then next state for high spans // must be NULL to trigger explicit goto generation in linear 'if' hgo = hSpans == 0 ? NULL : new SwitchIf (hspan, hSpans, lgo ? NULL : next); operator delete (bspan); } const uint32_t CpgotoTable::TABLE_SIZE = 0x100; CpgotoTable::CpgotoTable (const Span * span, uint32_t nSpans) : table (new const State * [TABLE_SIZE]) { uint32_t c = 0; for (uint32_t i = 0; i < nSpans; ++i) { for(; c < span[i].ub && c < TABLE_SIZE; ++c) { table[c] = span[i].to; } } } Cpgoto::Cpgoto (const Span * span, uint32_t nSpans, const Span * hspan, uint32_t hSpans, const State * next) : hgo (hSpans == 0 ? NULL : new SwitchIf (hspan, hSpans, next)) , table (new CpgotoTable (span, nSpans)) {} Dot::Dot (const Span * sp, uint32_t nsp, const State * s) : from (s) , cases (new Cases (sp, nsp)) {} Go::Go () : nSpans (0) , span (NULL) , type (EMPTY) , info () {} void Go::init (const State * from) { if (nSpans == 0) { return; } // initialize high (wide) spans uint32_t hSpans = 0; const Span * hspan = NULL; for (uint32_t i = 0; i < nSpans; ++i) { if (span[i].ub > 0x100) { hspan = &span[i]; hSpans = nSpans - i; break; } } // initialize bitmaps uint32_t nBitmaps = 0; const BitMap * bitmap = NULL; const State * bitmap_state = NULL; for (uint32_t i = 0; i < nSpans; ++i) { if (span[i].to->isBase) { const BitMap *b = BitMap::find (span[i].to); if (b && matches(b->go->span, b->go->nSpans, b->on, span, nSpans, span[i].to)) { if (bitmap == NULL) { bitmap = b; bitmap_state = span[i].to; } nBitmaps++; } } } const uint32_t dSpans = nSpans - hSpans - nBitmaps; if (opts->target == opt_t::DOT) { type = DOT; info.dot = new Dot (span, nSpans, from); } else if (opts->gFlag && (dSpans >= opts->cGotoThreshold)) { type = CPGOTO; info.cpgoto = new Cpgoto (span, nSpans, hspan, hSpans, from->next); } else if (opts->bFlag && (nBitmaps > 0)) { type = BITMAP; info.bitmap = new GoBitmap (span, nSpans, hspan, hSpans, bitmap, bitmap_state, from->next); bUsedYYBitmap = true; } else { type = SWITCH_IF; info.switchif = new SwitchIf (span, nSpans, from->next); } } /* * Find all spans, that map to the given state. For each of them, * find upper adjacent span, that maps to another state (if such * span exists, otherwize try lower one). * If input contains single span that maps to the given state, * then output contains 0 spans. */ uint32_t unmap (Span * new_span, const Span * old_span, uint32_t old_nspans, const State * x) { uint32_t new_nspans = 0; for (uint32_t i = 0; i < old_nspans; ++i) { if (old_span[i].to != x) { if (new_nspans > 0 && new_span[new_nspans - 1].to == old_span[i].to) new_span[new_nspans - 1].ub = old_span[i].ub; else { new_span[new_nspans].to = old_span[i].to; new_span[new_nspans].ub = old_span[i].ub; ++new_nspans; } } } if (new_nspans > 0) new_span[new_nspans - 1].ub = old_span[old_nspans - 1].ub; return new_nspans; } } // namespace re2c
22.484211
155
0.597378
[ "vector" ]
e680aff778fabd34a098ff6375d081422f569741
617
cpp
C++
solutions/1443.minimum-time-to-collect-all-apples-in-a-tree.378293872.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/1443.minimum-time-to-collect-all-apples-in-a-tree.378293872.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/1443.minimum-time-to-collect-all-apples-in-a-tree.378293872.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int minTime(int n, vector<vector<int>> &edges, vector<bool> &hasApple) { int ans = 0; vector<vector<int>> g(n); for (auto &v : edges) { g[v[0]].push_back(v[1]); g[v[1]].push_back(v[0]); } dfs(g, hasApple, ans, 0); return ans * 2; } bool dfs(vector<vector<int>> &g, vector<bool> &hasApple, int &ans, int i, int parent = -1) { bool apple = hasApple[i]; for (int j : g[i]) { if (j == parent) continue; if (dfs(g, hasApple, ans, j, i)) { ans++; apple = true; } } return apple; } };
22.035714
75
0.50081
[ "vector" ]
e6824e4ea2d5de301260edb29bcba77c89606dfb
3,668
cc
C++
yundun-ds/src/model/DescribeFlowTotalCountResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
yundun-ds/src/model/DescribeFlowTotalCountResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
yundun-ds/src/model/DescribeFlowTotalCountResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.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/yundun-ds/model/DescribeFlowTotalCountResult.h> #include <json/json.h> using namespace AlibabaCloud::Yundun_ds; using namespace AlibabaCloud::Yundun_ds::Model; DescribeFlowTotalCountResult::DescribeFlowTotalCountResult() : ServiceResult() {} DescribeFlowTotalCountResult::DescribeFlowTotalCountResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeFlowTotalCountResult::~DescribeFlowTotalCountResult() {} void DescribeFlowTotalCountResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto flowCountNode = value["FlowCount"]; auto dataHubNode = flowCountNode["DataHub"]; auto projectNode = dataHubNode["Project"]; if(!projectNode["TotalCount"].isNull()) flowCount_.dataHub.project.totalCount = std::stol(projectNode["TotalCount"].asString()); if(!projectNode["LastCount"].isNull()) flowCount_.dataHub.project.lastCount = std::stol(projectNode["LastCount"].asString()); auto topicNode = dataHubNode["Topic"]; if(!topicNode["TotalCount"].isNull()) flowCount_.dataHub.topic.totalCount = std::stol(topicNode["TotalCount"].asString()); if(!topicNode["LastCount"].isNull()) flowCount_.dataHub.topic.lastCount = std::stol(topicNode["LastCount"].asString()); auto subscriptionNode = dataHubNode["Subscription"]; if(!subscriptionNode["TotalCount"].isNull()) flowCount_.dataHub.subscription.totalCount = std::stol(subscriptionNode["TotalCount"].asString()); if(!subscriptionNode["LastCount"].isNull()) flowCount_.dataHub.subscription.lastCount = std::stol(subscriptionNode["LastCount"].asString()); auto connectorNode = dataHubNode["Connector"]; if(!connectorNode["TotalCount"].isNull()) flowCount_.dataHub.connector.totalCount = std::stol(connectorNode["TotalCount"].asString()); if(!connectorNode["LastCount"].isNull()) flowCount_.dataHub.connector.lastCount = std::stol(connectorNode["LastCount"].asString()); auto cDPNode = flowCountNode["CDP"]; auto inputInstanceCountNode = cDPNode["InputInstanceCount"]; if(!inputInstanceCountNode["TotalCount"].isNull()) flowCount_.cDP.inputInstanceCount.totalCount = std::stol(inputInstanceCountNode["TotalCount"].asString()); auto inputRecordCountNode = cDPNode["InputRecordCount"]; if(!inputRecordCountNode["TotalCount"].isNull()) flowCount_.cDP.inputRecordCount.totalCount = std::stol(inputRecordCountNode["TotalCount"].asString()); auto outputInstanceCountNode = cDPNode["OutputInstanceCount"]; if(!outputInstanceCountNode["TotalCount"].isNull()) flowCount_.cDP.outputInstanceCount.totalCount = std::stol(outputInstanceCountNode["TotalCount"].asString()); auto outputRecordCountNode = cDPNode["OutputRecordCount"]; if(!outputRecordCountNode["TotalCount"].isNull()) flowCount_.cDP.outputRecordCount.totalCount = std::stol(outputRecordCountNode["TotalCount"].asString()); } DescribeFlowTotalCountResult::FlowCount DescribeFlowTotalCountResult::getFlowCount()const { return flowCount_; }
43.152941
110
0.772901
[ "model" ]
e6868daedc3e6a18271d96a5ef218e53b138093d
1,012
hpp
C++
include/Components/RectangleCollider.hpp
fgagamedev/voID
37cd56fe2878d036c36dafcf595e48ed85408d02
[ "MIT" ]
null
null
null
include/Components/RectangleCollider.hpp
fgagamedev/voID
37cd56fe2878d036c36dafcf595e48ed85408d02
[ "MIT" ]
null
null
null
include/Components/RectangleCollider.hpp
fgagamedev/voID
37cd56fe2878d036c36dafcf595e48ed85408d02
[ "MIT" ]
null
null
null
#ifndef __RECTANGLE_COLLIDER__ #define __RECTANGLE_COLLIDER__ #include "Engine/GameObject.hpp" #include "Components/Collider.hpp" #include "Math/Shapes.hpp" #include "Math/Vector.hpp" /** @file RectangleCollider.hpp @brief This class contains all attributes and methods that creates all collisions in-game. @copyright LGPL. MIT License. */ using namespace std; class RectangleCollider : public Collider { public: RectangleCollider(GameObject *owner, Vector offset, float width, float height, int layer); void FixedComponentUpdate() override; Vector GetRectanglePoint() { return Vector(m_shape.x, m_shape.y); }; float GetWidth() { return m_shape.width; }; float GetHeight() { return m_shape.height; }; virtual string GetComponentName() override { return "RectangleCollider"; }; GameObject *m_owner; private: Rectangle m_shape; Vector m_offset; }; #endif // __RECTANGLE_COLLIDER__
21.083333
94
0.683794
[ "vector" ]
e6968f4c38993f7255f5e6ab10fd72e829ec84f8
15,069
cpp
C++
Engine/Object.cpp
CrossProd/Aardbei_SouthsideExploration
cead610de95fb87b5aab60b4ec834a8c814a3c12
[ "MIT" ]
1
2018-11-20T03:50:35.000Z
2018-11-20T03:50:35.000Z
Engine/Object.cpp
rbruinier/Aardbei_SouthsideExploration
cead610de95fb87b5aab60b4ec834a8c814a3c12
[ "MIT" ]
null
null
null
Engine/Object.cpp
rbruinier/Aardbei_SouthsideExploration
cead610de95fb87b5aab60b4ec834a8c814a3c12
[ "MIT" ]
null
null
null
/* Pyramid Engine - Object Class 2003, Robert Jan Bruinier (rob / aardbei) */ #include "Object.h" #include <math.h> #include "../System/VertexBuffer.h" #include "../System/IndexBuffer.h" #include "../System/VertexShader.h" #include "../System/PixelShader.h" #include "../System/Matrix.h" D3DVERTEXELEMENT9 OBJECT_VERTEX_DECLARATION[] = { {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, {0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0}, {0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0}, {0, 32, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1}, {1, 40, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0}, D3DDECL_END() }; extern Pyramid *pyramid; Object::Object() { vertexBuffer = NULL; indexBuffer = NULL; vertexBufferTangent = NULL; //vertexShader = NULL; //pixelShader = NULL; vertex = NULL; face = NULL; tangent = NULL; isCreated = false; isFinished = false; SetEnvmapEnable(false); SetCullMode(CULL_CW); SetTexture(NULL); SetLightmap(NULL); SetFlipNormals(false); SetCalculateNormals(true); SetEnabled(true); SetTransparency(BLEND_NONE); SetWriteZBuffer(true); //SetPerPixelLighting(false); SetScale(1, 1, 1); SetLocation(0, 0, 0); SetRotation(0, 0, 0); } Object::~Object() { } void Object::Create(int iNrVertices, int iNrFaces) { if (isCreated) { return; } nrVertices = iNrVertices; nrFaces = iNrFaces; vertex = new OBJECT_VERTEX[nrVertices]; face = new OBJECT_FACE[nrFaces]; normalCounter = new int[nrVertices]; isCreated = true; } void Object::Finish(bool bIsDynamic) { if (isFinished || !isCreated) { return; } isDynamic = bIsDynamic; if (isEnvmapped) { isDynamic = true; } pyramid->CreateVertexBuffer(nrVertices, sizeof(OBJECT_VERTEX), OBJECT_VERTEX_FVF, isDynamic, false, &vertexBuffer); pyramid->CreateIndexBuffer(nrFaces, false, false, &indexBuffer); if (doCalculateNormals) { CalculateNormals(); } /*if (doPerPixelLighting) { if (tangent == NULL) { tangent = new OBJECT_TANGENT[nrVertices]; } if (vertexBufferTangent == NULL) { pyramid->CreateVertexBuffer(nrVertices, sizeof(OBJECT_TANGENT), 0, isDynamic, false, &vertexBufferTangent); } CalculateTangents(); vertexBufferTangent->Update(tangent); }*/ vertexBuffer->Update(vertex); indexBuffer->Update(face); isFinished = true; } void Object::Refresh() { if (doCalculateNormals) { CalculateNormals(); } //if (doPerPixelLighting) //{ // CalculateTangents(); // vertexBufferTangent->Update(tangent); //} vertexBuffer->Update(vertex, 0, nrVertices * sizeof(OBJECT_VERTEX)); indexBuffer->Update(face, 0, nrFaces * sizeof(OBJECT_FACE)); } void Object::Destroy() { if (isCreated) { delete [] vertex; delete [] face; delete [] normalCounter; } if (tangent != NULL) { delete [] tangent; } } void Object::CalculateNormals() { int i; for (i = 0; i < nrVertices; i++) { vertex[i].nx = vertex[i].ny = vertex[i].nz = 0; normalCounter[i] = 0; } for (i = 0; i < nrFaces; i++) { int a = face[i].a; int b = face[i].b; int c = face[i].c; float relx1 = vertex[b].x - vertex[a].x; float rely1 = vertex[b].y - vertex[a].y; float relz1 = vertex[b].z - vertex[a].z; float relx2 = vertex[c].x - vertex[a].x; float rely2 = vertex[c].y - vertex[a].y; float relz2 = vertex[c].z - vertex[a].z; float nx = (rely1 * relz2) - (relz1 * rely2); float ny = (relz1 * relx2) - (relx1 * relz2); float nz = (relx1 * rely2) - (rely1 * relx2); vertex[a].nx += nx; vertex[a].ny += ny; vertex[a].nz += nz; normalCounter[a]++; vertex[b].nx += nx; vertex[b].ny += ny; vertex[b].nz += nz; normalCounter[b]++; vertex[c].nx += nx; vertex[c].ny += ny; vertex[c].nz += nz; normalCounter[c]++; } for (i = 0; i < nrVertices; i++) { float nx = vertex[i].nx / normalCounter[i]; float ny = vertex[i].ny / normalCounter[i]; float nz = vertex[i].nz / normalCounter[i]; float magnitude = (float) sqrt((nx * nx) + (ny * ny) + (nz * nz)); vertex[i].nx = -nx / magnitude; vertex[i].ny = -ny / magnitude; vertex[i].nz = -nz / magnitude; } if (doFlipNormals) { for (i = 0; i < nrVertices; i++) { vertex[i].nx = -vertex[i].nx; vertex[i].ny = -vertex[i].ny; vertex[i].nz = -vertex[i].nz; } } } //void Object::CalculateTangents() //{ // //int i; // // //Vector *binormal = new Vector[nrVertices]; // // //for (i = 0; i < nrVertices; i++) // //{ // // tangent[i].tx = tangent[i].ty = tangent[i].tz = 0; // // binormal[i].x = binormal[i].y = binormal[i].z = 0; // // // // normalCounter[i] = 0; // //} // // // for (i = 0; i < nrFaces; i++) // //{ // // int a = face[i].a; // // int b = face[i].b; // // int c = face[i].c; // // // // Vector t1, t2, t; // // // // x // // t1.x = vertex[b].x - vertex[a].x; // // t1.y = vertex[b].u - vertex[a].u; // // t1.z = vertex[b].v - vertex[a].v; // // // t2.x = vertex[c].x - vertex[a].x; // // t2.y = vertex[c].u - vertex[a].u; // // t2.z = vertex[c].v - vertex[a].v; // // // t = t1.CrossProduct(t2); // // // if (t.x != 0) // // { // // tangent[a].tx += -t.y / t.x; // // tangent[b].tx += -t.y / t.x; // // tangent[c].tx += -t.y / t.x; // // // binormal[a].x += -t.z / t.x; // // binormal[b].x += -t.z / t.x; // // binormal[c].x += -t.z / t.x; // // // // normalCounter[a]++; // // } // // // // // y // // t1.x = vertex[b].y - vertex[a].y; // // t2.x = vertex[c].y - vertex[a].y; // // // t = t1.CrossProduct(t2); // // // if (t.x != 0) // // { // // tangent[a].ty += -t.y / t.x; // // tangent[b].ty += -t.y / t.x; // // tangent[c].ty += -t.y / t.x; // // // binormal[a].y += -t.z / t.x; // // binormal[b].y += -t.z / t.x; // // binormal[c].y += -t.z / t.x; // // // normalCounter[b]++; // // } // // // // z // // t1.x = vertex[b].z - vertex[a].z; // // t2.x = vertex[c].z - vertex[a].z; // // // t = t1.CrossProduct(t2); // // // if (t.x != 0) // // { // // tangent[a].tz += -t.y / t.x; // // tangent[b].tz += -t.y / t.x; // // tangent[c].tz += -t.y / t.x; // // // binormal[a].z += -t.z / t.x; // // binormal[b].z += -t.z / t.x; // // binormal[c].z += -t.z / t.x; // // // normalCounter[c]++; // // } // // } // // //for (i = 0; i < nrVertices; i++) // //{ // // Vector t1, t2, t, n; // // // t1.x = tangent[i].tx; // // t1.y = tangent[i].ty; // // t1.z = tangent[i].tz; // // // t2.x = binormal[i].x; // // t2.y = binormal[i].y; // // t2.z = binormal[i].z; // // // n.x = vertex[i].nx; // // n.y = vertex[i].ny; // // n.z = vertex[i].nz; // // // t1 = t1.Normalize(); // // t2 = t2.Normalize(); // // // tangent[i].tx = t1.x; // // tangent[i].ty = t1.y; // // tangent[i].tz = t1.z; // // // t = t1.CrossProduct(t2); // // // t = t.Normalize(); // // // if (t.DotProduct(n) < 0.0f) // // { // // t.x = -t.x; // // t.y = -t.y; // // t.z = -t.z; // // } // // // vertex[i].nx = t.x; // // vertex[i].ny = t.y; // // vertex[i].nz = t.z; // //} // // //delete [] binormal; //} //void Object::SetPerPixelLighting(bool bPerPixelLighting) //{ // doPerPixelLighting = bPerPixelLighting; //} void Object::CalculateEnvmapUV() { Matrix matWorld, matView, matWV; pyramid->GetViewMatrix(matView); pyramid->GetWorldMatrix(matWorld); matWV = matWorld * matView; for (int i = 0; i < nrVertices; i++) { vertex[i].u = 0.5f + (0.5f * (vertex[i].nx * matWV._11 + vertex[i].ny * matWV._21 + vertex[i].nz * matWV._31)); vertex[i].v = 0.5f - (0.5f * (vertex[i].nx * matWV._12 + vertex[i].ny * matWV._22 + vertex[i].nz * matWV._32)); } } void Object::Render() { if (!isCreated || !isEnabled) { return; } if (!isFinished) { Finish(false); } Matrix matRot, matLoc, matScl; matRot = Matrix::RotateY(rotation.y) * Matrix::RotateZ(rotation.z) * Matrix::RotateX(rotation.x); matLoc = Matrix::Translation(location.x, location.y, location.z); matScl = Matrix::Scale(scale.x, scale.y, scale.z); pyramid->SetWorldMatrix(matScl * matRot * matLoc); if (isDynamic || isEnvmapped) { if (doCalculateNormals) { CalculateNormals(); } if (isEnvmapped) { CalculateEnvmapUV(); } Refresh(); } pyramid->SetMaterial(material); if (material.power > 0.0f) { pyramid->SetRenderState(D3DRS_SPECULARENABLE, true); } else { pyramid->SetRenderState(D3DRS_SPECULARENABLE, false); } pyramid->SetCullMode(cullMode); if (texture != NULL) { pyramid->SetTexture(texture); } else { pyramid->SetTexture(NULL); } if (lightmap != NULL) { pyramid->SetTexture(lightmap, 1); pyramid->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE); pyramid->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1); } else { pyramid->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); } if (writeZBuffer) { pyramid->SetWriteZBufferEnable(true); } else { pyramid->SetWriteZBufferEnable(false); } pyramid->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); pyramid->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); pyramid->SetTransparency(transMode); pyramid->SetVertexStream(vertexBuffer); pyramid->SetIndexStream(indexBuffer); //if (vertexShader != NULL) //{ // Matrix matView, matProj, matWorld, matTransform, matWorldInverse; // pyramid->GetWorldMatrix(matWorld); // pyramid->GetViewMatrix(matView); // pyramid->GetProjectionMatrix(matProj); // matTransform = (matWorld * matView * matProj).Transpose(); // matWorldInverse = (matWorld.Inverse()).Transpose(); // matWorld = matWorld.Transpose(); // matView = matView.Transpose(); // pyramid->SetVertexShaderConstantF( 0, (float*)&matTransform, 4); // pyramid->SetVertexShaderConstantF( 4, (float*)&matWorld, 4); // pyramid->SetVertexShaderConstantF( 8, (float*)&matWorldInverse, 4); // pyramid->SetVertexShaderConstantF(12, (float*)&matView, 4); // float power[] = {material.power, 0, 0, 0}; // pyramid->SetVertexShaderConstantF(40, (float*)&material.diffuse, 4); // pyramid->SetVertexShaderConstantF(41, (float*)&material.specular, 4); // pyramid->SetVertexShaderConstantF(42, (float*)&material.emissive, 4); // pyramid->SetVertexShaderConstantF(43, (float*)&power, 4); // pyramid->SetVertexShader(vertexShader); //} //if (pixelShader != NULL) //{ // pyramid->SetPixelShader(pixelShader); //} //if (doPerPixelLighting) //{ // pyramid->SetVertexStream(vertexBufferTangent, 1); //} pyramid->DrawIndexedPrimitiveList(0, nrVertices, 0, nrFaces); pyramid->SetPixelShader(NULL); // pyramid->SetVertexShader(NULL); pyramid->SetVertexStream(NULL, 1); } void Object::ScaleUV(float fScale) { ScaleUV(fScale, fScale); } void Object::ScaleUV(float fScaleU, float fScaleV) { for (int i = 0; i < nrVertices; i++) { vertex[i].u *= fScaleU; vertex[i].v *= fScaleV; } } void Object::FlipU(float fBase) { for (int i = 0; i < nrVertices; i++) { vertex[i].u = fBase - vertex[i].u; } } void Object::FlipV(float fBase) { for (int i = 0; i < nrVertices; i++) { vertex[i].v = fBase - vertex[i].v; } } void Object::SetLocation(float fX, float fY, float fZ) { location.x = fX; location.y = fY; location.z = fZ; } void Object::SetRotation(float fX, float fY, float fZ) { rotation.x = fX * _PI / 180.f; rotation.y = fY * _PI / 180.f; rotation.z = fZ * _PI / 180.f; } void Object::SetScale(float fX, float fY, float fZ) { scale.x = fX; scale.y = fY; scale.z = fZ; } void Object::SetLocation(Vector &pLocation) { location = pLocation; } void Object::SetRotation(Vector &pRotation) { rotation = pRotation; } void Object::SetScale(Vector &pScale) { scale = pScale; } //void Object::SetVertexShader(VertexShader* pVertexShader) //{ // vertexShader = pVertexShader; //} // //void Object::SetPixelShader(PixelShader* pPixelShader) //{ // pixelShader = pPixelShader; //} void Object::SetDiffuse(float fR, float fG, float fB, float fA) { material.SetDiffuse(fR, fG, fB, fA); } void Object::SetAmbient(float fR, float fG, float fB, float fA) { material.SetAmbient(fR, fG, fB, fA); } void Object::SetSpecular(float fR, float fG, float fB, float fA) { material.SetSpecular(fR, fG, fB, fA); } void Object::SetEmissive(float fR, float fG, float fB, float fA) { material.SetEmissive(fR, fG, fB, fA); } void Object::SetPower(float fPower) { material.SetPower(fPower); } void Object::SetCullMode(CULL_MODE uiCullMode) { cullMode = uiCullMode; } void Object::SetEnvmapEnable(bool bIsEnvmapped) { isEnvmapped = bIsEnvmapped; } void Object::SetTexture(Texture* pTexture) { texture = pTexture; } void Object::SetLightmap(Texture* pTexture) { lightmap = pTexture; } void Object::SetFlipNormals(bool bFlipNormals) { doFlipNormals = bFlipNormals; } void Object::SetCalculateNormals(bool bCalculateNormals) { doCalculateNormals = bCalculateNormals; } void Object::SetWriteZBuffer(bool bWriteZBuffer) { writeZBuffer = bWriteZBuffer; } void Object::SetEnabled(bool bRenderEnable) { isEnabled = bRenderEnable; } void Object::SetTransparency(BLEND_MODE iTransMode) { transMode = iTransMode; } //void Object::Optimize(float fDif) { // /*for (int i = 0; i < nrFaces; i++) // { // int a = face[i].a; // int b = face[i].b; // int c = face[i].c; // // OBJECT_VERTEX v1 = vertex[a]; // OBJECT_VERTEX v2 = vertex[b]; // OBJECT_VERTEX v3 = vertex[c]; // // for (int j = 0; j < nrVertices; j++) // { // OBJECT_VERTEX v = vertex[j]; // if (a != j) // { // if ((v1.x >= (v.x - fDif)) && (v1.x <= (v.x + fDif)) && // (v1.y >= (v.y - fDif)) && (v1.y <= (v.y + fDif)) && // (v1.z >= (v.z - fDif)) && (v1.z <= (v.z + fDif))) // a = j; // } // if (b != j) // { // if ((v2.x >= (v.x - fDif)) && (v2.x <= (v.x + fDif)) && // (v2.y >= (v.y - fDif)) && (v2.y <= (v.y + fDif)) && // (v2.z >= (v.z - fDif)) && (v2.z <= (v.z + fDif))) // b = j; // } // if (c != j) // { // if ((v3.x >= (v.x - fDif)) && (v3.x <= (v.x + fDif)) && // (v3.y >= (v.y - fDif)) && (v3.y <= (v.y + fDif)) && // (v3.z >= (v.z - fDif)) && (v3.z <= (v.z + fDif))) // c = j; // } // } // // face[i].a = a; // face[i].b = b; // face[i].c = c; // }*/ //}
20.842324
117
0.564736
[ "render", "object", "vector" ]
e699c98efdefecdaac238a9125ff405de9a13117
1,788
cpp
C++
UVa-OnlineJudge/UVa280_Vetex.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
UVa-OnlineJudge/UVa280_Vetex.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
UVa-OnlineJudge/UVa280_Vetex.cpp
AREA44/competitive-programming
00cede478685bf337193bce4804f13c4ff170903
[ "MIT" ]
null
null
null
/* UVa - 280 - Vertex * https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=216 */ //nhatnguyendrgs (c) 2015 #include "iostream" #include "stdio.h" #include "stdlib.h" #include "string" #include "string.h" #include "algorithm" #include "math.h" #include "vector" #include "map" #include "queue" #include "stack" #include "deque" #include "set" using namespace std; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; const int inf = 1e9; const int MaxN = 1e2; const int base = 1e9+7; #define DFS_WHITE -1 #define DFS_BLACK 1 int n,q,u,v; vector<vi> Adj; vi dfs_num; void dfs(int u){ for(int j=0;j<Adj[u].size();j++){ int v=Adj[u][j]; if(dfs_num[v]==DFS_WHITE){ dfs_num[v]=DFS_BLACK; dfs(v); } } } queue<int> Q; int main(){ while(1){ scanf("%d",&n); if(n==0) break; Adj.assign(n+4,vi()); while(1){ scanf("%d",&u); if(u==0) break; while(1){ scanf("%d",&v); if(v==0) break; Adj[u].push_back(v); } } scanf("%d",&q); for(int i=1;i<=q;i++){ scanf("%d",&u); dfs_num.assign(n+4,DFS_WHITE); dfs(u); for(int i=1;i<=n;i++){ if(dfs_num[i]==DFS_WHITE) Q.push(i); } if(Q.size()==0) printf("0\n"); else{ printf("%d ",Q.size()); while(Q.size()>1){ printf("%d ", Q.front()); Q.pop(); } printf("%d\n",Q.front()); Q.pop(); } } } return 0; }
21.285714
117
0.463087
[ "vector" ]
e6ac59eef4d9cc88e80009f20ca0452bc59e94f3
1,300
cpp
C++
Arrays/CPP/duplicate_in_sorted_array.cpp
ultraUnicorn74/DSA-Path-And-Important-Questions
5fca1a11f083f6ccb704cf50e101234b1260edc5
[ "MIT" ]
26
2021-08-04T17:03:26.000Z
2022-03-08T08:43:44.000Z
Arrays/CPP/duplicate_in_sorted_array.cpp
ultraUnicorn74/DSA-Path-And-Important-Questions
5fca1a11f083f6ccb704cf50e101234b1260edc5
[ "MIT" ]
25
2021-08-04T16:58:33.000Z
2021-11-01T05:26:19.000Z
Arrays/CPP/duplicate_in_sorted_array.cpp
ultraUnicorn74/DSA-Path-And-Important-Questions
5fca1a11f083f6ccb704cf50e101234b1260edc5
[ "MIT" ]
16
2021-08-14T20:15:24.000Z
2022-02-23T11:04:06.000Z
/* Input format:- first line takes the no. of test cases second line takes n - the no of elements third lines takes input of n space seperated elements Testcases:- Input:- 2 5 1 1 4 4 6 14 1 3 4 5 5 5 5 8 8 8 8 9 9 9 Output:- 1 4 6 1 3 4 5 8 9 */ #include <iostream> #include <vector> using namespace std; int removeDuplicates(vector<int>& nums) { // if size is 0 then there is no unique element if(nums.size()==0) return 0; int ans = 0; for (int i = 0; i < nums.size() - 1; i++) // if there is unique element then add it if (nums[i] != nums[i + 1]) nums[ans++] = nums[i]; // finally add the last element as we have not checked for it before nums[ans++] = nums[nums.size() - 1]; return ans; } int main() { int t; // for different testcases cin>>t; while(t--){ int n; // size of array cin>>n; vector<int> nums; for(int i=0; i<n; i++){ int temp; cin>>temp; nums.push_back(temp); } int k = removeDuplicates(nums); for(int i=0; i<k; i++) cout<<nums[i]<<" "; cout<<endl; } return 0; }
22.413793
73
0.490769
[ "vector" ]
e6b531ae0cf3574a108e1c208b46c583834f9927
9,444
cpp
C++
src/detection_processing.cpp
tue-ropod/camera_detector
bf57cf82d9c4a4a87a2f2e992ad7454298d0a63c
[ "BSD-2-Clause" ]
null
null
null
src/detection_processing.cpp
tue-ropod/camera_detector
bf57cf82d9c4a4a87a2f2e992ad7454298d0a63c
[ "BSD-2-Clause" ]
null
null
null
src/detection_processing.cpp
tue-ropod/camera_detector
bf57cf82d9c4a4a87a2f2e992ad7454298d0a63c
[ "BSD-2-Clause" ]
null
null
null
using namespace std; /// [headers] // ROS //#include <ros/ros.h> //#include "camera_detector/objPosVel.h" //#include "camera_detector/detections.h" #include "ed_gui_server/objsPosVel.h" //#include<geometry_msgs/Point.msg> // Openpose API (including opencv) #include <openpose/headers.hpp> #include <camera_detector/detection_processing.h> #include <ctime> #include <iostream> #include <chrono> #include <sys/time.h> struct timeval timeC; #include <sstream> #include <openpose/pose/poseParameters.hpp> /* Pose output As mentioned at https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/doc/02_output.md Result for BODY_25 (25 body parts consisting of COCO + foot) const std::map<unsigned int, std::string> POSE_BODY_25_BODY_PARTS { {0, "Nose"}, {1, "Neck"}, {2, "RShoulder"}, {3, "RElbow"}, {4, "RWrist"}, {5, "LShoulder"}, {6, "LElbow"}, {7, "LWrist"}, {8, "MidHip"}, {9, "RHip"}, {10, "RKnee"}, {11, "RAnkle"}, {12, "LHip"}, {13, "LKnee"}, {14, "LAnkle"}, {15, "REye"}, {16, "LEye"}, {17, "REar"}, {18, "LEar"}, {19, "LBigToe"}, {20, "LSmallToe"}, {21, "LHeel"}, {22, "RBigToe"}, {23, "RSmallToe"}, {24, "RHeel"}, {25, "Background"} }; */ const auto& poseBodyPartMappingBody25 = op::getPoseBodyPartMapping(op::PoseModel::BODY_25); string storageLocation = "/home/nvidia/pictures/"; void detection_processing::display(const std::shared_ptr<std::vector<std::shared_ptr<op::Datum>>>& datumsPtr,double timeD) { try { if (datumsPtr != nullptr && !datumsPtr->empty()) { // Display image cv::Mat flipImage; cv::flip(datumsPtr->at(0)->cvOutputData, flipImage,1); // cv::imshow(OPEN_POSE_NAME_AND_VERSION + " - detector on Kinect input", flipImage); // time_t current_time; // string name = "/media/nvidia/TOSHIBA/pictures/kinectDetection_" + to_string(time(NULL)) + ".jpg"; // gettimeofday(&timeC, NULL); std::stringstream stream; stream << std::fixed << std::setprecision(2) << timeD; // string name = "/home/nvidia/pictures/kinectDetection_" + stream.str() + ".jpg"; string name = storageLocation + "kinectDetection_" + stream.str() + ".jpg"; cout<<name<<endl; cv::imwrite(name,flipImage); } else op::log("Nullptr or empty datumsPtr found.", op::Priority::High); } catch (const std::exception& e) { op::error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } void detection_processing::depthMeasurement(int indx,int indy, cv::Mat &rgbd2, double &dist) { // calculate mean distance over 25 points double distItTemp; double countDistIt=0; double distIt=0.0; for (int ii=-2;ii<3;ii++) { for (int jj=-2;jj<3;jj++) { distItTemp = rgbd2.at<float>(indy+ii,indx+jj); if (distItTemp!=0 && !isnan(distItTemp)) { // check if measurement is valid distIt = distIt + distItTemp; // add measurement countDistIt = countDistIt+1.0; // count amount of valid measurements } } } dist = distIt/countDistIt/1000.0+0.5*rBody; // determine average distance (in meter) AND compensate for measuring front instead of inside leg } hip_msgs::detection detection_processing::xyzPoints(const auto poseKeypoints,auto person,vector<unsigned int> bodyParts,cv::Mat &rgbd2, double timeStamp, bool saveDetectionData) { // measure depth of object double dist,thetaH,thetaV,x,y,z,p; int indx,indy,bodyPart; hip_msgs::detection m; int count=0; x=y=p=0.0; m.x=m.y=m.p=0.0; point pTemp; for (int i=0; i<bodyParts.size(); i++) { bodyPart = bodyParts[i]; indx = round(poseKeypoints[vector<int> {person, bodyPart, 0}])-1; // look for index in depth image from rgb detection if (indx>0) { // for all detected points indy = round(poseKeypoints[vector<int> {person, bodyPart, 1}])-1; // look for index in depth image from rgb detection // calculate mean distance over 25 points depthMeasurement(indx,indy,rgbd2,dist); if (dist>0 && dist<20) { // only use points with distance between zero and 20 meter count++; thetaH = (indx/resH-0.5)*thetaHKinect/180.0*M_PI; thetaV = -(indy/resV-0.5)*thetaVKinect/180.0*M_PI; toXYZ(pTemp, thetaH, thetaV, dist); //std::cout << "detection processing: bodyprt = " << bodyPart << " thetaH = " << thetaH << " thetaV = " << thetaV << " dist = " << dist << " xyz = " << pTemp.x << ", " << pTemp.y << ", " << pTemp.z << std::endl; x = x+pTemp.x; y = y+pTemp.y; z = z+pTemp.z; p = p+poseKeypoints[vector<int> {person, bodyPart, 2}]; } } } m.p = p/double(count); m.x = x/double(count); m.y = y/double(count); m.z = z/double(count); if(saveDetectionData) { FILE* fp; string fileName = storageLocation + "keypointDataPerson" + to_string(person) + "_" + to_string(timeStamp) + ".txt"; fp = fopen(fileName.c_str(), "w"); for (int i=0; i<bodyParts.size(); i++) { bodyPart = bodyParts[i]; indx = round(poseKeypoints[vector<int> {person, bodyPart, 0}])-1; // look for index in depth image from rgb detection if (indx>0) { // for all detected points indy = round(poseKeypoints[vector<int> {person, bodyPart, 1}])-1; // look for index in depth image from rgb detection // calculate mean distance over 25 points depthMeasurement(indx,indy,rgbd2,dist); if (dist>0 && dist<20) { // only use points with distance between zero and 20 meter thetaH = (indx/resH-0.5)*thetaHKinect/180.0*M_PI; thetaV = -(indy/resV-0.5)*thetaVKinect/180.0*M_PI; toXYZ(pTemp, thetaH, thetaV, dist); x = pTemp.x; y = pTemp.y; z = pTemp.z; p = poseKeypoints[vector<int> {person, bodyPart, 2}]; // fprintf(fp, "%s, %f, %f, %f, %f\n",poseBodyPartMappingBody25.at(bodyPart).c_str(), x, y, z, p); } else { fprintf(fp, "%s skipped, dist = %f\n",poseBodyPartMappingBody25.at(bodyPart).c_str(), dist); } } } fclose(fp); } return m; } void detection_processing::process(const auto poseKeypoints, cv::Mat &rgbd2, hip_msgs::detections &detectionData, double timeStamp, bool saveDetectionData) { std::stringstream timeStream; timeStream << std::fixed << std::setprecision(2) << timeStamp; hip_msgs::detection m; // const vector<int> all = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; // vector with all bodyparts // WH: why 1-24? const vector<unsigned int> all = {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}; for (int person = 0 ; person < poseKeypoints.getSize(0); person++) { m = xyzPoints(poseKeypoints,person,all,rgbd2,timeStamp, false); if (m.x>-20 && m.x<20 && m.y>-20 && m.y<20 && m.z>-20 && m.z<20) { detectionData.detections.push_back(m); } } if(saveDetectionData) { FILE* fp; string fileName = storageLocation + "positionData_" + timeStream.str() + ".txt"; fp = fopen(fileName.c_str(), "w"); for (int person = 0 ; person < poseKeypoints.getSize(0); person++) { m = xyzPoints(poseKeypoints,person,all,rgbd2,timeStamp, true); if (m.x>-20 && m.x<20 && m.y>-20 && m.y<20 && m.z>-20 && m.z<20) { fprintf(fp, "%f, %f, %f, %f\n", m.x, m.y, m.z, m.p); } } fclose(fp); } } void detection_processing::toXYZ(point &p, double thetaH, double thetaV, double dist) { // thetaH = -thetaH; // thetaV = -thetaV; p.x = cos(thetaH)*cos(thetaV)*dist; p.y = sin(thetaH)*cos(thetaV)*dist; p.z = sin(thetaV)*dist; } void detection_processing::processKeypoints(const std::shared_ptr<std::vector<std::shared_ptr<op::Datum>>>& datumsPtr,cv::Mat &rgbd2,hip_msgs::detections &detectionData, double timeStamp, bool saveDetectionData) { try { if (datumsPtr != nullptr && !datumsPtr->empty()) { // Accesing each element of the keypoints /** poseKeypoints (from https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/include/openpose/core/datum.hpp) * Body pose (x,y,score) locations for each person in the image. * It has been resized to the desired output resolution (e.g., `resolution` flag in the demo). * Size: #people x #body parts (e.g., 18 for COCO or 15 for MPI) x 3 ((x,y) coordinates + score) */ const auto& poseKeypoints = datumsPtr->at(0)->poseKeypoints; process(poseKeypoints,rgbd2,detectionData, timeStamp, saveDetectionData); } else op::log("Nullptr or empty datumsPtr found.", op::Priority::High); } catch (const std::exception& e) { op::error(e.what(), __LINE__, __FUNCTION__, __FILE__); } }
37.47619
211
0.580263
[ "object", "vector" ]
e6bf36f586aba0f2b4fa0116678d66e8f9226493
6,727
cpp
C++
src/base/RectangularPrism.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
src/base/RectangularPrism.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
src/base/RectangularPrism.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
/* * Copyright 2018 <copyright holder> <email> * * 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 "RectangularPrism.h" RectangularPrism::RectangularPrism() { } RectangularPrism::RectangularPrism(MVector3<float> pointFront, MVector3<float> pointBack, float size) { this->pointFront = pointFront; this->pointBack = pointBack; this->size = size; initMeshData(); } RectangularPrism::RectangularPrism(const RectangularPrism& other) { this->pointFront = other.pointFront; this->pointBack = other.pointBack; this->size = other.size; initMeshData(); } RectangularPrism::~RectangularPrism() { } void RectangularPrism::initMeshData() { MVector3<float> normal ( pointBack.GetX()-pointFront.GetX(), pointBack.GetY()-pointFront.GetY(), pointBack.GetZ()-pointFront.GetZ()); MVector3<float> w;//u=(0,0,0) if ( Math<float>::Abs(normal.GetX()) <= Math<float>::Abs(normal.GetY()) ) { if ( Math<float>::Abs(normal.GetX()) <= Math<float>::Abs(normal.GetZ()) ) { //x is minor w.SetX(1); } else {//z is minor w.SetZ(1); } } else {//y is minor ? if(Math<float>::Abs(normal.GetY()) <= Math<float>::Abs(normal.GetZ())) { //y is minor w.SetY(1); } else { //z is minor w.SetZ(1); } } normal.normalize(); MVector3<float> u = normal.CrossProduct(w); MVector3<float> v = normal.CrossProduct(u); u*=size; v*=size; //MVector3<float> v0 ( pointBack.GetX()-u.GetX(), pointBack.GetY()-v.GetY(), pointBack.GetZ());//left-bottom-back // MVector3<float> v1 ( pointBack.GetX()+u.GetX(), pointBack.GetY()-v.GetY(), pointBack.GetZ());//right-bottom-back // MVector3<float> v2 ( pointBack.GetX()-u.GetX(), pointBack.GetY()+v.GetY(), pointBack.GetZ());//left-top-back // MVector3<float> v3 ( pointFront.GetX()-u.GetX(), pointFront.GetY()-v.GetY(), pointFront.GetZ());//left-bottom-front // // //max face // MVector3<float> v4 ( pointBack.GetX()+u.GetX(), pointBack.GetY()+v.GetY(), pointBack.GetZ() );//right-top-back // MVector3<float> v5 ( pointFront.GetX()+u.GetX(), pointFront.GetY()-v.GetY(), pointFront.GetZ() );//right-bottom-front // MVector3<float> v6 ( pointFront.GetX()-u.GetX(), pointFront.GetY()+v.GetY(), pointFront.GetZ() );//left-top-front // MVector3<float> v7 ( pointFront.GetX()+u.GetX(), pointFront.GetY()+v.GetY(), pointFront.GetZ() );//right-top-front MVector3<float> v0 = pointBack -u-v;//left-bottom-back MVector3<float> v1 = pointBack +u-v;//right-bottom-back MVector3<float> v2 = pointBack -u+v;//left-top-back MVector3<float> v3 = pointFront -u-v;//left-bottom-front //max face MVector3<float> v4 = pointBack +u+v;//right-top-back MVector3<float> v5 = pointFront +u-v;//right-bottom-front MVector3<float> v6 = pointFront -u+v;//left-top-front MVector3<float> v7 = pointFront +u+v;//right-top-front std::cout << " normal : " << normal << endl; std::cout << " u : " << u << endl; std::cout << " v : " << v << endl; std::cout << " pointFront : " << pointFront << " left-bottom-front : " << v3 << " right-bottom-front : " << v5 << " left-top-front : " << v6 << " right-top-front : " << v7 << endl; std::cout << " pointBack : " << pointBack << " left-bottom-back : " << v0 << " right-bottom-back : " << v1 << " left-top-back : " << v2 << " right-top-back : " << v4 << endl; //0-left-bottom-back vertexCoords.push_back(v0.GetX()); vertexCoords.push_back(v0.GetY()); vertexCoords.push_back(v0.GetZ()); //1-right-bottom-back vertexCoords.push_back(v1.GetX()); vertexCoords.push_back(v1.GetY()); vertexCoords.push_back(v1.GetZ()); //2-left-top-back vertexCoords.push_back(v2.GetX()); vertexCoords.push_back(v2.GetY()); vertexCoords.push_back(v2.GetZ()); //3-left-bottom-front vertexCoords.push_back(v3.GetX()); vertexCoords.push_back(v3.GetY()); vertexCoords.push_back(v3.GetZ()); //4-right-top-back vertexCoords.push_back(v4.GetX()); vertexCoords.push_back(v4.GetY()); vertexCoords.push_back(v4.GetZ()); //5-right-bottom-front vertexCoords.push_back(v5.GetX()); vertexCoords.push_back(v5.GetY()); vertexCoords.push_back(v5.GetZ()); //6-left-top-front vertexCoords.push_back(v6.GetX()); vertexCoords.push_back(v6.GetY()); vertexCoords.push_back(v6.GetZ()); //7-right-top-front vertexCoords.push_back(v7.GetX()); vertexCoords.push_back(v7.GetY()); vertexCoords.push_back(v7.GetZ()); int index=0, index1=1, index2=2, index3=3, index4=4, index5=5, index6=6, index7=7; //back face indexBuffer.push_back(index); indexBuffer.push_back(index1); indexBuffer.push_back(index4); indexBuffer.push_back(index4); indexBuffer.push_back(index2); indexBuffer.push_back(index); //left face indexBuffer.push_back(index); indexBuffer.push_back(index2); indexBuffer.push_back(index6); indexBuffer.push_back(index6); indexBuffer.push_back(index3); indexBuffer.push_back(index); //bottom face indexBuffer.push_back(index); indexBuffer.push_back(index3); indexBuffer.push_back(index5); indexBuffer.push_back(index5); indexBuffer.push_back(index1); indexBuffer.push_back(index); //right face indexBuffer.push_back(index1); indexBuffer.push_back(index4); indexBuffer.push_back(index7); indexBuffer.push_back(index7); indexBuffer.push_back(index5); indexBuffer.push_back(index1); //front face indexBuffer.push_back(index5); indexBuffer.push_back(index7); indexBuffer.push_back(index6); indexBuffer.push_back(index6); indexBuffer.push_back(index3); indexBuffer.push_back(index5); //top face indexBuffer.push_back(index2); indexBuffer.push_back(index6); indexBuffer.push_back(index7); indexBuffer.push_back(index7); indexBuffer.push_back(index4); indexBuffer.push_back(index2); indexSections[0]=indexBuffer; indexModeBuffer.push_back(Mesh::Triangles); indexLenghts.push_back(12); UpdateTriangleList(); }
37.581006
185
0.653486
[ "mesh" ]
e6bf5def281e1944001774175d63436472df18a6
15,714
cpp
C++
qtmultimedia/src/imports/multimedia/qdeclarativeradio.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtmultimedia/src/imports/multimedia/qdeclarativeradio.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtmultimedia/src/imports/multimedia/qdeclarativeradio.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativeradio_p.h" #include "qdeclarativeradiodata_p.h" QT_BEGIN_NAMESPACE /*! \qmltype Radio \instantiates QDeclarativeRadio \inqmlmodule QtMultimedia \brief Access radio functionality from a QML application. \ingroup multimedia_qml \ingroup multimedia_radio_qml \inherits Item \qml Rectangle { width: 320 height: 480 Radio { id: radio band: Radio.FM } MouseArea { x: 0; y: 0 height: parent.height width: parent.width / 2 onClicked: radio.scanDown() } MouseArea { x: parent.width / 2; y: 0 height: parent.height width: parent.width / 2 onClicked: radio.scanUp() } } \endqml You can use \c Radio to tune the radio and get information about the signal. You can also use the Radio to get information about tuning, for instance the frequency steps supported for tuning. The corresponding \l RadioData gives RDS information about the current radio station. The best way to access the RadioData for the current Radio is to use the \c radioData property. \sa {Radio Overview} */ QDeclarativeRadio::QDeclarativeRadio(QObject *parent) : QObject(parent) { m_radioTuner = new QRadioTuner(this); m_radioData = new QDeclarativeRadioData(m_radioTuner, this); connect(m_radioTuner, SIGNAL(stateChanged(QRadioTuner::State)), this, SLOT(_q_stateChanged(QRadioTuner::State))); connect(m_radioTuner, SIGNAL(bandChanged(QRadioTuner::Band)), this, SLOT(_q_bandChanged(QRadioTuner::Band))); connect(m_radioTuner, SIGNAL(frequencyChanged(int)), this, SIGNAL(frequencyChanged(int))); connect(m_radioTuner, SIGNAL(stereoStatusChanged(bool)), this, SIGNAL(stereoStatusChanged(bool))); connect(m_radioTuner, SIGNAL(searchingChanged(bool)), this, SIGNAL(searchingChanged(bool))); connect(m_radioTuner, SIGNAL(signalStrengthChanged(int)), this, SIGNAL(signalStrengthChanged(int))); connect(m_radioTuner, SIGNAL(volumeChanged(int)), this, SIGNAL(volumeChanged(int))); connect(m_radioTuner, SIGNAL(mutedChanged(bool)), this, SIGNAL(mutedChanged(bool))); connect(m_radioTuner, SIGNAL(stationFound(int,QString)), this, SIGNAL(stationFound(int,QString))); connect(m_radioTuner, SIGNAL(antennaConnectedChanged(bool)), this, SIGNAL(antennaConnectedChanged(bool))); connect(m_radioTuner, SIGNAL(availabilityChanged(QMultimedia::AvailabilityStatus)), this, SLOT(_q_availabilityChanged(QMultimedia::AvailabilityStatus))); connect(m_radioTuner, SIGNAL(error(QRadioTuner::Error)), this, SLOT(_q_error(QRadioTuner::Error))); } QDeclarativeRadio::~QDeclarativeRadio() { } /*! \qmlproperty enumeration QtMultimedia::Radio::state This property holds the current state of the Radio. \table \header \li Value \li Description \row \li ActiveState \li The radio is started and active \row \li StoppedState \li The radio is stopped \endtable \sa start, stop */ QDeclarativeRadio::State QDeclarativeRadio::state() const { return static_cast<QDeclarativeRadio::State>(m_radioTuner->state()); } /*! \qmlproperty enumeration QtMultimedia::Radio::band This property holds the frequency band used for the radio, which can be specified as any one of the values in the table below. \table \header \li Value \li Description \row \li AM \li 520 to 1610 kHz, 9 or 10kHz channel spacing, extended 1610 to 1710 kHz \row \li FM \li 87.5 to 108.0 MHz, except Japan 76-90 MHz \row \li SW \li 1.711 to 30.0 MHz, divided into 15 bands. 5kHz channel spacing \row \li LW \li 148.5 to 283.5 kHz, 9kHz channel spacing (Europe, Africa, Asia) \row \li FM2 \li range not defined, used when area supports more than one FM range \endtable */ QDeclarativeRadio::Band QDeclarativeRadio::band() const { return static_cast<QDeclarativeRadio::Band>(m_radioTuner->band()); } /*! \qmlproperty int QtMultimedia::Radio::frequency Sets the frequency in Hertz that the radio is tuned to. The frequency must be within the frequency range for the current band, otherwise it will be changed to be within the frequency range. \sa maximumFrequency, minimumFrequency */ int QDeclarativeRadio::frequency() const { return m_radioTuner->frequency(); } /*! \qmlproperty enumeration QtMultimedia::Radio::stereoMode This property holds the stereo mode of the radio, which can be set to any one of the values in the table below. \table \header \li Value \li Description \row \li Auto \li Uses stereo mode matching the station \row \li ForceStereo \li Forces the radio to play the station in stereo, converting the sound signal if necessary \row \li ForceMono \li Forces the radio to play the station in mono, converting the sound signal if necessary \endtable */ QDeclarativeRadio::StereoMode QDeclarativeRadio::stereoMode() const { return static_cast<QDeclarativeRadio::StereoMode>(m_radioTuner->stereoMode()); } /*! \qmlproperty int QtMultimedia::Radio::volume Set this property to control the volume of the radio. The valid range of the volume is from 0 to 100. */ int QDeclarativeRadio::volume() const { return m_radioTuner->volume(); } /*! \qmlproperty bool QtMultimedia::Radio::muted This property reflects whether the radio is muted or not. */ bool QDeclarativeRadio::muted() const { return m_radioTuner->isMuted(); } /*! \qmlproperty bool QtMultimedia::Radio::stereo This property holds whether the radio is receiving a stereo signal or not. If \l stereoMode is set to ForceMono the value will always be false. Likewise, it will always be true if stereoMode is set to ForceStereo. \sa stereoMode */ bool QDeclarativeRadio::stereo() const { return m_radioTuner->isStereo(); } /*! \qmlproperty int QtMultimedia::Radio::signalStrength The strength of the current radio signal as a percentage where 0% equals no signal, and 100% is a very good signal. */ int QDeclarativeRadio::signalStrength() const { return m_radioTuner->signalStrength(); } /*! \qmlproperty bool QtMultimedia::Radio::searching This property is true if the radio is currently searching for radio stations, for instance using the \l scanUp, \l scanDown, and \l searchAllStations methods. Once the search completes, or if it is cancelled using \l cancelScan, this property will be false. */ bool QDeclarativeRadio::searching() const { return m_radioTuner->isSearching(); } /*! \qmlproperty int QtMultimedia::Radio::frequencyStep The number of Hertz for each step when tuning the radio manually. The value is for the current \l band. */ int QDeclarativeRadio::frequencyStep() const { return m_radioTuner->frequencyStep(m_radioTuner->band()); } /*! \qmlproperty int QtMultimedia::Radio::minimumFrequency The minimum frequency for the current \l band. */ int QDeclarativeRadio::minimumFrequency() const { return m_radioTuner->frequencyRange(m_radioTuner->band()).first; } /*! \qmlproperty int QtMultimedia::Radio::maximumFrequency The maximum frequency for the current \l band. */ int QDeclarativeRadio::maximumFrequency() const { return m_radioTuner->frequencyRange(m_radioTuner->band()).second; } /*! \qmlproperty int QtMultimedia::Radio::antennaConnected This property is true if there is an antenna connected. Otherwise it will be false. */ bool QDeclarativeRadio::isAntennaConnected() const { return m_radioTuner->isAntennaConnected(); } /*! \qmlproperty enumeration QtMultimedia::Radio::availability Returns the availability state of the radio. This is one of: \table \header \li Value \li Description \row \li Available \li The radio is available to use \row \li Busy \li The radio is usually available to use, but is currently busy. This can happen when some other process needs to use the audio hardware. \row \li Unavailable \li The radio is not available to use (there may be no radio hardware) \row \li ResourceMissing \li There is one or more resources missing, so the radio cannot be used. It may be possible to try again at a later time. This can occur if there is no antenna connected - see the \l antennaConnected property as well. \endtable */ QDeclarativeRadio::Availability QDeclarativeRadio::availability() const { return Availability(m_radioTuner->availability()); } void QDeclarativeRadio::setBand(QDeclarativeRadio::Band band) { m_radioTuner->setBand(static_cast<QRadioTuner::Band>(band)); } void QDeclarativeRadio::setFrequency(int frequency) { m_radioTuner->setFrequency(frequency); } void QDeclarativeRadio::setStereoMode(QDeclarativeRadio::StereoMode stereoMode) { m_radioTuner->setStereoMode(static_cast<QRadioTuner::StereoMode>(stereoMode)); } void QDeclarativeRadio::setVolume(int volume) { m_radioTuner->setVolume(volume); } void QDeclarativeRadio::setMuted(bool muted) { m_radioTuner->setMuted(muted); } /*! \qmlmethod QtMultimedia::Radio::cancelScan() Cancel the current scan. Will also cancel a search started with \l searchAllStations. */ void QDeclarativeRadio::cancelScan() { m_radioTuner->cancelSearch(); } /*! \qmlmethod QtMultimedia::Radio::scanDown() Searches backward in the frequency range for the current band. */ void QDeclarativeRadio::scanDown() { m_radioTuner->searchBackward(); } /*! \qmlmethod QtMultimedia::Radio::scanUp() Searches forward in the frequency range for the current band. */ void QDeclarativeRadio::scanUp() { m_radioTuner->searchForward(); } /*! \qmlmethod QtMultimedia::Radio::searchAllStations(enumeration searchMode) Start searching the complete frequency range for the current band, and save all the radio stations found. The search mode can be either of the values described in the table below. \table \header \li Value \li Description \row \li SearchFast \li Stores each radio station for later retrival and tuning \row \li SearchGetStationId \li Does the same as SearchFast, but also emits the station Id with the \l stationFound signal. \endtable The snippet below uses \c searchAllStations with \c SearchGetStationId to receive all the radio stations in the current band, and store them in a ListView. The station Id is shown to the user and if the user presses a station, the radio is tuned to this station. \qml Item { width: 640 height: 360 Radio { id: radio onStationFound: radioStations.append({"frequency": frequency, "stationId": stationId}) } ListModel { id: radioStations } ListView { model: radioStations delegate: Rectangle { MouseArea { anchors.fill: parent onClicked: radio.frequency = frequency } Text { anchors.fill: parent text: stationId } } } Rectangle { MouseArea { anchors.fill: parent onClicked: radio.searchAllStations(Radio.SearchGetStationId) } } } \endqml */ void QDeclarativeRadio::searchAllStations(QDeclarativeRadio::SearchMode searchMode) { m_radioTuner->searchAllStations(static_cast<QRadioTuner::SearchMode>(searchMode)); } /*! \qmlmethod QtMultimedia::Radio::tuneDown() Decrements the frequency by the frequency step for the current band. If the frequency is already set to the minimum frequency, calling this function has no effect. \sa band, frequencyStep, minimumFrequency */ void QDeclarativeRadio::tuneDown() { int f = frequency(); f = f - frequencyStep(); setFrequency(f); } /*! \qmlmethod QtMultimedia::Radio::tuneUp() Increments the frequency by the frequency step for the current band. If the frequency is already set to the maximum frequency, calling this function has no effect. \sa band, frequencyStep, maximumFrequency */ void QDeclarativeRadio::tuneUp() { int f = frequency(); f = f + frequencyStep(); setFrequency(f); } /*! \qmlmethod QtMultimedia::Radio::start() Starts the radio. If the radio is available, as determined by the \l availability property, this will result in the \l state becoming \c ActiveState. */ void QDeclarativeRadio::start() { m_radioTuner->start(); } /*! \qmlmethod QtMultimedia::Radio::stop() Stops the radio. After calling this method the \l state will be \c StoppedState. */ void QDeclarativeRadio::stop() { m_radioTuner->stop(); } void QDeclarativeRadio::_q_stateChanged(QRadioTuner::State state) { emit stateChanged(static_cast<QDeclarativeRadio::State>(state)); } void QDeclarativeRadio::_q_bandChanged(QRadioTuner::Band band) { emit bandChanged(static_cast<QDeclarativeRadio::Band>(band)); } void QDeclarativeRadio::_q_error(QRadioTuner::Error errorCode) { emit error(static_cast<QDeclarativeRadio::Error>(errorCode)); emit errorChanged(); } void QDeclarativeRadio::_q_availabilityChanged(QMultimedia::AvailabilityStatus availability) { emit availabilityChanged(Availability(availability)); } /*! \qmlsignal QtMultimedia::Radio::stationFound(int frequency, string stationId) This signal is emitted when a new radio station is found. This signal is only emitted if \l searchAllStations is called with \c SearchGetStationId. The \a frequency is returned in Hertz, and the \a stationId corresponds to the station Id in the \l RadioData for this radio station. The corresponding handler is \c onStationFound. */ QT_END_NAMESPACE
29.371963
157
0.695558
[ "model" ]
e6c5fe8c6299d67451ec71a0769eae83a2218ad1
708
cpp
C++
src/old/numWays.cpp
hewei-nju/LeetCode
39aafffa9cc260056435ef4611e305f402b32223
[ "MIT" ]
null
null
null
src/old/numWays.cpp
hewei-nju/LeetCode
39aafffa9cc260056435ef4611e305f402b32223
[ "MIT" ]
null
null
null
src/old/numWays.cpp
hewei-nju/LeetCode
39aafffa9cc260056435ef4611e305f402b32223
[ "MIT" ]
null
null
null
class Solution { public: const int MODULO = 1000000007; int numWays(int steps, int arrLen) { int maxColumn = min(arrLen - 1, steps); vector<int> dp(maxColumn + 1); dp[0] = 1; for (int i = 1; i <= steps; i++) { vector<int> dpNext(maxColumn + 1); for (int j = 0; j <= maxColumn; j++) { dpNext[j] = dp[j]; if (j - 1 >= 0) { dpNext[j] = (dpNext[j] + dp[j - 1]) % MODULO; } if (j + 1 <= maxColumn) { dpNext[j] = (dpNext[j] + dp[j + 1]) % MODULO; } } dp = dpNext; } return dp[0]; } };
28.32
65
0.387006
[ "vector" ]
e6c9eafa68a3503327d3f082482ae252e1a3ac4f
4,215
cpp
C++
langdetectpp/src/detection/DetectionRunner.cpp
kovdan01/langdetectpp
85521e1372a4d45d4752b8183cb53aebb7080271
[ "Apache-2.0" ]
null
null
null
langdetectpp/src/detection/DetectionRunner.cpp
kovdan01/langdetectpp
85521e1372a4d45d4752b8183cb53aebb7080271
[ "Apache-2.0" ]
null
null
null
langdetectpp/src/detection/DetectionRunner.cpp
kovdan01/langdetectpp
85521e1372a4d45d4752b8183cb53aebb7080271
[ "Apache-2.0" ]
null
null
null
#include "detection/DetectionRunner.h" #include "ngrams/ExtractedNGrams.h" #include "ngrams/NGramExtractor.h" #include "profiles/Profile.h" #include "profiles/ProfileGroup.h" #include "util/CircleArray.h" #include "util/misc.h" #include "util/stats.h" #include <langdetectpp/Language.h> #include <string> #include <vector> using langdetectpp::profiles::ProfileGroup; using langdetectpp::util::Alpha; using langdetectpp::util::UniformIntDist; namespace langdetectpp::detection { constexpr double CONV_THRESHOLD = 0.99999; constexpr std::size_t BASE_FREQ = 10000; constexpr std::size_t ITERATION_LIMIT = 1000; DetectionRunner::DetectionRunner(std::shared_ptr<ProfileGroup> profGroup, ngrams::ExtractedNGrams& extracted) : profileGroup_(profGroup) , textNGrams_(extracted) { for (std::size_t i = 0; i < profileGroup_->profiles.size(); i++) { langScores_.push_back(0.0); } } Language DetectionRunner::getBestScore() { double maxScore = 0.0; std::size_t maxIndex = 0; for (std::size_t i = 0; i < langScores_.size(); i++) { auto score = langScores_[i]; if (score > maxScore) { maxScore = score; maxIndex = i; } } auto winningLang = profileGroup_->profiles.at(maxIndex); return winningLang->getLanguage(); } Language DetectionRunner::detect() { const std::size_t numTrials = 7; for (std::size_t trialN = 0; trialN < numTrials; trialN++) { alpha_.warble(); auto probs = runTrial(); for (std::size_t j = 0; j < langScores_.size(); j++) { double divisor = static_cast<double>(trialN); if (divisor <= 0) { divisor = 1.0; } double toAdd = (probs[j] / divisor); langScores_[j] += toAdd; } } return getBestScore(); } std::vector<double>* DetectionRunner::getLanguageScoresForRandomNGramOrNull() { std::size_t ngLen = ngramLengthDist_.get(); std::vector<double>* langWordScores = nullptr; if (ngLen == 1) { auto ng = textNGrams_.randomOneGram(); auto found = profileGroup_->oneGramWeights.find(ng); if (found != profileGroup_->oneGramWeights.end()) { langWordScores = &found->second; } } else if (ngLen == 2) { auto ng = textNGrams_.randomBigram(); auto found = profileGroup_->bigramWeights.find(ng); if (found != profileGroup_->bigramWeights.end()) { langWordScores = &found->second; } } else if (ngLen == 3) { auto ng = textNGrams_.randomTrigram(); auto found = profileGroup_->trigramWeights.find(ng); if (found != profileGroup_->trigramWeights.end()) { langWordScores = &found->second; } } return langWordScores; } std::vector<double> DetectionRunner::runTrial() { std::vector<double> probs; double startingProb = 1.0 / static_cast<double>(profileGroup_->profiles.size()); for (std::size_t i = 0; i < profileGroup_->profiles.size(); i++) { probs.push_back(startingProb); } for (std::size_t i = 0;; i++) { double weight = alpha_.get() / BASE_FREQ; auto langWordScores = getLanguageScoresForRandomNGramOrNull(); if (langWordScores != nullptr) { for (std::size_t k = 0; k < langWordScores->size(); k++) { probs[k] *= (weight + langWordScores->at(k)); } } if (i % 5 == 0) { double maxp = 0.0; double sump = 0.0; for (auto& elem : probs) { sump += elem; } for (std::size_t j = 0; j < probs.size(); j++) { double p = probs[j] / sump; if (maxp < p) { maxp = p; } probs[j] = p; } if (maxp > CONV_THRESHOLD || i >= ITERATION_LIMIT) { break; } } } return probs; } } // namespace langdetectpp::detection
27.019231
84
0.554211
[ "vector" ]
e6cf5cf4fd8efde026509e4ce0358ff4f2525ae0
7,684
cpp
C++
fibers/io.cpp
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
33
2018-12-12T20:05:06.000Z
2021-09-26T13:30:16.000Z
fibers/io.cpp
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
5
2019-04-25T11:34:43.000Z
2021-11-14T04:35:37.000Z
fibers/io.cpp
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
15
2018-12-21T22:44:59.000Z
2021-08-29T10:30:25.000Z
#include "io.h" void printSurfVTK(Mesh *mesh, std::ostream &out){ out << "# vtk DataFile Version 3.0\n" "Generated by MFEM\n" "ASCII\n" "DATASET UNSTRUCTURED_GRID\n"; int NumOfVertices=mesh->GetNV(); int spaceDim=3; out << "POINTS " << NumOfVertices << " double\n"; for (int i = 0; i < NumOfVertices; i++) { const double* coord=mesh->GetVertex(i); for(int j=0; j<spaceDim; j++){ out << coord[j] << " "; } out << '\n'; } int NumOfElements=mesh->GetNBE(); int size = 0; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetBdrElement(i); size += ele->GetNVertices() + 1; } out << "CELLS " << NumOfElements << ' ' << size << '\n'; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetBdrElement(i); const int *v = ele->GetVertices(); const int nv = ele->GetNVertices(); out << nv; for (int j = 0; j < nv; j++) { out << ' ' << v[j]; } out << '\n'; } out << "CELL_TYPES " << NumOfElements << '\n'; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetBdrElement(i); int vtk_cell_type = 5; { switch (ele->GetGeometryType()) { case Geometry::TRIANGLE: vtk_cell_type = 5; break; case Geometry::SQUARE: vtk_cell_type = 9; break; case Geometry::TETRAHEDRON: vtk_cell_type = 10; break; case Geometry::CUBE: vtk_cell_type = 12; break; } } out << vtk_cell_type << '\n'; } // write attributes out << "CELL_DATA " << NumOfElements << '\n' << "SCALARS material int\n" << "LOOKUP_TABLE default\n"; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetBdrElement(i); out << ele->GetAttribute() << '\n'; } out.flush(); } void printSurf4SurfVTK(Mesh *mesh, std::ostream &out){ out << "# vtk DataFile Version 3.0\n" "Generated by MFEM\n" "ASCII\n" "DATASET UNSTRUCTURED_GRID\n"; int NumOfVertices=mesh->GetNV(); int spaceDim=3; out << "POINTS " << NumOfVertices << " double\n"; for (int i = 0; i < NumOfVertices; i++) { const double* coord=mesh->GetVertex(i); for(int j=0; j<spaceDim; j++){ out << coord[j] << " "; } out << '\n'; } int NumOfElements=mesh->GetNE(); int size = 0; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetElement(i); size += ele->GetNVertices() + 1; } out << "CELLS " << NumOfElements << ' ' << size << '\n'; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetElement(i); const int *v = ele->GetVertices(); const int nv = ele->GetNVertices(); out << nv; for (int j = 0; j < nv; j++) { out << ' ' << v[j]; } out << '\n'; } out << "CELL_TYPES " << NumOfElements << '\n'; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetElement(i); int vtk_cell_type = 5; { switch (ele->GetGeometryType()) { case Geometry::TRIANGLE: vtk_cell_type = 5; break; case Geometry::SQUARE: vtk_cell_type = 9; break; case Geometry::TETRAHEDRON: vtk_cell_type = 10; break; case Geometry::CUBE: vtk_cell_type = 12; break; } } out << vtk_cell_type << '\n'; } // write attributes out << "CELL_DATA " << NumOfElements << '\n' << "SCALARS material int\n" << "LOOKUP_TABLE default\n"; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetElement(i); out << ele->GetAttribute() << '\n'; } out.flush(); } void printFiberVTK(Mesh *mesh, vector<Vector>& fiber_vecs, std::ostream &out){ out << "# vtk DataFile Version 3.0\n" "Generated by MFEM\n" "ASCII\n" "DATASET UNSTRUCTURED_GRID\n"; int NumOfVertices=mesh->GetNV(); int spaceDim=3; out << "POINTS " << NumOfVertices << " double\n"; for (int i = 0; i < NumOfVertices; i++) { const double* coord=mesh->GetVertex(i); for(int j=0; j<spaceDim; j++){ out << coord[j] << " "; } out << '\n'; } int NumOfElements=mesh->GetNE(); int size = 0; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetElement(i); size += ele->GetNVertices() + 1; } out << "CELLS " << NumOfElements << ' ' << size << '\n'; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetElement(i); const int *v = ele->GetVertices(); const int nv = ele->GetNVertices(); out << nv; for (int j = 0; j < nv; j++) { out << ' ' << v[j]; } out << '\n'; } out << "CELL_TYPES " << NumOfElements << '\n'; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetElement(i); int vtk_cell_type = 5; { switch (ele->GetGeometryType()) { case Geometry::TRIANGLE: vtk_cell_type = 5; break; case Geometry::SQUARE: vtk_cell_type = 9; break; case Geometry::TETRAHEDRON: vtk_cell_type = 10; break; case Geometry::CUBE: vtk_cell_type = 12; break; } } out << vtk_cell_type << '\n'; } // write point data MFEM_ASSERT(fiber_vecs.size()==(unsigned)NumOfVertices, "Size of fiber vector should equal to size of points"); out << "POINT_DATA " << NumOfVertices<< "\n" << "VECTORS fiber double\n"; for (int i = 0; i < NumOfVertices; i++) { fiber_vecs[i].Print(out, 10); } out << "\n"; // write attributes out << "CELL_DATA " << NumOfElements << '\n' << "SCALARS material int\n" << "LOOKUP_TABLE default\n"; for (int i = 0; i < NumOfElements; i++) { const Element *ele = mesh->GetElement(i); out << ele->GetAttribute() << '\n'; } out.flush(); } void printAnatomy(vector<anatomy>& anatVectors, filerheader& header, std::ostream &out){ // Print out the anatomy file header out << "anatomy FILEHEADER { \n" << "datatype = VARRECORDASCII;\n" << "nfiles = 1; \n" << "nrecord = " << header.nrecord << "; \n" << " nfields = 8; \n" << " lrec = 80; \n" << " endian_key = 875770417; \n" << " field_names = gid cellType sigma11 sigma12 sigma13 sigma22 sigma23 sigma33; \n" << " field_types = u u f f f f f f; \n" << " field_units = 1 1 mS/mm mS/mm mS/mm mS/mm mS/mm mS/mm; \n" << " nx = "<< header.nx<<"; \n" << " ny = "<< header.ny<<"; \n" << " nz = "<< header.nz<<"; \n" << " dx = "<< header.dx<<"; \n" << " dy = "<< header.dy<<"; \n" << " dz = "<< header.dz<<"; \n" << " offset_x = "<< header.offset_x<<"; \n" << " offset_y = "<< header.offset_y<<"; \n" << " offset_z = "<< header.offset_z<<"; \n" << "} \n\n"; for(unsigned i=0; i<anatVectors.size(); i++){ anatomy anat=anatVectors[i]; out << " " << anat.gid << " " << anat.celltype << " "; for(int j=0; j<6; j++){ out << anat.sigma[j] << " "; } out << endl; } }
28.671642
114
0.485424
[ "mesh", "geometry", "vector" ]
e6cfdf8effbcceae5a6ea0050f84afae599bf8ce
17,547
cpp
C++
gsa/wit/COIN/Clp/ClpDualRowSteepest.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
1
2019-10-25T05:25:23.000Z
2019-10-25T05:25:23.000Z
gsa/wit/COIN/Clp/ClpDualRowSteepest.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
2
2019-09-04T17:34:59.000Z
2020-09-16T08:10:57.000Z
gsa/wit/COIN/Clp/ClpDualRowSteepest.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
18
2019-07-22T19:01:25.000Z
2022-03-03T15:36:11.000Z
// Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. #include "CoinPragma.hpp" #include "ClpSimplex.hpp" #include "ClpDualRowSteepest.hpp" #include "CoinIndexedVector.hpp" #include "ClpFactorization.hpp" #include "CoinHelperFunctions.hpp" #include <cstdio> //############################################################################# // Constructors / Destructor / Assignment //############################################################################# //------------------------------------------------------------------- // Default Constructor //------------------------------------------------------------------- ClpDualRowSteepest::ClpDualRowSteepest (int mode) : ClpDualRowPivot(), state_(-1), mode_(mode), weights_(NULL), infeasible_(NULL), alternateWeights_(NULL), savedWeights_(NULL) { type_=2+64*mode; } //------------------------------------------------------------------- // Copy constructor //------------------------------------------------------------------- ClpDualRowSteepest::ClpDualRowSteepest (const ClpDualRowSteepest & rhs) : ClpDualRowPivot(rhs) { state_=rhs.state_; mode_ = rhs.mode_; model_ = rhs.model_; if (rhs.infeasible_) { infeasible_= new CoinIndexedVector(rhs.infeasible_); } else { infeasible_=NULL; } if (rhs.weights_) { assert(model_); int number = model_->numberRows(); weights_= new double[number]; ClpDisjointCopyN(rhs.weights_,number,weights_); } else { weights_=NULL; } if (rhs.alternateWeights_) { alternateWeights_= new CoinIndexedVector(rhs.alternateWeights_); } else { alternateWeights_=NULL; } if (rhs.savedWeights_) { savedWeights_= new CoinIndexedVector(rhs.savedWeights_); } else { savedWeights_=NULL; } } //------------------------------------------------------------------- // Destructor //------------------------------------------------------------------- ClpDualRowSteepest::~ClpDualRowSteepest () { delete [] weights_; delete infeasible_; delete alternateWeights_; delete savedWeights_; } //---------------------------------------------------------------- // Assignment operator //------------------------------------------------------------------- ClpDualRowSteepest & ClpDualRowSteepest::operator=(const ClpDualRowSteepest& rhs) { if (this != &rhs) { ClpDualRowPivot::operator=(rhs); state_=rhs.state_; mode_ = rhs.mode_; model_ = rhs.model_; delete [] weights_; delete infeasible_; delete alternateWeights_; delete savedWeights_; if (rhs.infeasible_!=NULL) { infeasible_= new CoinIndexedVector(rhs.infeasible_); } else { infeasible_=NULL; } if (rhs.weights_!=NULL) { assert(model_); int number = model_->numberRows(); weights_= new double[number]; ClpDisjointCopyN(rhs.weights_,number,weights_); } else { weights_=NULL; } if (rhs.alternateWeights_!=NULL) { alternateWeights_= new CoinIndexedVector(rhs.alternateWeights_); } else { alternateWeights_=NULL; } if (rhs.savedWeights_!=NULL) { savedWeights_= new CoinIndexedVector(rhs.savedWeights_); } else { savedWeights_=NULL; } } return *this; } // Returns pivot row, -1 if none int ClpDualRowSteepest::pivotRow() { assert(model_); int i,iRow; double * infeas = infeasible_->denseVector(); double largest=1.0e-50; int * index = infeasible_->getIndices(); int number = infeasible_->getNumElements(); const int * pivotVariable =model_->pivotVariable(); int chosenRow=-1; int lastPivotRow = model_->pivotRow(); double tolerance=model_->currentPrimalTolerance(); // we can't really trust infeasibilities if there is primal error // this coding has to mimic coding in checkPrimalSolution double error = min(1.0e-3,model_->largestPrimalError()); // allow tolerance at least slightly bigger than standard tolerance = tolerance + error; tolerance *= tolerance; // as we are using squares double * solution = model_->solutionRegion(); double * lower = model_->lowerRegion(); double * upper = model_->upperRegion(); // do last pivot row one here //#define COLUMN_BIAS 4.0 //#define FIXED_BIAS 10.0 if (lastPivotRow>=0) { #ifdef COLUMN_BIAS int numberColumns = model_->numberColumns(); #endif int iPivot=pivotVariable[lastPivotRow]; double value = solution[iPivot]; double lower = model_->lower(iPivot); double upper = model_->upper(iPivot); if (value>upper+tolerance) { value -= upper; value *= value; #ifdef COLUMN_BIAS if (iPivot<numberColumns) value *= COLUMN_BIAS; // bias towards columns #endif // store square in list if (infeas[lastPivotRow]) infeas[lastPivotRow] = value; // already there else infeasible_->quickAdd(lastPivotRow,value); } else if (value<lower-tolerance) { value -= lower; value *= value; #ifdef COLUMN_BIAS if (iPivot<numberColumns) value *= COLUMN_BIAS; // bias towards columns #endif // store square in list if (infeas[lastPivotRow]) infeas[lastPivotRow] = value; // already there else infeasible_->add(lastPivotRow,value); } else { // feasible - was it infeasible - if so set tiny if (infeas[lastPivotRow]) infeas[lastPivotRow] = 1.0e-100; } number = infeasible_->getNumElements(); } for (i=0;i<number;i++) { iRow = index[i]; double value = infeas[iRow]; if (value>largest*weights_[iRow]&&value>tolerance) { // make last pivot row last resort choice if (iRow==lastPivotRow) { if (value*1.0e-10<largest*weights_[iRow]) continue; else value *= 1.0e-10; } int iSequence = pivotVariable[iRow]; if (!model_->flagged(iSequence)) { //#define CLP_DEBUG 1 #ifdef CLP_DEBUG double value2=0.0; if (solution[iSequence]>upper[iSequence]+tolerance) value2=solution[iSequence]-upper[iSequence]; else if (solution[iSequence]<lower[iSequence]-tolerance) value2=solution[iSequence]-lower[iSequence]; assert(fabs(value2*value2-infeas[iRow])<1.0e-8*min(value2*value2,infeas[iRow])); #endif if (solution[iSequence]>upper[iSequence]+tolerance|| solution[iSequence]<lower[iSequence]-tolerance) { chosenRow=iRow; largest=value/weights_[iRow]; } } } } return chosenRow; } #define TRY_NORM 1.0e-4 // Updates weights void ClpDualRowSteepest::updateWeights(CoinIndexedVector * input, CoinIndexedVector * spare, CoinIndexedVector * updatedColumn) { // clear other region alternateWeights_->clear(); double norm = 0.0; double * work = input->denseVector(); int number = input->getNumElements(); int * which = input->getIndices(); double * work2 = spare->denseVector(); int * which2 = spare->getIndices(); double * work3 = alternateWeights_->denseVector(); int * which3 = alternateWeights_->getIndices(); int i; #if CLP_DEBUG>2 // Very expensive debug { int numberRows = model_->numberRows(); CoinIndexedVector * temp = new CoinIndexedVector(); temp->reserve(numberRows+ model_->factorization()->maximumPivots()); double * array = alternateWeights_->denseVector(); int * which = alternateWeights_->getIndices(); for (i=0;i<numberRows;i++) { double value=0.0; array[i] = 1.0; which[0] = i; alternateWeights_->setNumElements(1); model_->factorization()->updateColumnTranspose(temp, alternateWeights_); int number = alternateWeights_->getNumElements(); int j; for (j=0;j<number;j++) { int iRow=which[j]; value+=array[iRow]*array[iRow]; array[iRow]=0.0; } alternateWeights_->setNumElements(0); if (fabs(weights_[i]-value)>1.0e-4) printf("%d old %g, true %g\n",i,weights_[i],value); } delete temp; } #endif for (i=0;i<number;i++) { int iRow = which[i]; double value = work[iRow]; norm += value*value; work2[iRow]=value; which2[i]=iRow; } spare->setNumElements(number); // ftran model_->factorization()->updateColumn(alternateWeights_,spare); // alternateWeights_ should still be empty int pivotRow = model_->pivotRow(); #ifdef CLP_DEBUG if ( model_->logLevel ( ) >4 && fabs(norm-weights_[pivotRow])>1.0e-3*(1.0+norm)) printf("on row %d, true weight %g, old %g\n", pivotRow,sqrt(norm),sqrt(weights_[pivotRow])); #endif // could re-initialize here (could be expensive) norm /= model_->alpha() * model_->alpha(); assert(norm); if (norm < TRY_NORM) norm = TRY_NORM; if (norm != 0.) { double multiplier = 2.0 / model_->alpha(); // look at updated column work = updatedColumn->denseVector(); number = updatedColumn->getNumElements(); which = updatedColumn->getIndices(); int nSave=0; for (i =0; i < number; i++) { int iRow = which[i]; double theta = work[iRow]; if (theta) { double devex = weights_[iRow]; work3[iRow]=devex; // save old which3[nSave++]=iRow; double value = work2[iRow]; devex += theta * (theta*norm+value * multiplier); if (devex < TRY_NORM) devex = TRY_NORM; weights_[iRow]=devex; } } #ifdef CLP_DEBUG assert(work3[pivotRow]&&work[pivotRow]); #endif alternateWeights_->setNumElements(nSave); if (norm < TRY_NORM) norm = TRY_NORM; weights_[pivotRow] = norm; } spare->clear(); #ifdef CLP_DEBUG spare->checkClear(); #endif } /* Updates primal solution (and maybe list of candidates) Uses input vector which it deletes Computes change in objective function */ void ClpDualRowSteepest::updatePrimalSolution( CoinIndexedVector * primalUpdate, double primalRatio, double & objectiveChange) { double * work = primalUpdate->denseVector(); int number = primalUpdate->getNumElements(); int * which = primalUpdate->getIndices(); int i; double changeObj=0.0; double tolerance=model_->currentPrimalTolerance(); const int * pivotVariable = model_->pivotVariable(); double * infeas = infeasible_->denseVector(); int pivotRow = model_->pivotRow(); double * solution = model_->solutionRegion(); #ifdef COLUMN_BIAS int numberColumns = model_->numberColumns(); #endif for (i=0;i<number;i++) { int iRow=which[i]; int iPivot=pivotVariable[iRow]; double value = solution[iPivot]; double cost = model_->cost(iPivot); double change = primalRatio*work[iRow]; value -= change; changeObj -= change*cost; solution[iPivot] = value; double lower = model_->lower(iPivot); double upper = model_->upper(iPivot); // But if pivot row then use value of incoming // Although it is safer to recompute before next selection // in case something odd happens if (iRow==pivotRow) { iPivot = model_->sequenceIn(); lower = model_->lower(iPivot); upper = model_->upper(iPivot); value = model_->valueIncomingDual(); } if (value<lower-tolerance) { value -= lower; value *= value; #ifdef COLUMN_BIAS if (iPivot<numberColumns) value *= COLUMN_BIAS; // bias towards columns #endif #ifdef FIXED_BIAS if (lower==upper) value *= FIXED_BIAS; // bias towards taking out fixed variables #endif // store square in list if (infeas[iRow]) infeas[iRow] = value; // already there else infeasible_->quickAdd(iRow,value); } else if (value>upper+tolerance) { value -= upper; value *= value; #ifdef COLUMN_BIAS if (iPivot<numberColumns) value *= COLUMN_BIAS; // bias towards columns #endif #ifdef FIXED_BIAS if (lower==upper) value *= FIXED_BIAS; // bias towards taking out fixed variables #endif // store square in list if (infeas[iRow]) infeas[iRow] = value; // already there else infeasible_->quickAdd(iRow,value); } else { // feasible - was it infeasible - if so set tiny if (infeas[iRow]) infeas[iRow] = 1.0e-100; } work[iRow]=0.0; } primalUpdate->setNumElements(0); objectiveChange += changeObj; } /* Saves any weights round factorization as pivot rows may change 1) before factorization 2) after factorization 3) just redo infeasibilities 4) restore weights */ void ClpDualRowSteepest::saveWeights(ClpSimplex * model,int mode) { // alternateWeights_ is defined as indexed but is treated oddly model_ = model; int numberRows = model_->numberRows(); int numberColumns = model_->numberColumns(); const int * pivotVariable = model_->pivotVariable(); int i; if (mode==1&&weights_) { alternateWeights_->clear(); // change from row numbers to sequence numbers int * which = alternateWeights_->getIndices(); for (i=0;i<numberRows;i++) { int iPivot=pivotVariable[i]; which[i]=iPivot; } state_=1; } else if (mode==2||mode==4||mode==5) { // restore if (!weights_||state_==-1||mode==5) { // initialize weights delete [] weights_; delete alternateWeights_; weights_ = new double[numberRows]; alternateWeights_ = new CoinIndexedVector(); // enough space so can use it for factorization alternateWeights_->reserve(numberRows+ model_->factorization()->maximumPivots()); if (!mode_||mode==5) { // initialize to 1.0 (can we do better?) for (i=0;i<numberRows;i++) { weights_[i]=1.0; } } else { CoinIndexedVector * temp = new CoinIndexedVector(); temp->reserve(numberRows+ model_->factorization()->maximumPivots()); double * array = alternateWeights_->denseVector(); int * which = alternateWeights_->getIndices(); for (i=0;i<numberRows;i++) { double value=0.0; array[i] = 1.0; which[0] = i; alternateWeights_->setNumElements(1); model_->factorization()->updateColumnTranspose(temp, alternateWeights_); int number = alternateWeights_->getNumElements(); int j; for (j=0;j<number;j++) { int iRow=which[j]; value+=array[iRow]*array[iRow]; array[iRow]=0.0; } alternateWeights_->setNumElements(0); weights_[i] = value; } delete temp; } // create saved weights (not really indexedvector) savedWeights_ = new CoinIndexedVector(); savedWeights_->reserve(numberRows); double * array = savedWeights_->denseVector(); int * which = savedWeights_->getIndices(); for (i=0;i<numberRows;i++) { array[i]=weights_[i]; which[i]=pivotVariable[i]; } } else { int * which = alternateWeights_->getIndices(); if (mode!=4) { // save memcpy(savedWeights_->getIndices(),which, numberRows*sizeof(int)); memcpy(savedWeights_->denseVector(),weights_, numberRows*sizeof(double)); } else { // restore memcpy(which,savedWeights_->getIndices(), numberRows*sizeof(int)); memcpy(weights_,savedWeights_->denseVector(), numberRows*sizeof(double)); } // restore (a bit slow - but only every re-factorization) double * array = new double[numberRows+numberColumns]; for (i=0;i<numberRows;i++) { int iSeq=which[i]; array[iSeq]=weights_[i]; } for (i=0;i<numberRows;i++) { int iPivot=pivotVariable[i]; weights_[i]=array[iPivot]; if (weights_[i]<TRY_NORM) weights_[i] = TRY_NORM; // may need to check more } delete [] array; } state_=0; // set up infeasibilities if (!infeasible_) { infeasible_ = new CoinIndexedVector(); infeasible_->reserve(numberRows); } } if (mode>=2) { infeasible_->clear(); int iRow; const int * pivotVariable = model_->pivotVariable(); double tolerance=model_->currentPrimalTolerance(); for (iRow=0;iRow<numberRows;iRow++) { int iPivot=pivotVariable[iRow]; double value = model_->solution(iPivot); double lower = model_->lower(iPivot); double upper = model_->upper(iPivot); if (value<lower-tolerance) { value -= lower; value *= value; #ifdef COLUMN_BIAS if (iPivot<numberColumns) value *= COLUMN_BIAS; // bias towards columns #endif #ifdef FIXED_BIAS if (lower==upper) value *= FIXED_BIAS; // bias towards taking out fixed variables #endif // store square in list infeasible_->quickAdd(iRow,value); } else if (value>upper+tolerance) { value -= upper; value *= value; #ifdef COLUMN_BIAS if (iPivot<numberColumns) value *= COLUMN_BIAS; // bias towards columns #endif #ifdef FIXED_BIAS if (lower==upper) value *= FIXED_BIAS; // bias towards taking out fixed variables #endif // store square in list infeasible_->quickAdd(iRow,value); } } } } // Gets rid of last update void ClpDualRowSteepest::unrollWeights() { double * saved = alternateWeights_->denseVector(); int number = alternateWeights_->getNumElements(); int * which = alternateWeights_->getIndices(); int i; for (i=0;i<number;i++) { int iRow = which[i]; weights_[iRow]=saved[iRow]; saved[iRow]=0.0; } alternateWeights_->setNumElements(0); } //------------------------------------------------------------------- // Clone //------------------------------------------------------------------- ClpDualRowPivot * ClpDualRowSteepest::clone(bool CopyData) const { if (CopyData) { return new ClpDualRowSteepest(*this); } else { return new ClpDualRowSteepest(); } } // Gets rid of all arrays void ClpDualRowSteepest::clearArrays() { delete [] weights_; weights_=NULL; delete infeasible_; infeasible_ = NULL; delete alternateWeights_; alternateWeights_ = NULL; delete savedWeights_; savedWeights_ = NULL; state_ =-1; }
29.196339
81
0.632758
[ "vector", "model" ]
e6d5f7879d133bf46408dc61a5fc1e4cf9596247
195
hpp
C++
src/board/emulator/EmulatorBoard.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
src/board/emulator/EmulatorBoard.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
4
2022-03-13T23:07:12.000Z
2022-03-13T23:10:09.000Z
src/board/emulator/EmulatorBoard.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <common/Board.hpp> class EmulatorBoard : public Board { public: EmulatorBoard(); ~EmulatorBoard() override; }; /* class EmulatorBoard */
12.1875
34
0.671795
[ "vector" ]
5c7b5353a84b5c0d3cd92da65eb687b89cf95b62
3,097
cpp
C++
Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/MultiLineTextEditHandler.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/MultiLineTextEditHandler.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/MultiLineTextEditHandler.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "MultiLineTextEditHandler.h" #include <AzToolsFramework/Debug/TraceContext.h> namespace AzToolsFramework { QWidget* MultiLineTextEditHandler::CreateGUI(QWidget* parent) { GrowTextEdit* textEdit = aznew GrowTextEdit(parent); connect(textEdit, &GrowTextEdit::textChanged, this, [textEdit]() { EBUS_EVENT(AzToolsFramework::PropertyEditorGUIMessages::Bus, RequestWrite, textEdit); }); connect(textEdit, &GrowTextEdit::EditCompleted, this, [textEdit]() { AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&PropertyEditorGUIMessages::Bus::Handler::OnEditingFinished, textEdit); }); return textEdit; } AZ::u32 MultiLineTextEditHandler::GetHandlerName() const { return AZ_CRC("MultiLineEdit", 0xf5d93777); } bool MultiLineTextEditHandler::AutoDelete() const { return true; } void MultiLineTextEditHandler::ConsumeAttribute(GrowTextEdit* GUI, AZ::u32 attrib, AzToolsFramework::PropertyAttributeReader* attrValue, const char* debugName) { AZ_TraceContext("Attribute name", debugName); if (attrib == AZ_CRC("PlaceholderText", 0xa23ec278)) { AZStd::string placeholderText; if (attrValue->Read<AZStd::string>(placeholderText)) { GUI->setPlaceholderText(placeholderText.c_str()); } else { AZ_WarningOnce("AzToolsFramework", false, "Failed to read 'PlaceholderText' attribute from property '%s' into multi-line text field.", debugName); } } else if (attrib == AZ::Edit::Attributes::ReadOnly) { bool value; if (attrValue->Read<bool>(value)) { GUI->setReadOnly(value); } else { AZ_WarningOnce("AzToolsFramework", false, "Failed to read 'ReadOnly' attribute from property '%s' into multi-line text field.", debugName); } } } void MultiLineTextEditHandler::WriteGUIValuesIntoProperty(size_t /*index*/, GrowTextEdit* GUI, property_t& instance, AzToolsFramework::InstanceDataNode* /*node*/) { instance = GUI->GetText(); } bool MultiLineTextEditHandler::ReadValuesIntoGUI(size_t /*index*/, GrowTextEdit* GUI, const property_t& instance, AzToolsFramework::InstanceDataNode* /*node*/) { GUI->blockSignals(true); GUI->SetText(instance); GUI->blockSignals(false); return true; } void RegisterMultiLineEditHandler() { EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew MultiLineTextEditHandler()); } } #include "UI/PropertyEditor/moc_MultiLineTextEditHandler.cpp"
34.411111
166
0.638683
[ "3d" ]
5c7e25042c74fb8a82feafa44090b3103bbd915b
6,508
cpp
C++
libraries/hvvr/raycaster/scene_update.cpp
wschnepp/HVVRText3D
737089f0027a93db489675a93e4cf874e107319c
[ "BSD-3-Clause" ]
1
2019-06-05T20:33:49.000Z
2019-06-05T20:33:49.000Z
libraries/hvvr/raycaster/scene_update.cpp
wschnepp/HVVRText3D
737089f0027a93db489675a93e4cf874e107319c
[ "BSD-3-Clause" ]
null
null
null
libraries/hvvr/raycaster/scene_update.cpp
wschnepp/HVVRText3D
737089f0027a93db489675a93e4cf874e107319c
[ "BSD-3-Clause" ]
1
2021-12-06T14:09:13.000Z
2021-12-06T14:09:13.000Z
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "bvh_node.h" #include "debug.h" #include "gpu_context.h" #include "gpu_scene_state.h" #include "material.h" #include "model.h" #include "raycaster.h" #include "vector_math.h" namespace hvvr { // convert from per-model data to global arrays void Raycaster::buildScene() { uint32_t modelCount = uint32_t(_models.size()); if (modelCount == 0) { _trianglesShade = std::vector<PrecomputedTriangleShade>(); _nodes = DynamicArray<BVHNode>(1); _materials = std::vector<SimpleMaterial>(); // Create a root node that points to nothing. _nodes[0].boxData.leafMask = 0xf; for (size_t i = 0; i < 5; i++) _nodes[0].boxData.leaf.triIndex[i] = 0; return; } // Count the number of objects we're going to have to allocate. uint32_t rootNodeCount = (modelCount + 1) / 3; { _vertexCount = 0; uint32_t triangleCount = 0; uint32_t nodeCount = rootNodeCount; uint32_t materialCount = 0; for (uint32_t modelIndex = 0; modelIndex < modelCount; modelIndex++) { const Model& model = *(_models[modelIndex]); const MeshData& meshData = model.getMesh(); _vertexCount += uint32_t(meshData.verts.size()); triangleCount += uint32_t(meshData.triShade.size()); nodeCount += uint32_t(meshData.nodes.size()); materialCount += uint32_t(meshData.materials.size()); } _trianglesShade = std::vector<PrecomputedTriangleShade>(triangleCount); _nodes = DynamicArray<BVHNode>(nodeCount); _materials = std::vector<SimpleMaterial>(materialCount); } // Allocate the views. std::vector<uint32_t> viewOffsets(_models.size()); uint32_t vertexOffset = 0; uint32_t triOffset = 0; uint32_t materialOffset = 0; uint32_t nodeOffset = rootNodeCount; for (uint32_t modelIndex = 0; modelIndex < modelCount; modelIndex++) { const Model& model = *(_models[modelIndex]); const MeshData& meshData = model.getMesh(); uint32_t materialCount = uint32_t(meshData.materials.size()); for (uint32_t n = 0; n < materialCount; n++) { _materials[materialOffset + n] = meshData.materials[n]; } uint32_t triCount = uint32_t(meshData.triShade.size()); for (uint32_t n = 0; n < triCount; n++) { PrecomputedTriangleShade& triShade = _trianglesShade[triOffset + n]; triShade = meshData.triShade[n]; triShade.indices[0] += vertexOffset; triShade.indices[1] += vertexOffset; triShade.indices[2] += vertexOffset; triShade.material += materialOffset; } // Initialize the BVH uint32_t nodeCount = uint32_t(meshData.nodes.size()); viewOffsets[modelIndex] = nodeOffset; for (uint32_t n = 0; n < nodeCount; n++) { const TopologyNode& topoNode = meshData.nodes[n]; BVHNode& node = _nodes[nodeOffset + n]; node.boxData.leafMask = topoNode.leafMask; node.boxData.leaf.triIndex[0] = triOffset + topoNode.getFirstTriangleIndex(0); for (size_t k = 0; k < 4; k++) { if (topoNode.isLeaf(k)) node.boxData.leaf.triIndex[1 + k] = triOffset + topoNode.getBoundTriangleIndex(k); else node.boxData.children.offset[k] = topoNode.getChildOffset(k); } } vertexOffset += uint32_t(meshData.verts.size()); triOffset += triCount; materialOffset += materialCount; nodeOffset += nodeCount; } if (rootNodeCount > 0) { // Initialize the root nodes to link the sub-trees together. // We use a linear vector of child pointers initially because of the ease of access. std::vector<BVHNode*> children(rootNodeCount * 4); auto nextChild = children.data(); // Set the extra slots to nullptr (these will be empty leaves). for (size_t i = children.size() - _models.size() - (rootNodeCount - 1); i != 0; --i) *nextChild++ = nullptr; // Set the pointers to the fixup nodes. for (size_t i = 1, e = rootNodeCount; i < e; ++i) *nextChild++ = _nodes.data() + i; // Set the pointers to the entry points. for (auto viewOffset : viewOffsets) *nextChild++ = _nodes.data() + viewOffset; if (nextChild != children.data() + children.size()) fail("Didn't update all of the children."); // Convert the pointers in the children vector into offset in the actual fixup nodes. for (size_t i = 0; i < rootNodeCount; i++) { _nodes[i].boxData.leaf.triIndex[0] = 0; _nodes[i].boxData.leafMask = 0; for (size_t k = 0; k < 4; k++) { if (children[4 * i + k] == nullptr) { _nodes[i].boxData.leaf.triIndex[1 + k] = 0; _nodes[i].boxData.leafMask |= 1 << k; continue; } _nodes[i].boxData.children.offset[k] = uint32_t(children[4 * i + k] - (_nodes.data() + i)); } } } } void Raycaster::uploadScene() { GPUSceneState& gpuSceneState = _gpuContext->sceneState; gpuSceneState.updateMaterials(_materials.data(), _materials.size()); // if we update CUDA's copy of the scene, we must also call AnimateScene to supply the transforms gpuSceneState.setGeometry(*this); // TODO(anankervis): don't dynamically allocate memory here DynamicArray<matrix4x4> modelToWorld(_models.size()); for (size_t i = 0; i < _models.size(); ++i) modelToWorld[i] = matrix4x4(_models[i]->getTransform()); gpuSceneState.animate(modelToWorld.data(), modelToWorld.size()); gpuSceneState.updateLighting(*this); gpuSceneState.fetchUpdatedBVH(_nodes.data()); } void Raycaster::updateScene(double elapsedTime) { (void)elapsedTime; if (_sceneDirty) { // TODO(anankervis): commitTransforms() or Commmit on the Model class buildScene(); uploadScene(); _sceneDirty = false; } } } // namespace hvvr
36.357542
107
0.610018
[ "vector", "model" ]
5c85fdd4f45a40008c6eab6fb059d127a4a4240e
1,243
cpp
C++
Source/BackgroundComponent.cpp
Dezzles/ludumdare32
3cc85bd54466a0cca3d2d748b39250412b44ba9c
[ "MIT" ]
null
null
null
Source/BackgroundComponent.cpp
Dezzles/ludumdare32
3cc85bd54466a0cca3d2d748b39250412b44ba9c
[ "MIT" ]
null
null
null
Source/BackgroundComponent.cpp
Dezzles/ludumdare32
3cc85bd54466a0cca3d2d748b39250412b44ba9c
[ "MIT" ]
null
null
null
#include "BackgroundComponent.hpp" using namespace Math; BackgroundComponent::BackgroundComponent() { BackgroundSize_ = 40; } void BackgroundComponent::Initialise( Json::Value Params ) { Component::Initialise( Params ); REQUIRED_LOAD( Float, BackgroundSize, backgroundSize ); REQUIRED_LOAD( Float, GapShrink, gapShrink ); REQUIRED_LOAD( Float, Speed, speed ); } void BackgroundComponent::Copy( BackgroundComponent* Target, BackgroundComponent* Base ) { Component::Copy( Target, Base ); NAIVE_COPY( BackgroundSize ); NAIVE_COPY( Speed ); NAIVE_COPY( GapShrink ); } void BackgroundComponent::OnAttach() { std::vector<Sprite*> children = GetParentEntity()->GetComponentsByTypeAnyChild<Sprite>(); for ( unsigned int Idx = 0; Idx < children.size(); ++Idx ) { Entities_.push_back( children[ Idx ]->GetParentEntity() ); } } void BackgroundComponent::CreateMap() { } void BackgroundComponent::Update( float dt ) { for ( unsigned int Idx = 0; Idx < Entities_.size(); ++Idx ) { auto pos = Entities_[ Idx ]->LocalPosition(); float newX = pos.X() - dt * Speed_; if ( newX < -BackgroundSize_ * 0.5f ) newX += ( BackgroundSize_ - GapShrink_ ) * 3.0f; pos.SetX( newX ); Entities_[ Idx ]->SetLocalPosition( pos ); } }
23.45283
90
0.70716
[ "vector" ]
5c8f8b6c53ee7dbbbaae3854848b1db66122d592
13,009
cpp
C++
Abaqus/AbaqusModel.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
27
2020-06-25T06:34:52.000Z
2022-03-11T08:58:57.000Z
Abaqus/AbaqusModel.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
42
2020-06-15T18:40:57.000Z
2022-03-24T05:38:54.000Z
Abaqus/AbaqusModel.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
12
2020-06-27T13:58:57.000Z
2022-03-24T05:39:10.000Z
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "AbaqusModel.h" // in AbaqusImport.cpp bool szicmp(const char* sz1, const char* sz2); //----------------------------------------------------------------------------- AbaqusModel::AbaqusModel() { m_pPart = 0; m_pInst = 0; m_pStep = 0; } //----------------------------------------------------------------------------- AbaqusModel::~AbaqusModel() { // delete all instances list<INSTANCE*>::iterator ii; for (ii = m_Inst.begin(); ii != m_Inst.end(); ++ii) delete (*ii); m_Inst.clear(); m_pInst = 0; // delete all parts list<PART*>::iterator pi; for (pi = m_Part.begin(); pi != m_Part.end(); ++pi) delete (*pi); m_Part.clear(); m_pPart = 0; } //----------------------------------------------------------------------------- AbaqusModel::PART* AbaqusModel::CreatePart(const char* sz) { char szname[256] = { 0 }; if (sz == 0) { sprintf(szname, "Part%02d", (int)m_Part.size() + 1); } else strcpy(szname, sz); PART* pg = new PART; pg->SetName(szname); m_Part.push_back(pg); return pg; } //----------------------------------------------------------------------------- AbaqusModel::PART* AbaqusModel::FindPart(const char* sz) { list<PART*>::iterator pg; for (pg = m_Part.begin(); pg != m_Part.end(); ++pg) { PART* part = *pg; if (szicmp(part->GetName(), sz)) return part; } return 0; } //----------------------------------------------------------------------------- // add an instance AbaqusModel::INSTANCE* AbaqusModel::AddInstance() { // create a new instance m_pInst = new AbaqusModel::INSTANCE; m_Inst.push_back(m_pInst); return m_pInst; } //----------------------------------------------------------------------------- AbaqusModel::INSTANCE* AbaqusModel::FindInstance(const char* sz) { list<INSTANCE*>::iterator pg; for (pg = m_Inst.begin(); pg != m_Inst.end(); ++pg) { INSTANCE* pi = *pg; if (szicmp(pi->GetName(), sz)) return pi; } return 0; } // find a node set based on a name AbaqusModel::NODE_SET* AbaqusModel::FindNodeSet(const char* sznset) { list<AbaqusModel::PART*>::iterator it; for (it = m_Part.begin(); it != m_Part.end(); ++it) { AbaqusModel::PART& part = *(*it); map<string, NODE_SET>::iterator ns = part.FindNodeSet(sznset); if (ns != part.m_NSet.end()) { return &((*ns).second); } } return 0; } //----------------------------------------------------------------------------- // find a part with a particular element set AbaqusModel::ELEMENT_SET* AbaqusModel::FindElementSet(const char* szelemset) { list<AbaqusModel::PART*>::iterator it; for (it = m_Part.begin(); it != m_Part.end(); ++it) { AbaqusModel::PART& part = *(*it); list<AbaqusModel::ELEMENT_SET>::iterator ps = part.FindElementSet(szelemset); if (ps != part.m_ElSet.end()) { return &(*ps); } } return 0; } //----------------------------------------------------------------------------- AbaqusModel::SURFACE* AbaqusModel::FindSurface(const char* szname) { list<AbaqusModel::PART*>::iterator it; for (it = m_Part.begin(); it != m_Part.end(); ++it) { AbaqusModel::PART& part = *(*it); list<SURFACE>::iterator ps = part.FindSurface(szname); if (ps != part.m_Surf.end()) { return &(*ps); } } return 0; } //----------------------------------------------------------------------------- AbaqusModel::PART* AbaqusModel::GetActivePart(bool bcreate) { if ((m_pPart == 0) && bcreate) m_pPart = CreatePart(); return m_pPart; } //----------------------------------------------------------------------------- void AbaqusModel::ClearCurrentInstance() { m_pPart = 0; m_pInst = 0; } // Add a material AbaqusModel::MATERIAL* AbaqusModel::AddMaterial(const char* szname) { MATERIAL newmat; m_Mat.push_back(newmat); AbaqusModel::MATERIAL& pm = m_Mat.back(); return &pm; } // add a pressure load AbaqusModel::DSLOAD* AbaqusModel::AddPressureLoad(AbaqusModel::DSLOAD& p) { m_SLoads.push_back(p); return &(m_SLoads.back()); } // add a boundary condition AbaqusModel::BOUNDARY* AbaqusModel::AddBoundaryCondition(AbaqusModel::BOUNDARY& p) { m_Boundary.push_back(p); return &(m_Boundary.back()); } // add a step AbaqusModel::STEP* AbaqusModel::AddStep(const char* szname) { STEP step; if (szname) strcpy(step.szname, szname); else sprintf(step.szname, "Step-%d", (int)m_Step.size() + 1); step.dt0 = 0.1; step.time = 1.0; m_Step.push_back(step); m_pStep = &(m_Step.back()); return m_pStep; } // set the current step void AbaqusModel::SetCurrentStep(STEP* p) { m_pStep = p; } //============================================================================= //----------------------------------------------------------------------------- void AbaqusModel::PART::SetName(const char* sz) { strcpy(m_szname, sz); } //----------------------------------------------------------------------------- AbaqusModel::Tnode_itr AbaqusModel::PART::AddNode(AbaqusModel::NODE& n) { if (m_Node.size() == 0) { m_Node.push_back(n); return m_Node.begin(); } else { Tnode_itr p1 = m_Node.begin(); Tnode_itr p2 = --m_Node.end(); if (n.id < p1->id) { m_Node.insert(m_Node.begin(), n); return m_Node.begin(); } else if (n.id > p2->id) { m_Node.push_back(n); return --m_Node.end(); } else { if (n.id - p1->id < p2->id - n.id) { do { ++p1; } while (p1->id < n.id); return m_Node.insert(p1, n); } else { do { --p2; } while (p2->id > n.id); ++p2; return m_Node.insert(p2, n); } } } return m_Node.end(); } //----------------------------------------------------------------------------- AbaqusModel::Tnode_itr AbaqusModel::PART::FindNode(int id) { assert(!m_NLT.empty()); return m_NLT[id - m_ioff]; } list<AbaqusModel::SPRING>::iterator AbaqusModel::PART::AddSpring(AbaqusModel::SPRING& s) { m_Spring.push_back(s); return --m_Spring.end(); } //----------------------------------------------------------------------------- void AbaqusModel::PART::AddElement(AbaqusModel::ELEMENT& newElem) { int nid = newElem.id; if (nid >= (int)m_Elem.size()) { int oldSize = (int)m_Elem.size(); int newSize = nid + 1000; m_Elem.resize(newSize); for (int i = oldSize; i < newSize; ++i) m_Elem[i].id = -1; } m_Elem[nid] = newElem; } //----------------------------------------------------------------------------- vector<AbaqusModel::ELEMENT>::iterator AbaqusModel::PART::FindElement(int id) { return m_Elem.begin() + id; } //----------------------------------------------------------------------------- list<AbaqusModel::ELEMENT_SET>::iterator AbaqusModel::PART::FindElementSet(const char* szname) { size_t n = m_ElSet.size(); list<ELEMENT_SET>::iterator pe = m_ElSet.begin(); for (size_t i = 0; i<n; ++i, ++pe) if (strcmp(pe->szname, szname) == 0) return pe; return m_ElSet.end(); } //----------------------------------------------------------------------------- list<AbaqusModel::ELEMENT_SET>::iterator AbaqusModel::PART::AddElementSet(const char* szname) { ELEMENT_SET es; strcpy(es.szname, szname); m_ElSet.push_back(es); return --m_ElSet.end(); } //----------------------------------------------------------------------------- map<string, AbaqusModel::NODE_SET>::iterator AbaqusModel::PART::FindNodeSet(const char* szname) { map<string, AbaqusModel::NODE_SET>::iterator it = m_NSet.find(szname); return it; } //----------------------------------------------------------------------------- map<string, AbaqusModel::NODE_SET>::iterator AbaqusModel::PART::AddNodeSet(const char* szname) { NODE_SET ns; strcpy(ns.szname, szname); m_NSet[szname] = ns; return m_NSet.find(szname); } //----------------------------------------------------------------------------- list<AbaqusModel::SURFACE>::iterator AbaqusModel::PART::FindSurface(const char* szname) { size_t n = m_Surf.size(); list<SURFACE>::iterator ps = m_Surf.begin(); for (size_t i = 0; i<n; ++i, ++ps) if (strcmp(ps->szname, szname) == 0) return ps; return m_Surf.end(); } //----------------------------------------------------------------------------- // add a solid section list<AbaqusModel::SOLID_SECTION>::iterator AbaqusModel::PART::AddSolidSection(const char* szset, const char* szmat, const char* szorient) { SOLID_SECTION ss; strcpy(ss.szelset, szset); if (szmat) strcpy(ss.szmat, szmat); else ss.szmat[0] = 0; if (szorient) strcpy(ss.szorient, szorient); else ss.szorient[0] = 0; ss.part = this; m_Solid.push_back(ss); return --m_Solid.end(); } //----------------------------------------------------------------------------- list<AbaqusModel::SURFACE>::iterator AbaqusModel::PART::AddSurface(const char* szname) { SURFACE surf; strcpy(surf.szname, szname); m_Surf.push_back(surf); return --m_Surf.end(); } //----------------------------------------------------------------------------- bool AbaqusModel::PART::BuildNLT() { // make sure the NLT is empty if (!m_NLT.empty()) m_NLT.clear(); m_ioff = 0; if (m_Node.empty()) { assert(false); return false; } // find the lowest and highest node index int imin, imax; Tnode_itr it = m_Node.begin(); imin = imax = it->id; for (++it; it != m_Node.end(); ++it) { if (it->id < imin) imin = it->id; if (it->id > imax) imax = it->id; } // allocate NLT m_NLT.assign(imax - imin + 1, m_Node.end()); // fill the NLT for (it = m_Node.begin(); it != m_Node.end(); ++it) { m_NLT[it->id - imin] = it; } m_ioff = imin; return true; } //----------------------------------------------------------------------------- void AbaqusModel::PART::AddOrientation(const char* szname, const char* szdist) { Orientation o; strcpy(o.szname, szname); strcpy(o.szdist, szdist); m_Orient.push_back(o); } //----------------------------------------------------------------------------- AbaqusModel::Orientation* AbaqusModel::PART::FindOrientation(const char* szname) { if (szname == 0) return 0; list<Orientation>::iterator it; for (it = m_Orient.begin(); it != m_Orient.end(); ++it) { if (strcmp(it->szname, szname) == 0) return &(*it); } return 0; } //----------------------------------------------------------------------------- AbaqusModel::Distribution* AbaqusModel::PART::FindDistribution(const char* szname) { if (szname == 0) return 0; list<Distribution>::iterator it; for (it = m_Distr.begin(); it != m_Distr.end(); ++it) { if (strcmp(it->m_szname, szname) == 0) return &(*it); } return 0; } //============================================================================= AbaqusModel::INSTANCE::INSTANCE() { m_szname[0] = 0; m_pPart = 0; m_trans[0] = m_trans[1] = m_trans[2] = 0.0; m_rot[0] = 0; m_rot[1] = 0; m_rot[2] = 0; m_rot[3] = 0; m_rot[4] = 0; m_rot[5] = 0; m_rot[6] = 0; } //----------------------------------------------------------------------------- void AbaqusModel::INSTANCE::SetName(const char* sz) { strcpy(m_szname, sz); } //----------------------------------------------------------------------------- void AbaqusModel::INSTANCE::SetTranslation(double t[3]) { m_trans[0] = t[0]; m_trans[1] = t[1]; m_trans[2] = t[2]; } //----------------------------------------------------------------------------- void AbaqusModel::INSTANCE::GetTranslation(double t[3]) { t[0] = m_trans[0]; t[1] = m_trans[1]; t[2] = m_trans[2]; } //----------------------------------------------------------------------------- void AbaqusModel::INSTANCE::SetRotation(double t[7]) { m_rot[0] = t[0]; m_rot[1] = t[1]; m_rot[2] = t[2]; m_rot[3] = t[3]; m_rot[4] = t[4]; m_rot[5] = t[5]; m_rot[6] = t[6]; } //----------------------------------------------------------------------------- void AbaqusModel::INSTANCE::GetRotation(double t[7]) { t[0] = m_rot[0]; t[1] = m_rot[1]; t[2] = m_rot[2]; t[3] = m_rot[3]; t[4] = m_rot[4]; t[5] = m_rot[5]; t[6] = m_rot[6]; }
26.387424
137
0.53463
[ "vector", "solid" ]
5c9294a9f667e0315254d809b616b4c338db16c7
22,095
hpp
C++
include/mockturtle/algorithms/resyn_engines/xag_resyn_engines.hpp
mdsudara/mockturtle
129741e252a6b87d8cb8041c25655f1256e43c9a
[ "MIT" ]
1
2019-05-25T17:40:15.000Z
2019-05-25T17:40:15.000Z
include/mockturtle/algorithms/resyn_engines/xag_resyn_engines.hpp
mdsudara/mockturtle
129741e252a6b87d8cb8041c25655f1256e43c9a
[ "MIT" ]
2
2021-03-05T21:12:07.000Z
2021-03-06T18:42:52.000Z
include/mockturtle/algorithms/resyn_engines/xag_resyn_engines.hpp
mdsudara/mockturtle
129741e252a6b87d8cb8041c25655f1256e43c9a
[ "MIT" ]
null
null
null
/* mockturtle: C++ logic network library * Copyright (C) 2018-2021 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file xag_resyn_engines.hpp \brief Resynthesis by recursive decomposition for AIGs or XAGs. (based on ABC's implementation in `giaResub.c` by Alan Mishchenko) \author Siang-Yun Lee */ #pragma once #include "../../utils/index_list.hpp" #include "../../utils/stopwatch.hpp" #include <kitty/kitty.hpp> #include <fmt/format.h> #include <vector> #include <algorithm> #include <unordered_map> namespace mockturtle { struct xag_resyn_engine_params { /*! \brief Maximum size (number of gates) of the dependency circuit. */ uint32_t max_size{0u}; /*! \brief Whether to consider XOR gates as having the same cost as AND gates (i.e., using XAGs). */ bool use_xor{false}; /*! \brief Maximum number of binate divisors to be considered. */ uint32_t max_binates{50u}; }; struct xag_resyn_engine_stats { /*! \brief Time for finding 0-resub and collecting unate literals. */ stopwatch<>::duration time_unate{0}; /*! \brief Time for finding 1-resub. */ stopwatch<>::duration time_resub1{0}; /*! \brief Time for finding 2-resub. */ stopwatch<>::duration time_resub2{0}; /*! \brief Time for finding 3-resub. */ stopwatch<>::duration time_resub3{0}; /*! \brief Time for sorting unate literals and unate pairs. */ stopwatch<>::duration time_sort{0}; /*! \brief Time for collecting unate pairs. */ stopwatch<>::duration time_collect_pairs{0}; void report() const { fmt::print( "[i] 0-resub :{:>5.2f} secs\n", to_seconds( time_unate ) ); fmt::print( "[i] 1-resub :{:>5.2f} secs\n", to_seconds( time_resub1 ) ); fmt::print( "[i] 2-resub :{:>5.2f} secs\n", to_seconds( time_resub2 ) ); fmt::print( "[i] 3-resub :{:>5.2f} secs\n", to_seconds( time_resub3 ) ); fmt::print( "[i] sort :{:>5.2f} secs\n", to_seconds( time_sort ) ); fmt::print( "[i] collect pairs:{:>5.2f} secs\n", to_seconds( time_collect_pairs ) ); } }; /*! \brief Logic resynthesis engine for AIGs or XAGs. * * The algorithm is based on ABC's implementation in `giaResub.c` by Alan Mishchenko. * * Divisors are classified as positive unate (not overlapping with target offset), * negative unate (not overlapping with target onset), or binate (overlapping with * both onset and offset). Furthermore, pairs of binate divisors are combined with * an AND operation and considering all possible input polarities and again classified * as positive unate, negative unate or binate. Simple solutions of zero cost * (one unate divisor), one node (two unate divisors), two nodes (one unate divisor + * one unate pair), and three nodes (two unate pairs) are exhaustively examined. * When no simple solutions can be found, the algorithm heuristically chooses an unate * divisor or an unate pair to divide the target function with and recursively calls * itself to decompose the remainder function. */ template<class TT> class xag_resyn_engine { public: using stats = xag_resyn_engine_stats; using params = xag_resyn_engine_params; using index_list_t = xag_index_list; using truth_table_t = TT; private: struct and_pair { and_pair( uint32_t l1, uint32_t l2 ) : lit1( l1 < l2 ? l1 : l2 ), lit2( l1 < l2 ? l2 : l1 ) { } bool operator==( and_pair const& other ) const { return lit1 == other.lit1 && lit2 == other.lit2; } uint32_t lit1, lit2; }; struct pair_hash { std::size_t operator()( and_pair const& p ) const { return std::hash<uint64_t>{}( (uint64_t)p.lit1 << 32 | (uint64_t)p.lit2 ); } }; public: explicit xag_resyn_engine( TT const& target, TT const& care, stats& st, params const& ps = {} ) : divisors( { ~target & care, target & care } ), st( st ), ps( ps ) { } void add_divisor( TT const& tt ) { assert( tt.num_bits() == divisors[0].num_bits() ); divisors.emplace_back( tt ); } template<class node_type, class truth_table_storage_type> void add_divisor( node_type const& node, truth_table_storage_type const& tts ) { add_divisor( tts[node] ); } template<class iterator_type, class truth_table_storage_type> void add_divisors( iterator_type begin, iterator_type end, truth_table_storage_type const& tts ) { while ( begin != end ) { add_divisor( tts[*begin] ); ++begin; } } std::optional<index_list_t> operator()() { return compute_function(); } template<class iterator_type, class truth_table_storage_type> std::optional<index_list_t> operator()( iterator_type begin, iterator_type end, truth_table_storage_type const& tts ) { add_divisors( begin, end, tts ); return compute_function(); } private: std::optional<index_list_t> compute_function() { index_list.add_inputs( divisors.size() - 2 ); auto const lit = compute_function_rec( ps.max_size ); if ( lit ) { assert( index_list.num_gates() <= ps.max_size ); index_list.add_output( *lit ); return index_list; } return std::nullopt; } std::optional<uint32_t> compute_function_rec( uint32_t num_inserts ) { /* try 0-resub and collect unate literals */ auto const res0 = call_with_stopwatch( st.time_unate, [&]() { return find_one_unate(); }); if ( res0 ) { return *res0; } if ( num_inserts == 0u ) { return std::nullopt; } /* sort unate literals and try 1-resub */ call_with_stopwatch( st.time_sort, [&]() { sort_unate_lits( pos_unate_lits, pos_lit_scores, 1 ); sort_unate_lits( neg_unate_lits, neg_lit_scores, 0 ); }); auto const res1or = call_with_stopwatch( st.time_resub1, [&]() { return find_div_div( pos_unate_lits, pos_lit_scores, 1 ); }); if ( res1or ) { return *res1or; } auto const res1and = call_with_stopwatch( st.time_resub1, [&]() { return find_div_div( neg_unate_lits, neg_lit_scores, 0 ); }); if ( res1and ) { return *res1and; } if ( binate_divs.size() > ps.max_binates ) { binate_divs.resize( ps.max_binates ); } if ( ps.use_xor ) { auto const res1xor = find_xor(); if ( res1xor ) { return *res1xor; } } if ( num_inserts == 1u ) { return std::nullopt; } /* collect and sort unate pairs, then try 2- and 3-resub */ call_with_stopwatch( st.time_collect_pairs, [&]() { collect_unate_pairs(); }); call_with_stopwatch( st.time_sort, [&]() { sort_unate_pairs( pos_unate_pairs, pos_pair_scores, 1 ); sort_unate_pairs( neg_unate_pairs, neg_pair_scores, 0 ); }); auto const res2or = call_with_stopwatch( st.time_resub2, [&]() { return find_div_pair( pos_unate_lits, pos_unate_pairs, pos_lit_scores, pos_pair_scores, 1 ); }); if ( res2or ) { return *res2or; } auto const res2and = call_with_stopwatch( st.time_resub2, [&]() { return find_div_pair( neg_unate_lits, neg_unate_pairs, neg_lit_scores, neg_pair_scores, 0 ); }); if ( res2and ) { return *res2and; } if ( num_inserts >= 3u ) { auto const res3or = call_with_stopwatch( st.time_resub3, [&]() { return find_pair_pair( pos_unate_pairs, pos_pair_scores, 1 ); }); if ( res3or ) { return *res3or; } auto const res3and = call_with_stopwatch( st.time_resub3, [&]() { return find_pair_pair( neg_unate_pairs, neg_pair_scores, 0 ); }); if ( res3and ) { return *res3and; } } /* choose something to divide and recursive call on the remainder */ uint32_t on_off_div, on_off_pair; uint32_t score_div = 0, score_pair = 0; if ( pos_unate_lits.size() > 0 ) { on_off_div = 1; /* use pos_lit */ score_div = pos_lit_scores[pos_unate_lits[0]]; if ( neg_unate_lits.size() > 0 && neg_lit_scores[neg_unate_lits[0]] > pos_lit_scores[pos_unate_lits[0]] ) { on_off_div = 0; /* use neg_lit */ score_div = neg_lit_scores[neg_unate_lits[0]]; } } else if ( neg_unate_lits.size() > 0 ) { on_off_div = 0; /* use neg_lit */ score_div = neg_lit_scores[neg_unate_lits[0]]; } if ( num_inserts >= 3u ) { if ( pos_unate_pairs.size() > 0 ) { on_off_pair = 1; /* use pos_pair */ score_pair = pos_pair_scores[pos_unate_pairs[0]]; if ( neg_unate_pairs.size() > 0 && neg_pair_scores[neg_unate_pairs[0]] > pos_pair_scores[pos_unate_pairs[0]] ) { on_off_pair = 0; /* use neg_pair */ score_pair = neg_pair_scores[neg_unate_pairs[0]]; } } else if ( neg_unate_pairs.size() > 0 ) { on_off_pair = 0; /* use neg_pair */ score_pair = neg_pair_scores[neg_unate_pairs[0]]; } } if ( score_div > score_pair / 2 ) /* divide with a divisor */ { /* if using pos_lit (on_off_div = 1), modify on-set and use an OR gate on top; if using neg_lit (on_off_div = 0), modify off-set and use an AND gate on top */ uint32_t const lit = on_off_div ? pos_unate_lits[0] : neg_unate_lits[0]; divisors[on_off_div] &= lit & 0x1 ? divisors[lit >> 1] : ~divisors[lit >> 1]; auto const res_remain_div = compute_function_rec( num_inserts - 1 ); if ( res_remain_div ) { auto const new_lit = index_list.add_and( ( lit ^ 0x1 ) - 2, *res_remain_div ^ on_off_div ); return new_lit + on_off_div; } } else if ( score_pair > 0 ) /* divide with a pair */ { and_pair const pair = on_off_pair ? pos_unate_pairs[0] : neg_unate_pairs[0]; divisors[on_off_pair] &= ( pair.lit1 & 0x1 ? divisors[pair.lit1 >> 1] : ~divisors[pair.lit1 >> 1] ) | ( pair.lit2 & 0x1 ? divisors[pair.lit2 >> 1] : ~divisors[pair.lit2 >> 1] ); auto const res_remain_pair = compute_function_rec( num_inserts - 2 ); if ( res_remain_pair ) { auto const new_lit1 = index_list.add_and( pair.lit1 - 2, pair.lit2 - 2 ); auto const new_lit2 = index_list.add_and( new_lit1 ^ 0x1, *res_remain_pair ^ on_off_pair ); return new_lit2 + on_off_pair; } } return std::nullopt; } /* See if there is a constant or divisor covering all on-set bits or all off-set bits. 1. Check constant-resub 2. Collect unate literals 3. Find 0-resub (both positive unate and negative unate) and collect binate (neither pos nor neg unate) divisors */ std::optional<uint32_t> find_one_unate() { num_bits[0] = kitty::count_ones( divisors[0] ); /* off-set */ num_bits[1] = kitty::count_ones( divisors[1] ); /* on-set */ if ( num_bits[0] == 0 ) { return 1; } if ( num_bits[1] == 0 ) { return 0; } pos_unate_lits.clear(); neg_unate_lits.clear(); binate_divs.clear(); for ( auto v = 2u; v < divisors.size(); ++v ) { bool unateness[4] = {false, false, false, false}; /* check intersection with off-set */ if ( intersection_is_empty( divisors[v], divisors[0] ) ) { pos_unate_lits.emplace_back( v << 1 ); unateness[0] = true; } else if ( intersection_is_empty_neg( divisors[v], divisors[0] ) ) { pos_unate_lits.emplace_back( v << 1 | 0x1 ); unateness[1] = true; } /* check intersection with on-set */ if ( intersection_is_empty( divisors[v], divisors[1] ) ) { neg_unate_lits.emplace_back( v << 1 ); unateness[2] = true; } else if ( intersection_is_empty_neg( divisors[v], divisors[1] ) ) { neg_unate_lits.emplace_back( v << 1 | 0x1 ); unateness[3] = true; } /* 0-resub */ if ( unateness[0] && unateness[3] ) { return ( v << 1 ) - 2; } if ( unateness[1] && unateness[2] ) { return ( v << 1 ) - 1; } /* useless unate literal */ if ( ( unateness[0] && unateness[2] ) || ( unateness[1] && unateness[3] ) ) { pos_unate_lits.pop_back(); neg_unate_lits.pop_back(); } /* binate divisor */ else if ( !unateness[0] && !unateness[1] && !unateness[2] && !unateness[3] ) { binate_divs.emplace_back( v ); } } return std::nullopt; } /* Sort the unate literals by the number of minterms in the intersection. - For `pos_unate_lits`, `on_off` = 1, sort by intersection with on-set; - For `neg_unate_lits`, `on_off` = 0, sort by intersection with off-set */ void sort_unate_lits( std::vector<uint32_t>& unate_lits, std::unordered_map<uint32_t, uint32_t>& scores, uint32_t on_off ) { scores.clear(); for ( auto const& lit : unate_lits ) { scores[lit] = kitty::count_ones( ( lit & 0x1 ? ~divisors[lit >> 1] : divisors[lit >> 1] ) & divisors[on_off] ); } std::sort( unate_lits.begin(), unate_lits.end(), [&]( uint32_t lit1, uint32_t lit2 ) { return scores[lit1] > scores[lit2]; // descending order }); } void sort_unate_pairs( std::vector<and_pair>& unate_pairs, std::unordered_map<and_pair, uint32_t, pair_hash>& scores, uint32_t on_off ) { scores.clear(); for ( auto const& p : unate_pairs ) { scores[p] = kitty::count_ones( ( p.lit1 & 0x1 ? ~divisors[p.lit1 >> 1] : divisors[p.lit1 >> 1] ) & ( p.lit2 & 0x1 ? ~divisors[p.lit2 >> 1] : divisors[p.lit2 >> 1] ) & divisors[on_off] ); } std::sort( unate_pairs.begin(), unate_pairs.end(), [&]( and_pair const& p1, and_pair const& p2 ) { return scores[p1] > scores[p2]; // descending order }); } /* See if there are two unate divisors covering all on-set bits or all off-set bits. - For `pos_unate_lits`, `on_off` = 1, try covering all on-set bits by combining two with an OR gate; - For `neg_unate_lits`, `on_off` = 0, try covering all off-set bits by combining two with an AND gate */ std::optional<uint32_t> find_div_div( std::vector<uint32_t>& unate_lits, std::unordered_map<uint32_t, uint32_t>& scores, uint32_t on_off ) { for ( auto i = 0u; i < unate_lits.size(); ++i ) { uint32_t const& lit1 = unate_lits[i]; if ( scores[lit1] * 2 < num_bits[on_off] ) { break; } for ( auto j = i + 1; j < unate_lits.size(); ++j ) { uint32_t const& lit2 = unate_lits[j]; if ( scores[lit1] + scores[lit2] < num_bits[on_off] ) { break; } auto const ntt1 = lit1 & 0x1 ? divisors[lit1 >> 1] : ~divisors[lit1 >> 1]; auto const ntt2 = lit2 & 0x1 ? divisors[lit2 >> 1] : ~divisors[lit2 >> 1]; if ( intersection_is_empty( ntt1, ntt2, divisors[on_off] ) ) { auto const new_lit = index_list.add_and( ( lit1 ^ 0x1 ) - 2, ( lit2 ^ 0x1 ) - 2 ); return new_lit + on_off; } } } return std::nullopt; } std::optional<uint32_t> find_div_pair( std::vector<uint32_t>& unate_lits, std::vector<and_pair>& unate_pairs, std::unordered_map<uint32_t, uint32_t>& lit_scores, std::unordered_map<and_pair, uint32_t, pair_hash>& pair_scores, uint32_t on_off ) { for ( auto i = 0u; i < unate_lits.size(); ++i ) { uint32_t const& lit1 = unate_lits[i]; for ( auto j = 0u; j < unate_pairs.size(); ++j ) { and_pair const& pair2 = unate_pairs[j]; if ( lit_scores[lit1] + pair_scores[pair2] < num_bits[on_off] ) { break; } auto const ntt1 = lit1 & 0x1 ? divisors[lit1 >> 1] : ~divisors[lit1 >> 1]; auto const ntt2 = ( pair2.lit1 & 0x1 ? divisors[pair2.lit1 >> 1] : ~divisors[pair2.lit1 >> 1] ) | ( pair2.lit2 & 0x1 ? divisors[pair2.lit2 >> 1] : ~divisors[pair2.lit2 >> 1] ); if ( intersection_is_empty( ntt1, ntt2, divisors[on_off] ) ) { auto const new_lit1 = index_list.add_and( pair2.lit1 - 2, pair2.lit2 - 2 ); auto const new_lit2 = index_list.add_and( ( lit1 ^ 0x1 ) - 2, new_lit1 ^ 0x1 ); return new_lit2 + on_off; } } } return std::nullopt; } std::optional<uint32_t> find_pair_pair( std::vector<and_pair>& unate_pairs, std::unordered_map<and_pair, uint32_t, pair_hash>& scores, uint32_t on_off ) { for ( auto i = 0u; i < unate_pairs.size(); ++i ) { and_pair const& pair1 = unate_pairs[i]; if ( scores[pair1] * 2 < num_bits[on_off] ) { break; } for ( auto j = i + 1; j < unate_pairs.size(); ++j ) { and_pair const& pair2 = unate_pairs[j]; if ( scores[pair1] + scores[pair2] < num_bits[on_off] ) { break; } auto const ntt1 = ( pair1.lit1 & 0x1 ? divisors[pair1.lit1 >> 1] : ~divisors[pair1.lit1 >> 1] ) | ( pair1.lit2 & 0x1 ? divisors[pair1.lit2 >> 1] : ~divisors[pair1.lit2 >> 1] ); auto const ntt2 = ( pair2.lit1 & 0x1 ? divisors[pair2.lit1 >> 1] : ~divisors[pair2.lit1 >> 1] ) | ( pair2.lit2 & 0x1 ? divisors[pair2.lit2 >> 1] : ~divisors[pair2.lit2 >> 1] ); if ( intersection_is_empty( ntt1, ntt2, divisors[on_off] ) ) { uint32_t const fanin_lit1 = index_list.add_and( pair1.lit1 - 2, pair1.lit2 - 2 ); uint32_t const fanin_lit2 = index_list.add_and( pair2.lit1 - 2, pair2.lit2 - 2 ); uint32_t const output_lit = index_list.add_and( fanin_lit1 ^ 0x1, fanin_lit2 ^ 0x1 ); return output_lit + on_off; } } } return std::nullopt; } std::optional<uint32_t> find_xor() { /* collect xor_pairs (d1 ^ d2) & off = 0 and ~(d1 ^ d2) & on = 0, selecting d1, d2 from binate_divs */ return std::nullopt; } /* collect and_pairs (d1 & d2) & off = 0 and ~(d1 & d2) & on = 0, selecting d1, d2 from binate_divs */ void collect_unate_pairs() { for ( auto i = 0u; i < binate_divs.size(); ++i ) { for ( auto j = i + 1; j < binate_divs.size(); ++j ) { collect_unate_pairs_detail( binate_divs[i], 0, binate_divs[j], 0 ); collect_unate_pairs_detail( binate_divs[i], 0, binate_divs[j], 1 ); collect_unate_pairs_detail( binate_divs[i], 1, binate_divs[j], 0 ); collect_unate_pairs_detail( binate_divs[i], 1, binate_divs[j], 1 ); } } } void collect_unate_pairs_detail( uint32_t div1, uint32_t neg1, uint32_t div2, uint32_t neg2 ) { auto const tt1 = neg1 ? ~divisors[div1] : divisors[div1]; auto const tt2 = neg2 ? ~divisors[div2] : divisors[div2]; /* check intersection with off-set; additionally check intersection with on-set is not empty (otherwise it's useless) */ if ( intersection_is_empty( tt1, tt2, divisors[0] ) && !intersection_is_empty( tt1, tt2, divisors[1] ) ) { pos_unate_pairs.emplace_back( ( div1 << 1 ) + neg1, ( div2 << 1 ) + neg2 ); } /* check intersection with on-set; additionally check intersection with off-set is not empty (otherwise it's useless) */ else if ( intersection_is_empty( tt1, tt2, divisors[1] ) && !intersection_is_empty( tt1, tt2, divisors[0] ) ) { neg_unate_pairs.emplace_back( ( div1 << 1 ) + neg1, ( div2 << 1 ) + neg2 ); } } private: /* equivalent to kitty::is_const0( tt1 & tt2 ), but faster when num_blocks is a lot */ bool intersection_is_empty( TT const& tt1, TT const& tt2 ) { for ( auto i = 0u; i < tt1.num_blocks(); ++i ) { if ( ( tt1._bits[i] & tt2._bits[i] ) != 0 ) { return false; } } return true; } /* equivalent to kitty::is_const0( ~tt1 & tt2 ), but faster when num_blocks is a lot */ bool intersection_is_empty_neg( TT const& tt1, TT const& tt2 ) { for ( auto i = 0u; i < tt1.num_blocks(); ++i ) { if ( ( ~(tt1._bits[i]) & tt2._bits[i] ) != 0 ) { return false; } } return true; } /* equivalent to kitty::is_const0( tt1 & tt2 & tt3 ), but faster when num_blocks is a lot */ bool intersection_is_empty( TT const& tt1, TT const& tt2, TT const& tt3 ) { for ( auto i = 0u; i < tt1.num_blocks(); ++i ) { if ( ( tt1._bits[i] & tt2._bits[i] & tt3._bits[i] ) != 0 ) { return false; } } return true; } private: std::vector<TT> divisors; index_list_t index_list; uint32_t num_bits[2]; /* number of bits in on-set and off-set */ /* positive unate: not overlapping with off-set negative unate: not overlapping with on-set */ std::vector<uint32_t> pos_unate_lits, neg_unate_lits, binate_divs; std::unordered_map<uint32_t, uint32_t> pos_lit_scores, neg_lit_scores; std::vector<and_pair> pos_unate_pairs, neg_unate_pairs; std::unordered_map<and_pair, uint32_t, pair_hash> pos_pair_scores, neg_pair_scores; stats& st; params const& ps; }; /* xag_resyn_engine */ } /* namespace mockturtle */
34.469579
245
0.614211
[ "vector" ]
5c94d1c8781c46d8530d8c076545cc7395789e26
7,468
cpp
C++
beatroot-vamp/Induction.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
beatroot-vamp/Induction.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
beatroot-vamp/Induction.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Vamp feature extraction plugin for the BeatRoot beat tracker. Centre for Digital Music, Queen Mary, University of London. This file copyright 2011 Simon Dixon, Chris Cannam and QMUL. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. See the file COPYING included with this distribution for more information. */ #include "Induction.h" double Induction::clusterWidth = 0.025; double Induction::minIOI = 0.070; double Induction::maxIOI = 2.500; double Induction::minIBI = 0.3; double Induction::maxIBI = 1.0; int Induction::topN = 10; AgentList Induction::beatInduction(AgentParameters params, EventList events) { int i, j, b, bestCount; bool submult; int intervals = 0; // number of interval clusters vector<int> bestn;// count of high-scoring clusters bestn.resize(topN); double ratio, err; int degree; int maxClusterCount = (int) ceil((maxIOI - minIOI) / clusterWidth); vector<double> clusterMean; clusterMean.resize(maxClusterCount); vector<int> clusterSize; clusterSize.resize(maxClusterCount); vector<int> clusterScore; clusterScore.resize(maxClusterCount); EventList::iterator ptr1, ptr2; Event e1, e2; ptr1 = events.begin(); while (ptr1 != events.end()) { e1 = *ptr1; ++ptr1; ptr2 = events.begin(); e2 = *ptr2; ++ptr2; while (e2 != e1 && ptr2 != events.end()) { e2 = *ptr2; ++ptr2; } while (ptr2 != events.end()) { e2 = *ptr2; ++ptr2; double ioi = e2.time - e1.time; if (ioi < minIOI) // skip short intervals continue; if (ioi > maxIOI) // ioi too long break; for (b = 0; b < intervals; b++) // assign to nearest cluster if (fabs(clusterMean[b] - ioi) < clusterWidth) { if ((b < intervals - 1) && ( fabs(clusterMean[b+1] - ioi) < fabs(clusterMean[b] - ioi))) b++; // next cluster is closer clusterMean[b] = (clusterMean[b] * clusterSize[b] +ioi)/ (clusterSize[b] + 1); clusterSize[b]++; break; } if (b == intervals) { // no suitable cluster; create new one if (intervals == maxClusterCount) { // System.err.println("Warning: Too many clusters"); continue; // ignore this IOI } intervals++; for ( ; (b>0) && (clusterMean[b-1] > ioi); b--) { clusterMean[b] = clusterMean[b-1]; clusterSize[b] = clusterSize[b-1]; } clusterMean[b] = ioi; clusterSize[b] = 1; } } } for (b = 0; b < intervals; b++) // merge similar intervals // TODO: they are now in order, so don't need the 2nd loop // TODO: check BOTH sides before averaging or upper gps don't work for (i = b+1; i < intervals; i++) if (fabs(clusterMean[b] - clusterMean[i]) < clusterWidth) { clusterMean[b] = (clusterMean[b] * clusterSize[b] + clusterMean[i] * clusterSize[i]) / (clusterSize[b] + clusterSize[i]); clusterSize[b] = clusterSize[b] + clusterSize[i]; --intervals; for (j = i+1; j <= intervals; j++) { clusterMean[j-1] = clusterMean[j]; clusterSize[j-1] = clusterSize[j]; } } if (intervals == 0) return AgentList(); for (b = 0; b < intervals; b++) clusterScore[b] = 10 * clusterSize[b]; bestn[0] = 0; bestCount = 1; for (b = 0; b < intervals; b++) for (i = 0; i <= bestCount; i++) if ((i < topN) && ((i == bestCount) || (clusterScore[b] > clusterScore[bestn[i]]))){ if (bestCount < topN) bestCount++; for (j = bestCount - 1; j > i; j--) bestn[j] = bestn[j-1]; bestn[i] = b; break; } for (b = 0; b < intervals; b++) // score intervals for (i = b+1; i < intervals; i++) { ratio = clusterMean[b] / clusterMean[i]; submult = ratio < 1; if (submult) degree = (int) nearbyint(1/ratio); else degree = (int) nearbyint(ratio); if ((degree >= 2) && (degree <= 8)) { if (submult) err = fabs(clusterMean[b]*degree - clusterMean[i]); else err = fabs(clusterMean[b] - clusterMean[i]*degree); if (err < (submult? clusterWidth : clusterWidth * degree)) { if (degree >= 5) degree = 1; else degree = 6 - degree; clusterScore[b] += degree * clusterSize[i]; clusterScore[i] += degree * clusterSize[b]; } } } AgentList a; for (int index = 0; index < bestCount; index++) { b = bestn[index]; // Adjust it, using the size of super- and sub-intervals double newSum = clusterMean[b] * clusterScore[b]; int newCount = clusterSize[b]; int newWeight = clusterScore[b]; for (i = 0; i < intervals; i++) { if (i == b) continue; ratio = clusterMean[b] / clusterMean[i]; if (ratio < 1) { degree = (int) nearbyint(1 / ratio); if ((degree >= 2) && (degree <= 8)) { err = fabs(clusterMean[b]*degree - clusterMean[i]); if (err < clusterWidth) { newSum += clusterMean[i] / degree * clusterScore[i]; newCount += clusterSize[i]; newWeight += clusterScore[i]; } } } else { degree = (int) nearbyint(ratio); if ((degree >= 2) && (degree <= 8)) { err = fabs(clusterMean[b] - degree*clusterMean[i]); if (err < clusterWidth * degree) { newSum += clusterMean[i] * degree * clusterScore[i]; newCount += clusterSize[i]; newWeight += clusterScore[i]; } } } } double beat = newSum / newWeight; // Scale within range ... hope the grouping isn't ternary :( while (beat < minIBI) // Maximum speed beat *= 2.0; while (beat > maxIBI) // Minimum speed beat /= 2.0; if (beat >= minIBI) { a.push_back(new Agent(params, beat)); } } #ifdef DEBUG_BEATROOT std::cerr << "Induction complete, returning " << a.size() << " agent(s)" << std::endl; #endif return a; } // beatInduction()
38.297436
90
0.481387
[ "vector" ]
5c9836b5ff2fc15df1c148aa2b882db0a19f29e0
1,230
cpp
C++
mriga.cpp
avinal/C_ode
f056da37c8c56a4a62a06351c2ea3773d16d1b11
[ "MIT" ]
1
2020-08-23T20:21:35.000Z
2020-08-23T20:21:35.000Z
mriga.cpp
avinal/C_ode
f056da37c8c56a4a62a06351c2ea3773d16d1b11
[ "MIT" ]
null
null
null
mriga.cpp
avinal/C_ode
f056da37c8c56a4a62a06351c2ea3773d16d1b11
[ "MIT" ]
2
2019-03-18T10:22:13.000Z
2021-01-03T10:12:28.000Z
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int test; cin >> test; int m, n; while (test--) { cin >> n >> m; vector<int> eat; int k; for (int i = 0; i < m; i++) { cin >> k; eat.push_back(k); } int count = ((m % n == 0) ? (m / n) : (m / n) + 1), p = 0; for (int j = 0; j < count; j++) { vector<int>::const_iterator first = eat.begin() + p; vector<int>::const_iterator last; if (m < n) { last = eat.end(); } else { last = first + n; p += n; m-=n; } vector<int> small(first, last); sort(small.begin(), small.end()); auto dub = unique(small.begin(), small.end()); bool found = (dub == small.end()); if (!found) { cout << "NO\n"; break; } else { continue; } cout << "YES\n"; } } system("pause"); return 0; }
21.964286
66
0.347154
[ "vector" ]
5c9f3a1c13fa17a4eed61f6bc4884a8c1986f055
3,821
cpp
C++
vkconfig_core/test/test_setting_type_flags.cpp
Dantali0n/VulkanTools
b9317b652fc4015942148212b9e92498be3afb80
[ "Apache-2.0" ]
null
null
null
vkconfig_core/test/test_setting_type_flags.cpp
Dantali0n/VulkanTools
b9317b652fc4015942148212b9e92498be3afb80
[ "Apache-2.0" ]
null
null
null
vkconfig_core/test/test_setting_type_flags.cpp
Dantali0n/VulkanTools
b9317b652fc4015942148212b9e92498be3afb80
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-2021 Valve Corporation * Copyright (c) 2020-2021 LunarG, 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. * * Authors: * - Christophe Riccio <christophe@lunarg.com> */ #include "../setting_flags.h" #include "../layer.h" #include <gtest/gtest.h> inline SettingMetaFlags* InstantiateFlags(Layer& layer, const std::string& key) { return static_cast<SettingMetaFlags*>(layer.Instantiate(key, SETTING_FLAGS)); } TEST(test_setting_type_flags, init) { EXPECT_EQ(SETTING_FLAGS, SettingMetaFlags::TYPE); } TEST(test_setting_type_flags, meta_equal) { Layer layer; SettingMetaFlags* meta0 = InstantiateFlags(layer, "key"); SettingMetaFlags* meta1 = InstantiateFlags(layer, "key"); EXPECT_EQ(*meta0, *meta1); std::vector<std::string> valueX; valueX.push_back("valueA"); valueX.push_back("valueB"); meta0->default_value = valueX; EXPECT_NE(*meta0, *meta1); meta1->default_value = valueX; EXPECT_EQ(*meta0, *meta1); std::vector<std::string> valueY; valueY.push_back("valueB"); valueY.push_back("valueC"); meta1->default_value = valueY; EXPECT_NE(*meta0, *meta1); std::vector<std::string> valueZ; valueZ.push_back("valueB"); valueZ.push_back("valueA"); meta1->default_value = valueZ; EXPECT_EQ(*meta0, *meta1); } TEST(test_setting_type_flags, data_equal) { Layer layer; SettingMetaFlags* metaA = InstantiateFlags(layer, "keyA"); SettingMetaFlags* metaB = InstantiateFlags(layer, "keyB"); EXPECT_NE(*metaA, *metaB); std::vector<std::string> valueX; valueX.push_back("valueA"); valueX.push_back("valueB"); std::vector<std::string> valueY; valueY.push_back("valueB"); valueY.push_back("valueC"); SettingDataFlags* data0 = Instantiate<SettingDataFlags>(metaA); EXPECT_STREQ(metaA->key.c_str(), data0->key.c_str()); SettingDataFlags* data1 = Instantiate<SettingDataFlags>(metaA); EXPECT_STREQ(metaA->key.c_str(), data1->key.c_str()); EXPECT_EQ(*data0, *data1); data0->value = valueX; EXPECT_NE(*data0, *data1); data1->value = valueX; EXPECT_EQ(*data0, *data1); data1->value = valueY; EXPECT_NE(*data0, *data1); } TEST(test_setting_type_flags, value) { Layer layer; SettingMetaFlags* meta = InstantiateFlags(layer, "key"); meta->default_value.push_back("A"); meta->default_value.push_back("B"); EXPECT_STREQ("A,B", meta->Export(EXPORT_MODE_DOC).c_str()); EXPECT_STREQ("A,B", meta->Export(EXPORT_MODE_OVERRIDE).c_str()); SettingDataFlags* dataA = Instantiate<SettingDataFlags>(meta); EXPECT_EQ(dataA->value, meta->default_value); EXPECT_STREQ("A,B", dataA->Export(EXPORT_MODE_DOC).c_str()); EXPECT_STREQ("A,B", dataA->Export(EXPORT_MODE_OVERRIDE).c_str()); meta->default_value.clear(); meta->default_value.push_back("C"); meta->default_value.push_back("D"); EXPECT_STREQ("C,D", meta->Export(EXPORT_MODE_DOC).c_str()); EXPECT_STREQ("C,D", meta->Export(EXPORT_MODE_OVERRIDE).c_str()); SettingDataFlags* dataC = Instantiate<SettingDataFlags>(meta); EXPECT_EQ(dataC->value, meta->default_value); EXPECT_STREQ("C,D", dataC->Export(EXPORT_MODE_DOC).c_str()); EXPECT_STREQ("C,D", dataC->Export(EXPORT_MODE_OVERRIDE).c_str()); }
30.568
89
0.6972
[ "vector" ]
5c9f984e5af0c8b9c3f7d77afdd6e802dabe69a1
731
hpp
C++
modules/lua/luaconsole.hpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
5
2017-12-27T12:57:36.000Z
2021-10-02T03:21:40.000Z
modules/lua/luaconsole.hpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
9
2020-09-29T22:40:49.000Z
2020-10-17T20:05:05.000Z
modules/lua/luaconsole.hpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
null
null
null
#ifndef LUACONSOLE_HPP #define LUACONSOLE_HPP #include <window.hpp> #include <vector> #include <string> extern "C" { #include <lua.h> } class LuaConsole : public Window { WINDOW_PREAMBLE private: struct logentry { bool isError; std::string message; }; static const int MaxInputLength = 512; std::vector<logentry> log; bool scrollToEnd; lua_State * lua; char inputBuffer[MaxInputLength]; private: static int LuaPrint(lua_State * lua); protected: void OnUpdate() override; public: LuaConsole(); LuaConsole(LuaConsole const &) = delete; LuaConsole(LuaConsole &&) = delete; virtual ~LuaConsole(); void Execute(char const * str); void Print(char const * str, bool err = false); }; #endif // LUACONSOLE_HPP
15.891304
48
0.72093
[ "vector" ]
5ca0a6f2bbe7bc2feec4ce71476d1339198237bb
3,915
cpp
C++
Code/Tools/Standalone/Source/LUA/LUAEditorSettingsDialog.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Tools/Standalone/Source/LUA/LUAEditorSettingsDialog.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Tools/Standalone/Source/LUA/LUAEditorSettingsDialog.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Script/ScriptAsset.h> #include <AzFramework/StringFunc/StringFunc.h> #include <AzCore/Component/TickBus.h> #include <AzCore/UserSettings/UserSettingsComponent.h> #include <QtWidgets/QVBoxLayout> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/RTTI/TypeInfo.h> #include <AzToolsFramework/UI/LegacyFramework/Core/EditorFrameworkAPI.h> #include "LUAEditorSettingsDialog.hxx" #include "LUAEditorMainWindow.hxx" #include "LUAEditorContextMessages.h" #include "LUAEditorBlockState.h" #include <Source/LUA/ui_LUAEditorSettingsDialog.h> namespace { } namespace LUAEditor { extern AZ::Uuid ContextID; LUAEditorSettingsDialog::LUAEditorSettingsDialog(QWidget* parent) : QDialog(parent) { m_gui = azcreate(Ui::LUAEditorSettingsDialog, ()); m_gui->setupUi(this); AZ::SerializeContext* context = nullptr; { EBUS_EVENT_RESULT(context, AZ::ComponentApplicationBus, GetSerializeContext); AZ_Assert(context, "We should have a valid context!"); } AZStd::intrusive_ptr<SyntaxStyleSettings> syntaxStyleSettings = AZ::UserSettings::CreateFind<SyntaxStyleSettings>(AZ_CRC("LUA Editor Text Settings", 0xb6e15565), AZ::UserSettings::CT_GLOBAL); // Store a copy to revert if needed. m_originalSettings = *syntaxStyleSettings; m_gui->propertyEditor->Setup(context, nullptr, true, 420); m_gui->propertyEditor->AddInstance(syntaxStyleSettings.get(), syntaxStyleSettings->RTTI_GetType()); m_gui->propertyEditor->setObjectName("m_gui->propertyEditor"); m_gui->propertyEditor->setMinimumHeight(500); m_gui->propertyEditor->setMaximumHeight(1000); m_gui->propertyEditor->SetSavedStateKey(AZ_CRC("LuaIDE_SyntaxStyleSettings")); setModal(false); m_gui->propertyEditor->InvalidateAll(); m_gui->propertyEditor->ExpandAll(); m_gui->propertyEditor->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); QVBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(m_gui->propertyEditor); layout->addWidget(m_gui->cancelButton); layout->addWidget(m_gui->saveButton); layout->addWidget(m_gui->saveCloseButton); setLayout(layout); } void LUAEditorSettingsDialog::OnSave() { EBUS_EVENT(AZ::UserSettingsComponentRequestBus, Save); EBUS_EVENT(LUAEditorMainWindowMessages::Bus, Repaint); } void LUAEditorSettingsDialog::OnSaveClose() { OnSave(); close(); } void LUAEditorSettingsDialog::OnCancel() { AZStd::intrusive_ptr<SyntaxStyleSettings> syntaxStyleSettings = AZ::UserSettings::CreateFind<SyntaxStyleSettings>(AZ_CRC("LUA Editor Text Settings", 0xb6e15565), AZ::UserSettings::CT_GLOBAL); // Revert the stored copy, no changes will be stored. *syntaxStyleSettings = m_originalSettings; EBUS_EVENT(LUAEditorMainWindowMessages::Bus, Repaint); close(); } LUAEditorSettingsDialog::~LUAEditorSettingsDialog() { m_gui->propertyEditor->ClearInstances(); azdestroy(m_gui); } void LUAEditorSettingsDialog::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Escape) { OnCancel(); return; } else if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { OnSaveClose(); return; } } }//namespace LUAEditor #include <Source/LUA/moc_LUAEditorSettingsDialog.cpp>
30.826772
199
0.686335
[ "3d" ]
5ca1aac26956bd2111687fdae0c1608dd5f9b7ca
7,929
cpp
C++
src/dsp.cpp
colinbdclark/node-dsp
840bf5ecad5b4ce7be8a421160163597317d451f
[ "MIT" ]
1
2019-03-05T16:52:41.000Z
2019-03-05T16:52:41.000Z
src/dsp.cpp
colinbdclark/node-dsp
840bf5ecad5b4ce7be8a421160163597317d451f
[ "MIT" ]
null
null
null
src/dsp.cpp
colinbdclark/node-dsp
840bf5ecad5b4ce7be8a421160163597317d451f
[ "MIT" ]
null
null
null
#include <math.h> #include <algorithm> #include <time.h> #include <vector> #include <limits> #include <cstring> #include "dsp.h" #include "common.h" #include "float32array.h" using namespace v8; using namespace node; using namespace std; void NodeDSP::Initialize (Handle<Object> target) { HandleScope scope; srand((unsigned) time(0)); Handle<Object> dsp = Object::New(); SetMethod(dsp, "add", Add); SetMethod(dsp, "abs", Abs); SetMethod(dsp, "absCplx", AbsCplx); SetMethod(dsp, "acos", Acos); SetMethod(dsp, "add", Add); SetMethod(dsp, "asin", Asin); SetMethod(dsp, "atan", Atan); SetMethod(dsp, "atan2", Atan2); SetMethod(dsp, "ceil", Ceil); SetMethod(dsp, "clamp", Clamp); SetMethod(dsp, "cos", Cos); SetMethod(dsp, "div", Div); SetMethod(dsp, "divCplx", DivCplx); SetMethod(dsp, "exp", Exp); SetMethod(dsp, "floor", Floor); SetMethod(dsp, "fract", Fract); SetMethod(dsp, "log", Log); SetMethod(dsp, "madd", Madd); SetMethod(dsp, "max", Max); SetMethod(dsp, "min", Min); SetMethod(dsp, "mul", Mul); SetMethod(dsp, "mulCplx", MulCplx); SetMethod(dsp, "pack", Pack); SetMethod(dsp, "pow", Pow); SetMethod(dsp, "ramp", Ramp); SetMethod(dsp, "random", Random); SetMethod(dsp, "round", Round); SetMethod(dsp, "sampleCubic", SampleCubic); SetMethod(dsp, "sampleLinear", SampleLinear); SetMethod(dsp, "sign", Sign); SetMethod(dsp, "sin", Sin); SetMethod(dsp, "sqrt", Sqrt); SetMethod(dsp, "sub", Sub); SetMethod(dsp, "sum", Sum); SetMethod(dsp, "tan", Tan); SetMethod(dsp, "unpack", Unpack); target->Set(String::NewSymbol("DSP"), dsp); } DSP_METHOD_OP(Add, +) DSP_METHOD_OP(Sub, -) DSP_METHOD_OP(Mul, *) DSP_METHOD_OP(Div, /) DSP_METHOD_3_OVERLOADING(Madd, x[i] + y[i] * zz, x[i] + y[i] * z[i]) DSP_METHOD_ALG(Sin, sin) DSP_METHOD_ALG(Cos, cos) DSP_METHOD_ALG(Tan, tan) DSP_METHOD_ALG(Asin, asin) DSP_METHOD_ALG(Acos, acos) DSP_METHOD_ALG(Atan, atan) DSP_METHOD_2(Atan2, atan2(x[i], y[i])) DSP_METHOD_1(Sign, sign(x[i])) DSP_METHOD_1(Fract, fract(x[i])) DSP_METHOD_ALG(Abs, fabs) DSP_METHOD_ALG(Ceil, ceil) DSP_METHOD_ALG(Floor, floor) DSP_METHOD_ALG(Round, round) DSP_METHOD_ALG(Sqrt, sqrt) DSP_METHOD_2_OVERLOADING(Pow, pow(a, b)) DSP_METHOD_ALG(Exp, exp) DSP_METHOD_ALG(Log, log) DSP_METHOD_ACCUMULATOR(Sum, 0.0, src[i] + v) DSP_METHOD_ACCUMULATOR(Max, 1.0/0.0, max(src[i], v)) DSP_METHOD_ACCUMULATOR(Min, 1.0/0.0, min(src[i], v)) DSP_METHOD_CPLX_2_OVERLOADING(MulCplx, dstReal[i] = x_r * yr - xImag[i] * yi; dstImag[i] = x_r * yi + xImag[i] * yr; , dstReal[i] = x_r * y_r - xImag[i] * yImag[i]; dstImag[i] = x_r * yImag[i] + xImag[i] * y_r; ) DSP_METHOD_CPLX_2_OVERLOADING(DivCplx, float denom = yr * yr + yi * yi; dstReal[i] = (x_r * yr + xImag[i] * yi) / denom; dstImag[i] = (x_r * yi - xImag[i] * yr) / denom; , float denom = y_r * y_r + yImag[i] * yImag[i]; dstReal[i] = (x_r * y_r + xImag[i] * yImag[i]) / denom; dstImag[i] = (x_r * yImag[i] - xImag[i] * y_r) / denom; ) DSP_METHOD_2(AbsCplx, sqrt(pow(x[i], 2) + pow(y[i], 2))) Handle<Value> NodeDSP::Ramp (const Arguments &args) { HandleScope scope; Float32Array dst(args[0]); if ( !dst.IsValid() || !args[1]->IsNumber() || !args[2]->IsNumber() ) return INVALID_ARGUMENTS_ERROR; double first = args[1]->NumberValue(); double last = args[2]->NumberValue(); for (int i=0; i<dst.length; i++) { dst[i] = first + i * ((last - first) / (dst.length - 1)); } return Undefined(); } Handle<Value> NodeDSP::Random (const Arguments &args) { HandleScope scope; Float32Array dst(args[0]); if (!dst.IsValid()) return INVALID_ARGUMENTS_ERROR; double low = args[1]->IsNumber() ? args[1]->NumberValue() : 0.0; double high = args[2]->IsNumber() ? args[2]->NumberValue() : 1.0; for (int i=0; i<dst.length; i++) { dst[i] = low + (float) rand() / ((float) RAND_MAX / (high - low)); } return Undefined(); } Handle<Value> NodeDSP::Clamp (const Arguments &args) { HandleScope scope; int n = 0; Float32Array dst(args[n++]); Float32Array x(args[n++]); if (args.Length() == 3) { x.set(dst); n--; } else if (dst.Overlaps(x)) return OVERLAP_ERROR; if ( !dst.IsValid() || !x.IsValid() || !args[n+0]->IsNumber() || !args[n+1]->IsNumber() ) return INVALID_ARGUMENTS_ERROR; float minArg = args[n+0]->NumberValue(); float maxArg = args[n+1]->NumberValue(); int l = MIN2(dst, x); for (int i=0; i<l; i++) { dst[i] = clamp(x[i], minArg, maxArg); } return Undefined(); } Handle<Value> NodeDSP::Pack (const Arguments &args) { HandleScope scope; int srcCount = args.Length() - 3; Float32Array dst(args[0]); int offset = args[1]->Uint32Value(); int stride = args[2]->Uint32Value(); vector<Float32Array> src; for (int i=0; i<srcCount; i++) { Float32Array arg(args[i - 3]); src.push_back(arg); } int dstCount = floor((dst.length - offset) / stride); int l = dstCount < src[0].length ? dstCount : src[0].length; for (int k=0; k<l; k++) { int i = 0; for (vector<Float32Array>::iterator it = src.begin(); it != src.end(); it++, i++) { dst[offset + stride * k + i] = (*it)[k]; } } return Undefined(); } Handle<Value> NodeDSP::Unpack (const Arguments &args) { HandleScope scope; int dstCount = args.Length() - 3; Float32Array src(args[0]); int offset = args[1]->Uint32Value(); int stride = args[2]->Uint32Value(); vector<Float32Array> dst; for (int i=0; i<dstCount; i++) { Float32Array arg(args[i - 3]); dst.push_back(arg); } int srcCount = floor((src.length - offset) / stride); int l = srcCount < dst[0].length ? srcCount : dst[0].length; for (int k=0; k<l; k++) { int i = 0; for (vector<Float32Array>::iterator it = dst.begin(); it != dst.end(); it++, i++) { (*it)[k] = src[offset + stride * k + i]; } } return Undefined(); } Handle<Value> NodeDSP::SampleCubic (const Arguments &args) { HandleScope scope; Float32Array dst(args[0]); Float32Array x(args[1]); Float32Array t(args[2]); int repeat = args[3]->BooleanValue(); int xLen = x.length; int maxIdx = xLen - 1; if (repeat) { for (int k=MIN2(dst, t) - 1; k >= 0; k--) { float t2 = t[k] - floor(t[k] / xLen) * xLen; int idx = t2; float w = t2 - idx; float w2 = w * w; float w3 = w2 * w; float h2 = -2 * w3 + 3 * w2; float h1 = 1 - h2; float h4 = w3 - w2; float h3 = h4 - w2 + w; float p1 = x[idx > 0 ? idx - 1 : maxIdx]; float p2 = x[idx]; float p3 = x[idx < maxIdx ? idx + 1 : 0]; float p4 = x[idx < maxIdx - 1 ? idx + 2 : (idx + 2 - floor((idx + 2) / xLen) * xLen)]; dst[k] = h1 * p2 + h2 * p3 + 0.5 * (h3 * (p3 - p1) + h4 * (p4 - p2)); } } else { for (int k=MIN2(dst, t) - 1; k >= 0; k--) { float t2 = t[k] < 0 ? 0 : t[k] > maxIdx ? maxIdx : t[k]; int idx = t2; float w = t2 - idx; float w2 = w * w; float w3 = w2 * w; float h2 = -2 * w3 + 3 * w2; float h1 = 1 - h2; float h4 = w3 - w2; float h3 = h4 - w2 + w; float p1 = x[idx > 0 ? idx - 1 : 0]; float p2 = x[idx]; float p3 = x[idx < maxIdx ? idx + 1 : 0]; float p4 = x[idx < maxIdx - 1 ? idx + 2 : maxIdx]; dst[k] = h1 * p2 + h2 * p3 + 0.5 * (h3 * (p3 - p1) + h4 * (p4 - p2)); } } return Undefined(); } Handle<Value> NodeDSP::SampleLinear (const Arguments &args) { HandleScope scope; Float32Array dst(args[0]); Float32Array x(args[1]); Float32Array t(args[2]); int repeat = args[3]->BooleanValue(); int xLen = x.length; int maxIdx = xLen - 1; if (repeat) { for (int k=MIN2(dst, t) - 1; k >= 0; k--) { float t2 = t[k] - floor(t[k] / xLen) * xLen; int idx = t2; float w = t2 - idx; float p1 = x[idx]; float p2 = x[idx < maxIdx ? idx + 1 : 0]; dst[k] = p1 + w * (p2 - p1); } } else { for (int k=MIN2(dst, t) - 1; k >= 0; k--) { float t2 = t[k] < 0 ? 0 : t[k] > maxIdx ? maxIdx : t[k]; int idx = t2; float w = t2 - idx; float p1 = x[idx]; float p2 = x[idx < maxIdx ? idx + 1 : maxIdx]; dst[k] = p1 + w * (p2 - p1); } } return Undefined(); }
24.624224
89
0.605877
[ "object", "vector" ]
5ca46fa37cd32be75be5e05e6edbc04e2a1f241a
14,298
cpp
C++
universe.cpp
helm100/2d-cdt
e79044451f0f84c1b0ff5c3290a61b5f24df45c0
[ "MIT" ]
3
2021-01-11T14:28:27.000Z
2022-02-08T14:19:30.000Z
universe.cpp
helm100/2d-cdt
e79044451f0f84c1b0ff5c3290a61b5f24df45c0
[ "MIT" ]
1
2021-02-26T12:40:53.000Z
2021-02-26T12:40:53.000Z
universe.cpp
helm100/2d-cdt
e79044451f0f84c1b0ff5c3290a61b5f24df45c0
[ "MIT" ]
1
2021-03-02T16:03:14.000Z
2021-03-02T16:03:14.000Z
// Copyright 2020 Joren Brunekreef and Andrzej Görlich #include "universe.hpp" int Universe::nSlices = 0; std::vector<int> Universe::sliceSizes; bool Universe::sphere = false; bool Universe::imported = false; std::default_random_engine Universe::rng(0); // TODO(JorenB): set seed somewhere else Bag<Triangle, Triangle::pool_size> Universe::trianglesAll(rng); Bag<Vertex, Vertex::pool_size> Universe::verticesFour(rng); Bag<Triangle, Triangle::pool_size> Universe::trianglesFlip(rng); std::vector<Vertex::Label> Universe::vertices; std::vector<Link::Label> Universe::links; std::vector<Triangle::Label> Universe::triangles; std::vector<std::vector<Vertex::Label>> Universe::vertexNeighbors; std::vector<std::vector<Triangle::Label>> Universe::triangleNeighbors; std::vector<std::vector<Link::Label>> Universe::vertexLinks; std::vector<std::vector<Link::Label>> Universe::triangleLinks; void Universe::create(int nSlices_) { nSlices = nSlices_; initialize(); } void Universe::initialize() { int w = 3; // width of the initial strip. Can be adjusted for thermalization purposes - unclear what the 'optimal' value is. int t = nSlices; std::vector<Vertex::Label> initialVertices(w*t); for (int i = 0; i < w*t; i++) { auto v = Vertex::create(); v->time = i / w; initialVertices[i] = v; } for (int i = 0; i < t; i++) { sliceSizes.push_back(w); } // create triangles std::vector<Triangle::Label> initialTriangles(2*w*t); for(int i = 0; i < t; i++) { for(int j = 0; j < w; j++) { auto tl = Triangle::create(); tl->setVertices( initialVertices[i*w+j], initialVertices[i*w+(j+1)%w], initialVertices[((i+1)%t)*w+j]); initialTriangles[2*(i*w+j)] = tl; auto tr = Triangle::create(); tr->setVertices( initialVertices[((i+1)%t)*w+j], initialVertices[((i+1)%t)*w+(j+1)%w], initialVertices[i*w+(j+1)%w]); initialTriangles[2*(i*w+j)+1] = tr; trianglesAll.add(tl); trianglesAll.add(tr); trianglesFlip.add(tl); trianglesFlip.add(tr); } } // set triangle connectivity int row = 0, column = 0; for(int i = 0; i < t; ++i) { for(int j = 0; j < w; ++j) { row = 2*i*w; column = 2*j; initialTriangles[row + column]->setTriangles( initialTriangles[row + (column-1+2*w)%(2*w)], initialTriangles[row + column + 1], initialTriangles[(row + column -2*w+1+2*t*w)%(2*t*w)]); initialTriangles[row + column +1]->setTriangles( initialTriangles[row + column], initialTriangles[row + (column+2)%(2*w)], initialTriangles[(row + column + 2*w)%(2*t*w)]); } } } void Universe::insertVertex(Triangle::Label t) { Triangle::Label tc = t->getTriangleCenter(); Vertex::Label vr = t->getVertexRight(); int time = t->time; Vertex::Label v = Vertex::create(); v->time = time; verticesFour.add(v); sliceSizes[time] += 1; t->setVertexRight(v); tc->setVertexRight(v); Triangle::Label t1 = Triangle::create(); // right neighbor of t Triangle::Label t2 = Triangle::create(); // right neighbor of tc trianglesAll.add(t1); trianglesAll.add(t2); t1->setVertices(v, vr, t->getVertexCenter()); t2->setVertices(v, vr, tc->getVertexCenter()); t1->setTriangles(t, t->getTriangleRight(), t2); t2->setTriangles(tc, tc->getTriangleRight(), t1); if (t1->type != t1->getTriangleRight()->type) { trianglesFlip.remove(t); trianglesFlip.add(t1); } if (t2->type != t2->getTriangleRight()->type) { trianglesFlip.remove(tc); trianglesFlip.add(t2); } } void Universe::removeVertex(Vertex::Label v) { Triangle::Label tl = v->getTriangleLeft(); Triangle::Label tr = v->getTriangleRight(); Triangle::Label tlc = tl->getTriangleCenter(); Triangle::Label trc = tr->getTriangleCenter(); Triangle::Label trn = tr->getTriangleRight(); Triangle::Label trcn = trc->getTriangleRight(); tl->setTriangleRight(trn); tlc->setTriangleRight(trcn); tl->setVertexRight(tr->getVertexRight()); tlc->setVertexRight(tr->getVertexRight()); tr->getVertexRight()->setTriangleLeft(tl); sliceSizes[v->time] -= 1; trianglesAll.remove(tr); trianglesAll.remove(trc); if (trianglesFlip.contains(tr)) { trianglesFlip.remove(tr); trianglesFlip.add(tl); } if (trianglesFlip.contains(trc)) { trianglesFlip.remove(trc); trianglesFlip.add(tlc); } Triangle::destroy(tr); Triangle::destroy(trc); verticesFour.remove(v); Vertex::destroy(v); } void Universe::flipLink(Triangle::Label t) { auto tr = t->getTriangleRight(); auto tc = t->getTriangleCenter(); auto trc = tr->getTriangleCenter(); if (t->isUpwards()) { t->getVertexLeft()->setTriangleRight(tr); t->getVertexRight()->setTriangleLeft(tr); } else if (t->isDownwards()) { tr->getVertexLeft()->setTriangleRight(t); tr->getVertexRight()->setTriangleLeft(t); } t->setTriangleCenter(trc); tr->setTriangleCenter(tc); auto vl = t->getVertexLeft(); auto vr = t->getVertexRight(); auto vc = t->getVertexCenter(); auto vrr = tr->getVertexRight(); t->setVertices(vc, vrr, vl); tr->setVertices(vl, vr, vrr); if (verticesFour.contains(vl)) verticesFour.remove(vl); if (isFourVertex(vr)) verticesFour.add(vr); if (isFourVertex(vc)) verticesFour.add(vc); if (verticesFour.contains(vrr)) verticesFour.remove(vrr); if (trianglesFlip.contains(t->getTriangleLeft()) && (t->type == t->getTriangleLeft()->type)) trianglesFlip.remove(t->getTriangleLeft()); if (trianglesFlip.contains(tr) && (tr->type == tr->getTriangleRight()->type)) trianglesFlip.remove(tr); if ((!trianglesFlip.contains(t->getTriangleLeft())) && (t->type != t->getTriangleLeft()->type)) trianglesFlip.add(t->getTriangleLeft()); if ((!trianglesFlip.contains(tr)) && (tr->type != tr->getTriangleRight()->type)) trianglesFlip.add(tr); } bool Universe::isFourVertex(Vertex::Label v) { return (v->getTriangleLeft()->getTriangleRight() == v->getTriangleRight()) && (v->getTriangleLeft()->getTriangleCenter()->getTriangleRight() == v->getTriangleRight()->getTriangleCenter()); } void Universe::check() { for (auto t : trianglesAll) { assert(t->getTriangleLeft() >= 0); assert(t->getTriangleRight() >= 0); assert(t->getTriangleCenter() >= 0); assert(t->getVertexLeft() >= 0); assert(t->getVertexRight() >= 0); assert(t->getVertexCenter() >= 0); if (trianglesFlip.contains(t)) { assert(t->type != t->getTriangleRight()->type); } else if (!trianglesFlip.contains(t)) { assert(t->type == t->getTriangleRight()->type); } } for (auto t : trianglesAll) { if (t->isDownwards()) continue; auto v = t->getVertexLeft(); int nu = 1; auto tl = v->getTriangleLeft(); while (tl->getTriangleRight() != v->getTriangleRight()) { tl = tl->getTriangleRight(); nu++; } nu++; int nd = 1; tl = v->getTriangleLeft()->getTriangleCenter(); while (tl->getTriangleRight() != v->getTriangleRight()->getTriangleCenter()) { tl = tl->getTriangleRight(); nd++; } nd++; if (nu + nd == 4) { assert(Universe::verticesFour.contains(v)); } else { assert(!Universe::verticesFour.contains(v)); } } for (auto v : verticesFour) { auto tl = v->getTriangleLeft(); auto tr = v->getTriangleRight(); assert(tl->getTriangleRight() == tr); assert(tr->getTriangleLeft() == tl); } } void Universe::updateVertexData() { vertices.clear(); int max = 0; for (auto t : trianglesAll) { if (t->isUpwards()) { auto v = t->getVertexLeft(); vertices.push_back(v); if (v > max) max = v; } } vertexNeighbors.clear(); vertexNeighbors.resize(max+1); for (auto v : vertices) { if (sphere) { if (v->time == 0) { auto tl = v->getTriangleLeft(); Triangle::Label tn = tl; do { vertexNeighbors.at(v).push_back(tn->getVertexLeft()); tn = tn->getTriangleRight(); } while (tn->isDownwards()); vertexNeighbors.at(v).push_back(tn->getVertexCenter()); vertexNeighbors.at(v).push_back(tn->getVertexRight()); continue; } else if (v->time == nSlices-1) { auto tld = v->getTriangleLeft()->getTriangleCenter(); auto tn = tld; do { vertexNeighbors.at(v).push_back(tn->getVertexLeft()); tn = tn->getTriangleRight(); } while (tn->isUpwards()); vertexNeighbors.at(v).push_back(tn->getVertexCenter()); vertexNeighbors.at(v).push_back(tn->getVertexRight()); continue; } } auto tl = v->getTriangleLeft(); Triangle::Label tn = tl; do { vertexNeighbors.at(v).push_back(tn->getVertexLeft()); tn = tn->getTriangleRight(); } while (tn->isDownwards()); vertexNeighbors.at(v).push_back(tn->getVertexCenter()); vertexNeighbors.at(v).push_back(tn->getVertexRight()); tn = tn->getTriangleCenter()->getTriangleLeft(); while (tn->isUpwards()) { vertexNeighbors.at(v).push_back(tn->getVertexRight()); tn = tn->getTriangleLeft(); } vertexNeighbors.at(v).push_back(tn->getVertexCenter()); } } void Universe::updateLinkData() { for (auto l : links) { Link::destroy(l); } links.clear(); int max = 0; vertexLinks.clear(); for (auto i = 0u; i < vertexNeighbors.size(); i++) { vertexLinks.push_back({}); } triangleLinks.clear(); for (auto i = 0u; i < triangleNeighbors.size(); i++) { triangleLinks.push_back({-1, -1, -1}); } for (auto t : trianglesAll) { auto ll = Link::create(); // left link if (t->isUpwards()) ll->setVertices(t->getVertexLeft(), t->getVertexCenter()); else if (t->isDownwards()) ll->setVertices(t->getVertexCenter(), t->getVertexLeft()); ll->setTriangles(t->getTriangleLeft(), t); vertexLinks.at(t->getVertexLeft()).push_back(ll); vertexLinks.at(t->getVertexCenter()).push_back(ll); triangleLinks.at(t).at(0) = ll; triangleLinks.at(t->getTriangleLeft()).at(1) = ll; links.push_back(ll); if (ll > max) max = ll; if (t->isUpwards()) { auto lh = Link::create(); // horizontal link lh->setVertices(t->getVertexLeft(), t->getVertexRight()); lh->setTriangles(t, t->getTriangleCenter()); vertexLinks.at(t->getVertexLeft()).push_back(lh); vertexLinks.at(t->getVertexRight()).push_back(lh); triangleLinks.at(t).at(2) = lh; triangleLinks.at(t->getTriangleCenter()).at(2) = lh; links.push_back(lh); if (lh > max) max = lh; } } assert(links.size() == 3*vertices.size()); } void Universe::updateTriangleData() { triangles.clear(); int max = 0; for (auto t : trianglesAll) { triangles.push_back(t); if (t > max) max = t; } triangleNeighbors.clear(); triangleNeighbors.resize(max+1); for (auto t : trianglesAll) { if (sphere) { if (t->isUpwards() && t->time == 0) { triangleNeighbors.at(t) = {t->getTriangleLeft(), t->getTriangleRight()}; continue; } if (t->isDownwards() && t->time == nSlices-1) { triangleNeighbors.at(t) = {t->getTriangleLeft(), t->getTriangleRight()}; continue; } } triangleNeighbors.at(t) = {t->getTriangleLeft(), t->getTriangleRight(), t->getTriangleCenter()}; } } void Universe::exportGeometry(std::string geometryFilename) { updateTriangleData(); updateVertexData(); std::unordered_map<int, int> vertexMap; std::vector<Vertex::Label> intVMap; intVMap.resize(vertices.size()); int i = 0; for (auto v : vertices) { vertexMap.insert({v, i}); intVMap.at(i) = v; i++; } std::unordered_map<int, int> triangleMap; std::vector<Triangle::Label> intTMap; intTMap.resize(triangles.size()); i = 0; for (auto t : triangles) { triangleMap.insert({t, i}); intTMap.at(i) = t; i++; } std::string output; output += std::to_string(vertices.size()); output += "\n"; for (int j = 0; j < intVMap.size(); j++) { output += std::to_string(intVMap.at(j)->time); output += "\n"; } output += std::to_string(vertices.size()); output += "\n"; output += std::to_string(triangles.size()); output += "\n"; for (int j = 0; j < intTMap.size(); j++) { Triangle::Label t = intTMap.at(j); Vertex::Label tVs [3] = {t->getVertexLeft(),t->getVertexRight(),t->getVertexCenter()}; for (auto v : tVs) { output += std::to_string(vertexMap.at(v)); output += "\n"; } Triangle::Label tNeighb [3] = {t->getTriangleLeft(),t->getTriangleRight(),t->getTriangleCenter()}; for (auto t : tNeighb) { output += std::to_string(triangleMap.at(t)); output += "\n"; } } output += std::to_string(triangles.size()); std::ofstream file; file.open(geometryFilename, std::ios::out | std::ios::trunc); assert(file.is_open()); file << output << "\n"; file.close(); std::cout << geometryFilename << "\n"; } void Universe::importGeometry(std::string geometryFilename) { std::ifstream infile(geometryFilename.c_str()); assert(!infile.fail()); int line; int nV; infile >> nV; std::vector<Vertex::Label> vs(nV); int maxTime = 0; for (int i = 0; i < nV; i++) { infile >> line; auto v = Vertex::create(); v->time = line; vs.at(i) = v; if (v->time > maxTime) maxTime = v->time; } infile >> line; assert(line == nV); nSlices = maxTime+1; sliceSizes.resize(maxTime+1); std::fill(sliceSizes.begin(), sliceSizes.end(), 0); int nT; infile >> nT; for (int i = 0; i < nT; i++) { auto t = Triangle::create(); int tVs[3]; for (int j = 0; j < 3; j++) { infile >> tVs[j]; } int tNeighb[3]; for (int j = 0; j < 3; j++) { infile >> tNeighb[j]; } t->setVertices(tVs[0], tVs[1], tVs[2]); t->setTriangles(tNeighb[0], tNeighb[1], tNeighb[2]); trianglesAll.add(t); } infile >> line; assert(line == nT); printf("read %s\n", geometryFilename.c_str()); for (auto v : vs) sliceSizes.at(v->time)++; if (sphere) assert(sliceSizes.at(0) == 3); for (auto t : trianglesAll) { if (t->isUpwards()) { auto v = t->getVertexLeft(); if ( v->getTriangleLeft() == v->getTriangleRight()->getTriangleLeft() && v->getTriangleLeft()->getTriangleCenter() == v->getTriangleRight()->getTriangleCenter()->getTriangleLeft() ) { verticesFour.add(v); } } if (t->type != t->getTriangleRight()->type) { trianglesFlip.add(t); } } check(); imported = true; } std::string Universe::getGeometryFilename(int targetVolume, int slices, int seed) { std::string expectedFn = "geom/geometry-V" + std::to_string(targetVolume) + "-sl" + std::to_string(slices) + "-s" + std::to_string(seed); expectedFn += ".txt"; std::cout << "Searching for " << expectedFn << std::endl; std::ifstream f(expectedFn.c_str()); if (f.good()) { return expectedFn; } return ""; }
26.186813
138
0.646314
[ "geometry", "vector" ]
5ca9de85249a06471bcfe18b73ab23477688ab40
18,025
cpp
C++
ModuleSceneIntro.cpp
boscobarberesbert/Race-Car
be6865f64aab5dfb9def116a8e2d713d4d18bafe
[ "MIT" ]
null
null
null
ModuleSceneIntro.cpp
boscobarberesbert/Race-Car
be6865f64aab5dfb9def116a8e2d713d4d18bafe
[ "MIT" ]
null
null
null
ModuleSceneIntro.cpp
boscobarberesbert/Race-Car
be6865f64aab5dfb9def116a8e2d713d4d18bafe
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModuleSceneIntro.h" #include "Primitive.h" #include "PhysBody3D.h" ModuleSceneIntro::ModuleSceneIntro(Application* app, bool start_enabled) : Module(app, start_enabled) { spawnedBalls1 = false; spawnedBalls2 = false; } ModuleSceneIntro::~ModuleSceneIntro() {} // Load assets bool ModuleSceneIntro::Start() { LOG("Loading Intro assets"); bool ret = true; CreateCircuit(); return ret; } // Load assets bool ModuleSceneIntro::CleanUp() { LOG("Unloading Intro scene"); return true; } // Update update_status ModuleSceneIntro::Update(float dt) { for (int i = 0; i < primitives.Count(); i++) { primitives[i]->Update(); primitives[i]->Render(); } return UPDATE_CONTINUE; } void ModuleSceneIntro::OnCollision(PhysBody3D* body1, PhysBody3D* body2) { if (body1->type == ElementType::TUBE_SENSOR && body1->isSensor) { primitives[16]->wire = true; primitives[17]->wire = true; primitives[18]->wire = true; primitives[19]->wire = true; } else if (body1->type == ElementType::SPAWN_SENSOR_RAMP && body1->isSensor && spawnedBalls1 == false) { Sphere* sphere1 = new Sphere(2); sphere1->SetPos(230, 25, 90); primitives.PushBack(sphere1); App->physics->AddBody(*sphere1, 10.0f, ElementType::DAMAGE); sphere1->color = { 1,0,0,1 }; Sphere* sphere2 = new Sphere(2); sphere2->SetPos(220, 25, 90); primitives.PushBack(sphere2); App->physics->AddBody(*sphere2, 10.0f, ElementType::DAMAGE); sphere2->color = { 1,0,0,1 }; Sphere* sphere3 = new Sphere(2); sphere3->SetPos(210, 25, 90); primitives.PushBack(sphere3); App->physics->AddBody(*sphere3, 10.0f, ElementType::DAMAGE); sphere3->color = { 1,0,0,1 }; Sphere* sphere4 = new Sphere(2); sphere4->SetPos(200, 25, 90); primitives.PushBack(sphere4); App->physics->AddBody(*sphere4, 10.0f, ElementType::DAMAGE); sphere4->color = { 1,0,0,1 }; Sphere* sphere5 = new Sphere(2); sphere5->SetPos(190, 25, 90); primitives.PushBack(sphere5); App->physics->AddBody(*sphere5, 10.0f, ElementType::DAMAGE); sphere5->color = { 1,0,0,1 }; spawnedBalls1 = true; } else if (body1->type == ElementType::SPAWN_SENSOR_RAIL && body1->isSensor && spawnedBalls2 == false) { Sphere* sphere6 = new Sphere(2); sphere6->SetPos(210, 24, -55); primitives.PushBack(sphere6); App->physics->AddBody(*sphere6, 10.0f, ElementType::DAMAGE); sphere6->color = { 1,0,0,1 }; spawnedBalls2 = true; } else if (body1->type == ElementType::FINISH && body1->isSensor && checkpoint == 4) { App->player->minutesPassed = 0; App->player->secondsPassed = 0; App->player->lapTimer.Start(); checkpoint = 0; App->player->currentHUD = HUDStatus::VICTORY; spawnedBalls1 = false; spawnedBalls2 = false; primitives[16]->wire = false; primitives[17]->wire = false; primitives[18]->wire = false; primitives[19]->wire = false; } else if (body1->type == ElementType::CHECKPOINT && body1->isSensor && checkpoint == 0) { checkpoint = 1; App->player->currentHUD = HUDStatus::C1; } else if (body1->type == ElementType::CHECKPOINT2 && body1->isSensor && checkpoint == 1) { checkpoint = 2; App->player->currentHUD = HUDStatus::C2; } else if (body1->type == ElementType::CHECKPOINT3 && body1->isSensor && checkpoint == 2) { checkpoint = 3; App->player->currentHUD = HUDStatus::C3; } else if (body1->type == ElementType::CHECKPOINT4 && body1->isSensor && checkpoint == 3) { checkpoint = 4; App->player->currentHUD = HUDStatus::C4; } } void ModuleSceneIntro::CreateCircuit() { // Building scenario // Ground (lava) // 0 Cube* ground = new Cube(700, 1, 700); ground->SetPos(0, 0, 0); primitives.PushBack(ground); App->physics->AddBody(*ground, 0.0f, ElementType::DAMAGE, this, true); ground->color = { 1,0,0,1 }; // Ceiling (sky) // 1 Cube* ceiling = new Cube(500, 1, 500); ceiling->SetPos(100, 80, 0); primitives.PushBack(ceiling); App->physics->AddBody(*ceiling, 0.0f, ElementType::DAMAGE); ceiling->color = { 0.4,0.9,1,1 }; // Front wall (sky) // 2 Cube* frontWall = new Cube(500, 100, 1); frontWall->SetPos(100, 50, 200); primitives.PushBack(frontWall); App->physics->AddBody(*frontWall, 0.0f, ElementType::DAMAGE); frontWall->color = { 0.4,0.9,1,1 }; // Back wall (sky) // 3 Cube* backWall = new Cube(1, 100, 500); backWall->SetPos(-50, 50, 0); primitives.PushBack(backWall); App->physics->AddBody(*backWall, 0.0f, ElementType::DAMAGE); backWall->color = { 0.4,0.9,1,1 }; // Left wall (sky) // 4 Cube* leftWall = new Cube(1, 100, 500); leftWall->SetPos(300, 50, 0); primitives.PushBack(leftWall); App->physics->AddBody(*leftWall, 0.0f, ElementType::DAMAGE); leftWall->color = { 0.4,0.9,1,1 }; // Right wall (sky) // 5 Cube* rightWall = new Cube(500, 100, 1); rightWall->SetPos(100, 50, -150); primitives.PushBack(rightWall); App->physics->AddBody(*rightWall, 0.0f, ElementType::DAMAGE); rightWall->color = { 0.4,0.9,1,1 }; // Initial tunel // Left part // 6 Cube* leftTunel = new Cube(1, 10, 100); leftTunel->SetPos(5, 5, 10.5); primitives.PushBack(leftTunel); App->physics->AddBody(*leftTunel, 0.0f); // Right part // 7 Cube* rightTunel = new Cube(1, 10, 100); rightTunel->SetPos(-5, 5, 10.5); primitives.PushBack(rightTunel); App->physics->AddBody(*rightTunel, 0.0f); // Ramp up // 8 Cube* rampUp = new Cube(10, 100, 1); rampUp->SetPos(0, 1, 30); rampUp->SetRotation(75, { 1,0,0 }); primitives.PushBack(rampUp); App->physics->AddBody(*rampUp, 0.0f); rampUp->color = { 0.25,0.25,0.25,1 }; // Ramp down // 9 Cube* rampDown = new Cube(10, 30, 1); rampDown->SetPos(0, 10, 130); rampDown->SetRotation(285, { 1,0,0 }); primitives.PushBack(rampDown); App->physics->AddBody(*rampDown, 0.0f); rampDown->color = { 0.25,0.25,0.25 }; // Ramp jump // 10 Cube* rampJump = new Cube(10, 5, 1); rampJump->SetPos(0, 8, 140); rampJump->SetRotation(75, { 1,0,0 }); primitives.PushBack(rampJump); rampJump->color = { 0.25,0.25,0.25 }; App->physics->AddBody(*rampJump, 0.0f); // Cube to stop the car (Checkpoint) // Base // 11 Cube* stopBase = new Cube(60, 1, 15); stopBase->SetPos(22.5, 5, 175); primitives.PushBack(stopBase); App->physics->AddBody(*stopBase, 0.0f); // Wall // 12 Cube* stopWall = new Cube(15, 15, 1); stopWall->SetPos(0, 12.5, 182.5); primitives.PushBack(stopWall); App->physics->AddBody(*stopWall, 0.0f); // Fence // 13 Cube* stopFence = new Cube(15, 2, 1); stopFence->SetPos(0, 6, 167.5); primitives.PushBack(stopFence); App->physics->AddBody(*stopFence, 0.0f); // Platforms to jump on // 14 Cube* platformJump1 = new Cube(30, 1, 15); platformJump1->SetPos(97.5, 10, 175); primitives.PushBack(platformJump1); App->physics->AddBody(*platformJump1, 0.0f); // 15 Cube* platformJump2 = new Cube(45, 1, 15); platformJump2->SetPos(157.5, 12.5, 175); primitives.PushBack(platformJump2); App->physics->AddBody(*platformJump2, 0.0f); // Tube // 16 Cube* tube1 = new Cube(15, 10, 1); tube1->SetPos(210, 13.25, 167.5); primitives.PushBack(tube1); App->physics->AddBody(*tube1, 0.0f); // 17 Cube* tube2 = new Cube(15, 15, 1); tube2->SetPos(210, 10.75, 182.5); primitives.PushBack(tube2); App->physics->AddBody(*tube2, 0.0f); // 18 Cube* tube3 = new Cube(1, 15, 15); tube3->SetPos(202.5, 10.75, 175); primitives.PushBack(tube3); App->physics->AddBody(*tube3, 0.0f); // 19 Cube* tube4 = new Cube(1, 30, 15); tube4->SetPos(217.5, 18.25, 175); primitives.PushBack(tube4); App->physics->AddBody(*tube4, 0.0f); // Under tube platform (Checkpoint) // 20 Cube* tubePlatform = new Cube(15, 1, 15); tubePlatform->SetPos(210, 1, 175); primitives.PushBack(tubePlatform); App->physics->AddBody(*tubePlatform, 0.0f); // Tube sensor // 21 Cube* tubeSensor = new Cube(15, 1, 15); tubeSensor->SetPos(210, 10, 175); tubeSensor->wire = true; primitives.PushBack(tubeSensor); App->physics->AddBody(*tubeSensor, 0.0f, ElementType::TUBE_SENSOR, this, true); // Tube Bounds // 22 Cube* tubeFence1 = new Cube(15, 2, 1); tubeFence1->SetPos(210, 1, 182.5); primitives.PushBack(tubeFence1); App->physics->AddBody(*tubeFence1, 0.0f); // 23 Cube* tubeFence2 = new Cube(1, 2, 15); tubeFence2->SetPos(202.5, 1, 175); primitives.PushBack(tubeFence2); App->physics->AddBody(*tubeFence2, 0.0f); // 24 Cube* tubeFence3 = new Cube(1, 2, 15); tubeFence3->SetPos(217.5, 1, 175); primitives.PushBack(tubeFence3); App->physics->AddBody(*tubeFence3, 0.0f); // 25 Cube* tubeRamp = new Cube(15, 1, 15); tubeRamp->SetPos(210, 3, 161); tubeRamp->SetRotation(15, { 1,0,0 }); primitives.PushBack(tubeRamp); App->physics->AddBody(*tubeRamp, 0.0f); tubeRamp->color = { 0.25,0.25,0.25,1 }; // 26 Cube* hugeRamp = new Cube(60, 1, 60); hugeRamp->SetPos(210, 10, 115); hugeRamp->SetRotation(15, { 1,0,0 }); primitives.PushBack(hugeRamp); App->physics->AddBody(*hugeRamp, 0.0f); hugeRamp->color = { 0.25,0.25,0.25,1 }; // Balls sensor (at jump) // 27 Cube* ballsSensor = new Cube(15, 5, 1); ballsSensor->SetPos(210, 10, 155); ballsSensor->wire = true; primitives.PushBack(ballsSensor); App->physics->AddBody(*ballsSensor, 0.0f, ElementType::SPAWN_SENSOR_RAMP, this, true); // Balls for constraints links // 28 Sphere* sphere1 = new Sphere(1); sphere1->SetPos(0, 50, 90); primitives.PushBack(sphere1); App->physics->AddBody(*sphere1, 0.0f); // 29 Sphere* sphere2 = new Sphere(5); sphere2->SetPos(0, 20, 90); primitives.PushBack(sphere2); App->physics->AddBody(*sphere2, 100.0f); sphere2->body->Push(1500.0f, 0.0f, 0.0f); sphere2->color = { 1,1,0,1 }; // Platforms to jump (Checkpoint) // 30 Cube* landingPlatform1 = new Cube(15, 1, 15); landingPlatform1->SetPos(210, 20, 25); primitives.PushBack(landingPlatform1); App->physics->AddBody(*landingPlatform1, 0.0f); // 31 (Sensor Trap Ball) Cube* landingPlatform2 = new Cube(15, 1, 25); landingPlatform2->SetPos(210, 5, 10); primitives.PushBack(landingPlatform2); App->physics->AddBody(*landingPlatform2, 0.0f); // Sensor to spawn trap ball // 32 Cube* trapBallSensor = new Cube(5, 5, 1); trapBallSensor->SetPos(210, 5, 5); trapBallSensor->wire = true; primitives.PushBack(trapBallSensor); App->physics->AddBody(*trapBallSensor, 0.0f, ElementType::SPAWN_SENSOR_RAIL, this, true); // Rails // 33 Cube* rail1 = new Cube(1, 1, 15); rail1->SetPos(208.5, 5, -10); primitives.PushBack(rail1); App->physics->AddBody(*rail1, 0.0f); // 34 Cube* rail2 = new Cube(1, 1, 15); rail2->SetPos(211.5, 5, -10); primitives.PushBack(rail2); App->physics->AddBody(*rail2, 0.0f); // 35 (Ramp) Cube* rail3 = new Cube(1, 1, 45); rail3->SetPos(208.5, 14.5, -37.5); rail3->SetRotation(25, { 1,0,0 }); primitives.PushBack(rail3); App->physics->AddBody(*rail3, 0.0f); // 36 (Ramp) Cube* rail4 = new Cube(1, 1, 45); rail4->SetPos(211.5, 14.5, -37.5); rail4->SetRotation(25, { 1,0,0 }); primitives.PushBack(rail4); App->physics->AddBody(*rail4, 0.0f); // Mini platform after rails // 37 Cube* landingPlatform3 = new Cube(7, 1, 13); landingPlatform3->SetPos(210, 24, -64); primitives.PushBack(landingPlatform3); App->physics->AddBody(*landingPlatform3, 0.0f); // Platform to jump on (Checkpoint) // 38 Cube* landingPlatform4 = new Cube(15, 1, 15); landingPlatform4->SetPos(210, 15, -100); primitives.PushBack(landingPlatform4); App->physics->AddBody(*landingPlatform4, 0.0f); // Balls for constraints links // 39 Sphere* sphere3 = new Sphere(1); sphere3->SetPos(210, 55, 45); primitives.PushBack(sphere3); App->physics->AddBody(*sphere3, 0.0f); // 40 Sphere* sphere4 = new Sphere(5); sphere4->SetPos(210, 25, 45); primitives.PushBack(sphere4); App->physics->AddBody(*sphere4, 100.0f); sphere4->body->Push(1500.0f, 0.0f, 0.0f); sphere4->color = { 1,1,0,1 }; // Initial platform // 41 Cube* initPlatform = new Cube(9, 1, 135); initPlatform->SetPos(0, 1, -37.5); primitives.PushBack(initPlatform); App->physics->AddBody(*initPlatform, 0.0f); // Initial sensor // 42 Cube* initSensor = new Cube(1, 1, 1); initSensor->SetPos(0, 3, 5); primitives.PushBack(initSensor); App->physics->AddBody(*initSensor, 0.0f, ElementType::FINISH, this, true); initSensor->wire = true; // Death catwalk // 43 Cube* catwalk1 = new Cube(50, 1, 15); catwalk1->SetPos(150, 11, -100); primitives.PushBack(catwalk1); App->physics->AddBody(*catwalk1, 0.0f); // Death catwalk Square // 44 Cube* deathCatwalkSquare = new Cube(30, 1, 30); deathCatwalkSquare->SetPos(110, 11, -100); primitives.PushBack(deathCatwalkSquare); App->physics->AddBody(*deathCatwalkSquare, 0.0f); // Death catwalk // 45 Cube* catwalk2 = new Cube(50, 1, 15); catwalk2->SetPos(70, 11, -100); primitives.PushBack(catwalk2); App->physics->AddBody(*catwalk2, 0.0f); // Balls for constraints links // 46 Sphere* sphere5 = new Sphere(1); sphere5->SetPos(150, 47, -100); primitives.PushBack(sphere5); App->physics->AddBody(*sphere5, 0.0f); // 47 Sphere* sphere6 = new Sphere(5); sphere6->SetPos(150, 17, -100); primitives.PushBack(sphere6); App->physics->AddBody(*sphere6, 1000000.0f); sphere6->body->Push(25000000.0f, 0.0f, 0.0f); sphere6->color = { 1,1,0,1 }; // 48 Sphere* sphere7 = new Sphere(11); sphere7->SetPos(110, 11, -100); primitives.PushBack(sphere7); App->physics->AddBody(*sphere7, 0.0f, ElementType::DAMAGE); sphere7->color = { 1,0,0,1 }; // 49 Sphere* sphere8 = new Sphere(1); sphere8->SetPos(90, 20, -100); primitives.PushBack(sphere8); App->physics->AddBody(*sphere8, 0.0f); // 50 Sphere* sphere9 = new Sphere(1.5); sphere9->SetPos(90, 15, -100); primitives.PushBack(sphere9); App->physics->AddBody(*sphere9, 10.0f, ElementType::DAMAGE, App->player, true); sphere9->body->Push(0.0f, 0.0f, 100000.0f); sphere9->color = { 1,0,0,1 }; // 51 Sphere* sphere10 = new Sphere(1); sphere10->SetPos(70, 20, -100); primitives.PushBack(sphere10); App->physics->AddBody(*sphere10, 0.0f); // 52 Sphere* sphere11 = new Sphere(1.5); sphere11->SetPos(70, 15, -100); primitives.PushBack(sphere11); App->physics->AddBody(*sphere11, 10.0f, ElementType::DAMAGE, App->player, true); sphere11->body->Push(0.0f, 0.0f, -100000.0f); sphere11->color = { 1,0,0,1 }; // 53 Sphere* sphere12 = new Sphere(1); sphere12->SetPos(50, 20, -100); primitives.PushBack(sphere12); App->physics->AddBody(*sphere12, 0.0f); // 54 Sphere* sphere13 = new Sphere(1.5); sphere13->SetPos(50, 15, -100); primitives.PushBack(sphere13); App->physics->AddBody(*sphere13, 10.0f, ElementType::DAMAGE, App->player, true); sphere13->body->Push(0.0f, 0.0f, 100000.0f); sphere13->color = { 1,0,0,1 }; // 55 Cube* finalPlatform1 = new Cube(10, 10, 1); finalPlatform1->SetPos(0, 1, -105); primitives.PushBack(finalPlatform1); App->physics->AddBody(*finalPlatform1, 0.0f); // 56 Cube* finalPlatform2 = new Cube(1, 10, 10); finalPlatform2->SetPos(5, 1, -100); primitives.PushBack(finalPlatform2); App->physics->AddBody(*finalPlatform2, 0.0f); // 57 Cube* finalPlatform3 = new Cube(1, 10, 10); finalPlatform3->SetPos(-5, 1, -100); primitives.PushBack(finalPlatform3); App->physics->AddBody(*finalPlatform3, 0.0f); // Checkpoints // 58 Cube* checkpoint = new Cube(1, 1, 1); checkpoint->SetPos(0, 7, 175); primitives.PushBack(checkpoint); App->physics->AddBody(*checkpoint, 0.0f, ElementType::CHECKPOINT, this, true); checkpoint->wire = true; // 59 Cube* checkpoint2 = new Cube(1, 1, 1); checkpoint2->SetPos(210, 3, 175); primitives.PushBack(checkpoint2); App->physics->AddBody(*checkpoint2, 0.0f, ElementType::CHECKPOINT2, this, true); checkpoint2->wire = true; // 60 Cube* checkpoint3 = new Cube(1, 1, 1); checkpoint3->SetPos(210, 22, 25); primitives.PushBack(checkpoint3); App->physics->AddBody(*checkpoint3, 0.0f, ElementType::CHECKPOINT3, this, true); checkpoint3->wire = true; // 61 Cube* checkpoint4 = new Cube(1, 1, 1); checkpoint4->SetPos(210, 17, -100); primitives.PushBack(checkpoint4); App->physics->AddBody(*checkpoint4, 0.0f, ElementType::CHECKPOINT4, this, true); checkpoint4->wire = true; // Adding constraints App->physics->AddConstraintP2P(*sphere1->body, *sphere2->body, vec3{ 0.0f, 0.0f, 0.0f }, vec3{ sphere1->transform.translation().x - sphere2->transform.translation().x, sphere1->transform.translation().y - sphere2->transform.translation().y, sphere1->transform.translation().z - sphere2->transform.translation().z }); App->physics->AddConstraintP2P(*sphere3->body, *sphere4->body, vec3{ 0.0f, 0.0f, 0.0f }, vec3{ sphere3->transform.translation().x - sphere4->transform.translation().x, sphere3->transform.translation().y - sphere4->transform.translation().y, sphere3->transform.translation().z - sphere4->transform.translation().z }); App->physics->AddConstraintP2P(*sphere5->body, *sphere6->body, vec3{ 0.0f, 0.0f, 0.0f }, vec3{ sphere5->transform.translation().x - sphere6->transform.translation().x, sphere5->transform.translation().y - sphere6->transform.translation().y, sphere5->transform.translation().z - sphere6->transform.translation().z }); App->physics->AddConstraintP2P(*sphere8->body, *sphere9->body, vec3{ 0.0f, 0.0f, 0.0f }, vec3{ sphere8->transform.translation().x - sphere9->transform.translation().x, sphere8->transform.translation().y - sphere9->transform.translation().y, sphere8->transform.translation().z - sphere9->transform.translation().z }); App->physics->AddConstraintP2P(*sphere10->body, *sphere11->body, vec3{ 0.0f, 0.0f, 0.0f }, vec3{ sphere10->transform.translation().x - sphere11->transform.translation().x, sphere10->transform.translation().y - sphere11->transform.translation().y, sphere10->transform.translation().z - sphere11->transform.translation().z }); App->physics->AddConstraintP2P(*sphere12->body, *sphere13->body, vec3{ 0.0f, 0.0f, 0.0f }, vec3{ sphere12->transform.translation().x - sphere13->transform.translation().x, sphere12->transform.translation().y - sphere13->transform.translation().y, sphere12->transform.translation().z - sphere13->transform.translation().z }); }
30.19263
325
0.677947
[ "render", "transform" ]
5cac4d4a80db7adbec8d103b10e30d0f3a92a7ce
8,400
cpp
C++
GLAC/tests/unit_tests/iotests.cpp
hmvege/GluonicLQCD
9bb7466fce408bf51cb98d65f639acd37d034d62
[ "MIT" ]
1
2019-04-12T08:12:30.000Z
2019-04-12T08:12:30.000Z
GLAC/tests/unit_tests/iotests.cpp
hmvege/GluonicLQCD
9bb7466fce408bf51cb98d65f639acd37d034d62
[ "MIT" ]
2
2021-03-14T12:30:39.000Z
2021-03-14T12:33:17.000Z
GLAC/tests/unit_tests/iotests.cpp
hmvege/GluonicLQCD
9bb7466fce408bf51cb98d65f639acd37d034d62
[ "MIT" ]
1
2020-05-14T02:12:33.000Z
2020-05-14T02:12:33.000Z
#include "iotests.h" // Including chrono for taking IO times. #include <chrono> #include "parallelization/parallel.h" #include "config/parameters.h" #include "io/fieldio.h" IOTests::IOTests() { } // IO tests bool IOTests::testIOLatticeWriteRead() { if ((m_processRank == 0) && m_verbose) { printf("Running Lattice IO tests on lattice of size %d^3 x %d\n", Parameters::getNSpatial(), Parameters::getNTemporal()); } using std::chrono::steady_clock; using std::chrono::duration_cast; using std::chrono::duration; bool passed = true; if (Parallel::ParallelParameters::active) { // Create lattice // Initializes the lattice and allocates it with correct dimensions Lattice<SU3> * LBefore = new Lattice<SU3>[4]; Lattice<SU3> * LAfter = new Lattice<SU3>[4]; for (int i = 0; i < 4; i++) LBefore[i].allocate(m_dim); for (int i = 0; i < 4; i++) LAfter[i].allocate(m_dim); for (int mu = 0; mu < 4; mu++) { for (unsigned long iSite = 0; iSite < m_subLatticeSize; iSite++) { LBefore[mu][iSite] = m_SU3Generator->generateRandom(); // Fully random } } steady_clock::time_point t0_write; steady_clock::time_point t1_write; steady_clock::time_point t0_read; steady_clock::time_point t1_read; t0_write = steady_clock::now(); // Save lattice IO::FieldIO::writeFieldToFile(LBefore, 0); t1_write= steady_clock::now(); // Since we are by default writing to output, we temporarily set the input to be output. std::string tmpInputFolder = Parameters::getInputFolder(); Parameters::setInputFolder("/output/" + Parameters::getBatchName() + "/field_configurations/"); Parallel::Communicator::setBarrierActive(); // Simple cp from writeFieldToFile() std::string cfg_name = Parameters::getBatchName() + "_b" + std::to_string(Parameters::getBeta()) + "_N" + std::to_string(Parameters::getNSpatial()) + "_NT" + std::to_string(Parameters::getNTemporal()) + "_np" + std::to_string(Parallel::Communicator::getNumProc()) + "_config" + std::string("00000") + ".bin"; t0_read = steady_clock::now(); // Load into new lattice IO::FieldIO::loadFieldConfiguration(cfg_name, LAfter); t1_read = steady_clock::now(); // Resets the input folder Parameters::setInputFolder(tmpInputFolder); if (m_processRank == 0 && m_verbose) { printf(" Write time: %.16f seconds.\n Read time: %.16f\n", duration_cast<duration<double>>(t1_write - t0_write).count(), duration_cast<duration<double>>(t1_read - t0_read).count()); } // Compare loaded lattice with created lattice for (int mu = 0; mu < 4; mu++) { for (unsigned long iSite = 0; iSite < m_subLatticeSize; iSite++) { for (int i = 0; i < 18; i++) { if (fabs(LBefore[mu][iSite][i] - LAfter[mu][iSite][i]) > 1e-15) { cout << "Error in: " << LBefore[mu][iSite][i] << " " << LAfter[mu][iSite][i] << endl; passed = false; break; } } } } delete [] LBefore; delete [] LAfter; } if (passed) { if (m_processRank == 0) cout << "PASSED: IO lattice write and load." << endl; } else { if (m_processRank == 0) cout << "FAILED: IO lattice write or load." << endl; } return passed; } bool IOTests::testIOWriteDoubles() { if ((m_processRank == 0) && m_verbose) { printf(" Testing IO doubles writing for lattice of size %d^3 x %d\n", Parameters::getNSpatial(), Parameters::getNTemporal()); } using std::chrono::steady_clock; using std::chrono::duration_cast; using std::chrono::duration; bool passed = true; if (Parallel::ParallelParameters::active) { // Create lattice // Initializes the lattice and allocates it with correct dimensions Lattice<double> LBefore; Lattice<double> LAfter; LBefore.allocate(m_dim); LAfter.allocate(m_dim); for (unsigned long iSite = 0; iSite < m_subLatticeSize; iSite++) { LBefore[iSite] = m_uniform_distribution(m_generator); // Fully random } steady_clock::time_point t0_write; steady_clock::time_point t1_write; t0_write = steady_clock::now(); std::string filenameIOTest = "ioDoublesIOTest"; // Save lattice IO::FieldIO::writeDoublesFieldToFile(LBefore, 0, filenameIOTest); t1_write= steady_clock::now(); // Since we are by default writing to output, we temporarily set the input to be output. std::string tmpInputFolder = Parameters::getInputFolder(); Parameters::setInputFolder("/output/" + Parameters::getBatchName() + "/field_configurations/"); Parallel::Communicator::setBarrierActive(); // Simple cp from writeFieldToFile() std::string cfg_name = Parameters::getBatchName() + "_b" + std::to_string(Parameters::getBeta()) + "_N" + std::to_string(Parameters::getNSpatial()) + "_NT" + std::to_string(Parameters::getNTemporal()) + "_np" + std::to_string(Parallel::Communicator::getNumProc()) + "_config" + std::string("00000") + ".bin"; std::string filenamePath = Parameters::getFilePath() + Parameters::getOutputFolder() + Parameters::getBatchName() + "/scalar_fields/" + filenameIOTest + "/" + cfg_name; // Load into new lattice MPI_File file; MPI_File_open(Parallel::ParallelParameters::ACTIVE_COMM, filenamePath.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file); MPI_Offset offset = 0; std::vector<unsigned int> N =Parameters::getN(); long long nt = 0, nz = 0, ny = 0, nx = 0; for (unsigned long int t = 0; t < N[3]; t++) { nt = (Parallel::Neighbours::getProcessorDimensionPosition(3) * N[3] + t); for (unsigned long int z = 0; z < N[2]; z++) { nz = (Parallel::Neighbours::getProcessorDimensionPosition(2) * N[2] + z); for (unsigned long int y = 0; y < N[1]; y++) { ny = (Parallel::Neighbours::getProcessorDimensionPosition(1) * N[1] + y); for (unsigned long int x = 0; x < N[0]; x++) { nx = (Parallel::Neighbours::getProcessorDimensionPosition(0) * N[0] + x); offset = Parallel::Index::getGlobalIndex(nx,ny,nz,nt)*sizeof(double); MPI_File_read_at(file, offset, &LAfter[Parallel::Index::getIndex(x,y,z,t)], 1, MPI_DOUBLE, MPI_STATUS_IGNORE); } } } } MPI_File_close(&file); // Resets the input folder Parameters::setInputFolder(tmpInputFolder); if (m_processRank == 0 && m_verbose) { printf(" Write time: %.16f seconds.\n", duration_cast<duration<double>>(t1_write - t0_write).count()); } // Compare loaded lattice with created lattice for (unsigned long iSite = 0; iSite < m_subLatticeSize; iSite++) { for (int i = 0; i < 18; i++) { if (fabs(LBefore[iSite] - LAfter[iSite]) > 1e-15) { cout << "Error in: " << LBefore[iSite] << " " << LAfter[iSite] << endl; passed = false; break; } } } } if (passed) { if (m_processRank == 0) cout << "PASSED: IO lattice doubles write and load." << endl; } else { if (m_processRank == 0) cout << "FAILED: IO lattice doubles write or load." << endl; } return passed; } bool IOTests::runIOTests() { bool passed = (testIOWriteDoubles() && testIOLatticeWriteRead()); if (m_processRank == 0) { if (passed) { cout << "PASSED: IO properties." << endl; } else { cout << "FAILURE: IO properties." << endl; } } Parallel::Communicator::setBarrier(); return passed; }
35.146444
136
0.56381
[ "vector" ]
5cb648eabb56b0b78ca66826f5f2be00a306262f
728
cpp
C++
examples/galaga/src/galaga/PongBall.cpp
loafofpiecrust/lfant
a38826e325a50dffb5d030d71abcd58de59e8389
[ "Apache-2.0" ]
4
2017-03-06T16:59:27.000Z
2021-07-23T12:57:07.000Z
examples/galaga/src/galaga/PongBall.cpp
loafofpiecrust/lfant
a38826e325a50dffb5d030d71abcd58de59e8389
[ "Apache-2.0" ]
null
null
null
examples/galaga/src/galaga/PongBall.cpp
loafofpiecrust/lfant
a38826e325a50dffb5d030d71abcd58de59e8389
[ "Apache-2.0" ]
null
null
null
#include <galaga/PongBall.h> // internal // external #include <lfant/Input.h> #include <lfant/Console.h> #include <lfant/Transform.h> using namespace lfant; namespace pong { IMPLEMENT_TYPE(lfant::Component, pong::Ball) Ball::Ball() { } Ball::~Ball() { } void Ball::Init() { // ConnectEvent(SENDER(game->input, Jump_Down), RECEIVER(this, StartGame)); } void Ball::Update() { if(game->input->GetButtonDown("Jump")) { owner->TriggerEvent("ApplyCentralForce", vec3(100,100,0)); } if(game->input->GetButtonDown("Fire")) { owner->transform->SetPosition(vec3(0,0,0)); } } void Ball::FixedUpdate() { } void Ball::StartGame() { Log("Ball starting"); owner->TriggerEvent("ApplyCentralForce", vec3(100,100,0)); } }
14
75
0.678571
[ "transform" ]
5cbc653503c8246a1fd584aa58fa6218bfd10e48
1,724
hpp
C++
sw/src/batch.hpp
lvandam/pairhmm_posit_hdl_arrow
428e935d1f3cb78d881ec590cfcc1f85806c4589
[ "Apache-2.0" ]
1
2019-07-01T10:25:43.000Z
2019-07-01T10:25:43.000Z
pairhmm_compare/src/batch.hpp
lvandam/pairhmm_posit_cpp
580c45d65913bc683aabc9abf3049291bf7c82e3
[ "Apache-2.0" ]
null
null
null
pairhmm_compare/src/batch.hpp
lvandam/pairhmm_posit_cpp
580c45d65913bc683aabc9abf3049291bf7c82e3
[ "Apache-2.0" ]
2
2019-07-01T10:42:31.000Z
2021-02-05T09:10:13.000Z
#ifndef __BATCH_H #define __BATCH_H #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <sys/time.h> #include <posit/posit> #include "defines.hpp" using namespace sw::unum; typedef struct struct_workload { int pairs; uint32_t *hapl; uint32_t *read; int batches; uint32_t *by; uint32_t *bx; size_t *bbytes; size_t bytes; uint64_t cups; } t_workload; typedef union union_prob { float f; // as float uint32_t b; // as binary unsigned char x[sizeof(float)]; // as bytes } t_prob; typedef struct struct_probs { t_prob p[8]; // lambda_1, lambda_2, alpha, beta, delta, upsilon, zeta, eta } t_probs; typedef struct struct_bbase { unsigned char base; } t_bbase; // Initial values and batch configuration typedef struct struct_init { uint32_t initials[PIPE_DEPTH]; // 0 ... 511 uint32_t batch_bytes; // 512 ... 543 uint32_t x_size; // 544 ... 575 uint32_t x_padded; // 576 ... 607 uint32_t y_size; // 608 ... 639 uint32_t y_padded; // 640 ... 671 uint32_t x_bppadded; // 672 ... 704 uint8_t padding[40]; // } t_inits; typedef struct struct_batch { t_inits init; std::vector<t_bbase> read; std::vector<t_bbase> hapl; std::vector<t_probs> prob; } t_batch; void fill_batch(t_batch& batch, string& x_string, string& y_string, int batch_num, int x, int y, float initial); int batchToCore(int batch, std::vector<uint32_t>& batch_offsets); int batchToCoreBatch(int batch, std::vector<uint32_t>& batch_length); #endif //__BATCH_H
24.628571
112
0.62471
[ "vector" ]
5cc934c4f2232ed99ab3c7326072c6777e83dc4c
2,277
cpp
C++
activity_3/src/concordeSolver.cpp
lucasguesserts/MO824A-combinatorial-optimization
a88569e4496c0ed4f89a4e8bac7ab8f42f6cb7d4
[ "MIT" ]
null
null
null
activity_3/src/concordeSolver.cpp
lucasguesserts/MO824A-combinatorial-optimization
a88569e4496c0ed4f89a4e8bac7ab8f42f6cb7d4
[ "MIT" ]
null
null
null
activity_3/src/concordeSolver.cpp
lucasguesserts/MO824A-combinatorial-optimization
a88569e4496c0ed4f89a4e8bac7ab8f42f6cb7d4
[ "MIT" ]
null
null
null
#include "concordeSolver.hpp" extern "C" { #include <concorde.h> } #include <iostream> #include <vector> #include <numeric> #include <tuple> #include <stdexcept> std::vector<int> solve_tsp (const std::vector<std::vector<int>>& distance) { const int ncount = distance.size(); if (ncount < 5) { throw std::runtime_error("Less than 5 nodes."); } std::vector<int> tour(distance.size()); int rval; int seed = rand(); CCrandstate rstate; CCutil_sprand(seed, &rstate); const int ecount = (ncount * (ncount - 1)) / 2; std::vector<int> elist(ecount * 2); std::vector<int> elen(ecount); int edge = 0; int edgeWeight = 0; for (int i = 0; i < ncount; i++) { for (int j = i + 1; j < ncount; j++) { elist[edge++] = i; elist[edge++] = j; elen[edgeWeight++] = distance[i][j]; } } char *name = CCtsp_problabel(" "); CCdatagroup dat; CCutil_init_datagroup (&dat); rval = CCutil_graph2dat_matrix( ncount, ecount, elist.data(), elen.data(), 1, &dat ); double optval, *timebound = nullptr; int success, foundtour, hit_timebound = 0; rval = CCtsp_solve_dat ( ncount, &dat, nullptr, tour.data(), nullptr, &optval, &success, &foundtour, name, timebound, &hit_timebound, 1, &rstate ); if (rval != 0) { throw std::runtime_error("error solving TSP with concorde"); } return tour; } std::tuple<double, std::vector<int>> solve_tsp (const std::vector<std::vector<double>>& distance) { constexpr int multiplier = 1e+4; std::vector<std::vector<int>> integerDistances( distance.size(), std::vector<int>(distance[0].size(), 0) ); for (std::size_t i = 0; i < distance.size(); ++i) { for (std::size_t j = 0; j < distance.size(); ++j) { integerDistances[i][j] = multiplier * distance[i][j]; } } std::vector<int> tour = solve_tsp(integerDistances); ld cost = 0; FOR(i, SZ(tour)) cost += distance[tour[i]][tour[(i + 1) % SZ(tour)]]; return tuple<double, vi>(cost, tour); }
23.968421
97
0.541502
[ "vector" ]
5cca5e9f380e26bd13a81569be2dbc25db575117
5,468
hpp
C++
Code/Tenshi/Compiler/BuiltinType.hpp
NotKyon/Tenshi
9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7
[ "Zlib" ]
null
null
null
Code/Tenshi/Compiler/BuiltinType.hpp
NotKyon/Tenshi
9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7
[ "Zlib" ]
8
2016-11-17T00:39:03.000Z
2016-11-29T14:46:27.000Z
Code/Tenshi/Compiler/BuiltinType.hpp
NotKyon/Tenshi
9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7
[ "Zlib" ]
null
null
null
#pragma once #include <Core/Types.hpp> #include "Operator.hpp" namespace Tenshi { namespace Compiler { // Whether a cast is specified explicitly or is implicit enum class ECastMode { // Cast was explicitly requested Explicit, // Implicit cast into input parameter Input, // Implicit cast from return value or into output parameter Output }; // Base built-in type enum class EBuiltinType : Ax::uint8 { // Invalid type Invalid, // Not a built-in type; custom user type UserDefined, // Nothing Void, // Anything Any, // Boolean value Boolean, // 8-bit signed integer Int8, // 16-bit signed integer Int16, // 32-bit signed integer Int32, // 64-bit signed integer Int64, // 128-bit signed integer Int128, // 8-bit unsigned integer UInt8, // 16-bit unsigned integer UInt16, // 32-bit unsigned integer UInt32, // 64-bit unsigned integer UInt64, // 128-bit unsigned integer UInt128, // 16-bit float Float16, // 32-bit float Float32, // 64-bit float Float64, // Unsigned-normalized 8-bit float UNorm8, // Unsigned-normalized 16-bit float UNorm16, // Unsigned-normalized 32-bit float UNorm32, // Unsigned-normalized 64-bit float UNorm64, // Signed-normalized 8-bit float SNorm8, // Signed-normalized 16-bit float SNorm16, // Signed-normalized 32-bit float SNorm32, // Signed-normalized 64-bit float SNorm64, // 128-bit SIMD vector (no specific format) SIMDVector128, // 256-bit SIMD vector SIMDVector256, // 128-bit SIMD vector of 4 Float32 items SIMDVector128_4Float32, // 128-bit SIMD vector of 2 Float64 items SIMDVector128_2Float64, // 128-bit SIMD vector of 4 Int32 items SIMDVector128_4Int32, // 128-bit SIMD vector of 2 Int64 items SIMDVector128_2Int64, // 256-bit SIMD vector of 8 Float32 items SIMDVector256_8Float32, // 256-bit SIMD vector of 4 Float64 items SIMDVector256_4Float64, // 256-bit SIMD vector of 8 Int32 items SIMDVector256_8Int32, // 256-bit SIMD vector of 4 Int64 items SIMDVector256_4Int64, // C string (const char *) ConstUTF8Pointer, // C string (const wchar_t *) ConstUTF16Pointer, // String object StringObject, // Array object ArrayObject, // Linked list object LinkedListObject, // Binary tree object BinaryTreeObject, // 2 x Float32 as a vector Vector2f, // 3 x Float32 as a vector Vector3f, // 4 x Float32 as a vector Vector4f, // 2x2 x Float32 as a matrix Matrix2f, // 3x3 x Float32 as a matrix Matrix3f, // 4x4 x Float32 as a matrix Matrix4f, // 2x3 x Float32 as a matrix Matrix23f, // 2x4 x Float32 as a matrix Matrix24f, // 3x2 x Float32 as a matrix Matrix32f, // 3x4 x Float32 as a matrix Matrix34f, // 4x2 x Float32 as a matrix Matrix42f, // 4x3 x Float32 as a matrix Matrix43f, // 4 x Float32 as a quaternion Quaternionf }; // Details of a built-in type struct SBuiltinTypeInfo { bool bIsSigned; bool bIsUnsigned; bool bIsFloat; bool bIsNormalized; bool bIsSIMD; bool bIsPointer; //if set then cBits should be ignored unsigned cRows; unsigned cColumns; unsigned cBits; bool bNoPromote; }; // Retrieve the built-in type information for a given type const SBuiltinTypeInfo &GetBuiltinTypeInfo( EBuiltinType T ); // Convert a built-in type to a string const char *BuiltinTypeToString( EBuiltinType Type ); // Check whether a built-in type is trivial bool IsTrivial( EBuiltinType T ); // Check whether a type is a plain-old-data type bool IsPOD( EBuiltinType T ); // Check whether a type is a string (of some form) bool IsString( EBuiltinType T ); // Check whether a type is a number bool IsNumber( EBuiltinType T ); // Check whether a type is an integer number bool IsIntNumber( EBuiltinType T ); // Check whether a type is a real number bool IsRealNumber( EBuiltinType T ); // Check whether a type is an SIMD type bool IsSIMD( EBuiltinType T ); // Check whether a type is signed bool IsSigned( EBuiltinType T ); // Check whether a type is unsigned bool IsUnsigned( EBuiltinType T ); // Retrieve the number of rows in a type unsigned GetTypeRows( EBuiltinType T ); // Retrieve the number of columns in a type unsigned GetTypeColumns( EBuiltinType T ); // Retrieve the size of a built-in type, in bytes unsigned GetTypeSize( EBuiltinType T ); // Determine the type promotion between two types (Invalid if one can't be converted to the other) EBuiltinType FindTypePromotion( EBuiltinType T1, EBuiltinType T2 ); // Retrieve the component type of a vector/SIMD type EBuiltinType GetVectorTypeComponentType( EBuiltinType T ); // Determine the swizzle type from the number of accesses and the core type EBuiltinType GetVectorSwizzleType( EBuiltinType ComponentType, unsigned cAxes ); // Convert a type to its integer equivalent (for casting) EBuiltinType GetCastSafeType( EBuiltinType T ); // Convert a given built-in type to its signed equivalent EBuiltinType MakeTypeSigned( EBuiltinType T ); // Convert a given built-in type to its unsigned equivalent EBuiltinType MakeTypeUnsigned( EBuiltinType T ); // Get the built-in cast operator for two built-in types // // Returns EBuiltinOp::None if no cast is necessary or EBuiltinOp::Invalid // if there is no direct cast between the types ECast GetCastForTypes( EBuiltinType FromT, EBuiltinType ToT, ECastMode Mode ); }}
26.673171
99
0.713058
[ "object", "vector" ]
5ccab8444c184993bc2b314c7881ad8d3fa12b38
5,473
cxx
C++
TBDataAnalysis/202106_DESY/CheckCalib.cxx
polesell/DREMTubes
e396c37220baf458e66c69c806e92245521d8d88
[ "MIT" ]
null
null
null
TBDataAnalysis/202106_DESY/CheckCalib.cxx
polesell/DREMTubes
e396c37220baf458e66c69c806e92245521d8d88
[ "MIT" ]
null
null
null
TBDataAnalysis/202106_DESY/CheckCalib.cxx
polesell/DREMTubes
e396c37220baf458e66c69c806e92245521d8d88
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <TTree.h> #include <TBranch.h> #include <TFile.h> #include <TH1.h> #include <TMath.h> #include "../../TBDataPreparation/202106_DESY/scripts/PhysicsEvent.h" ClassImp(EventOut) #define DATADIR "/eos/user/i/ideadr/TB2021_Desy/recoNtuple/" #define OUTDIR "/eos/user/i/ideadr/TB2021_Desy/PMT_calibration/" void CheckCalib(int myconf){ // myconf flag allows to switch among the three configuration with which DESY data has been taken // select variables as function of the calib std:vector<int> runs; switch(myconf){ case 0 : // yellow filter runs={73,79,80,81,82,83,84,85,86}; break; case 1 : // no yellow filter runs={180,182,183,185,190,186,189,188,187}; break; case 2 : // no yellow filter and PMT_C ampliefied runs={266,274,275,276,273,277,280,279,278}; break; } cout << myconf << " run series starting with " <<runs[0] << endl; TH1F *h[16]; int nbin =150; int xlow = 0; int xhigh =15; // Histograms per Tower for(int n=0;n<8; n++){ stringstream hname; stringstream htitle; hname<<"h_C_"<<n+1; htitle << "Cher_"<<n+1; h[n]=new TH1F(hname.str().c_str(), htitle.str().c_str(), nbin, xlow,xhigh); h[n]->GetXaxis()->SetTitle("ADC counts"); } for(int n=8;n<16; n++){ stringstream hname; stringstream htitle; hname<<"h_S_"<<n-7; htitle << "Scint_"<<n-7; h[n]=new TH1F(hname.str().c_str(), htitle.str().c_str(), nbin, xlow, xhigh); h[n]->GetXaxis()->SetTitle("ADC counts"); } TH1F *h_SumC_SIPM = new TH1F("SumC_SIPM", "SumC_SIPM", nbin,xlow,xhigh); h_SumC_SIPM->GetXaxis()->SetTitle("Energy (GeV)"); TH1F *h_SumS_SIPM = new TH1F("SumS_SIPM", "SumS_SIPM", nbin, xlow, xhigh); h_SumS_SIPM->GetXaxis()->SetTitle("Energy (GeV)"); // using data file with beam steered in the center TFile *f; ostringstream infile; for(int tow=0; tow<9; tow++ ) { cout << "tow " << tow << endl; infile.str(""); infile << DATADIR << "physics_desy2021_run" << std::to_string(runs[tow]) << ".root"; std::cout<<"Using file: "<<infile.str()<<std::endl; f=new TFile(infile.str().c_str()); TTree *t = (TTree*) f->Get("Ftree"); cout << t->GetEntries()<< endl; auto evt = new EventOut(); t->SetBranchAddress("Events",&evt); cout << " looking at tow " << tow << endl; if(tow==0){ for( unsigned int i=0; i<t->GetEntries(); i++){ t->GetEntry(i); h_SumS_SIPM->Fill(evt->totSiPMSene); h_SumC_SIPM->Fill(evt->totSiPMCene); } } else{ for( unsigned int i=0; i<t->GetEntries(); i++){ t->GetEntry(i); switch (tow){ case 1 : h[tow-1]->Fill(evt->CPMT1); h[tow+7]->Fill(evt->SPMT1); break; case 2 : h[tow-1]->Fill(evt->CPMT2); h[tow+7]->Fill(evt->SPMT2); break; case 3 : h[tow-1]->Fill(evt->CPMT3); h[tow+7]->Fill(evt->SPMT3); break; case 4 : h[tow-1]->Fill(evt->CPMT4); h[tow+7]->Fill(evt->SPMT4); break; case 5 : h[tow-1]->Fill(evt->CPMT5); h[tow+7]->Fill(evt->SPMT5); break; case 6 : h[tow-1]->Fill(evt->CPMT6); h[tow+7]->Fill(evt->SPMT6); break; case 7 : h[tow-1]->Fill(evt->CPMT7); h[tow+7]->Fill(evt->SPMT7); break; case 8 : h[tow-1]->Fill(evt->CPMT8); h[tow+7]->Fill(evt->SPMT8); break; default: cout<< "error"<< endl; } // end switch } // end for on events } // end else } // end loop on tow TCanvas *c_all = new TCanvas("c_distrib", "c_distrib", 1000, 700); c_all->Divide(3,3); c_all->cd(1); gPad->SetLogy(); h[7]->Draw(); c_all->cd(2); gPad->SetLogy(); h[6]->Draw(); c_all->cd(3); gPad->SetLogy(); h[5]->Draw(); c_all->cd(4); gPad->SetLogy(); h[4]->Draw(); c_all->cd(5); gPad->SetLogy(); h_SumC_SIPM->Draw(); c_all->cd(6); gPad->SetLogy(); h[3]->Draw(); c_all->cd(7); gPad->SetLogy(); h[2]->Draw(); c_all->cd(8); gPad->SetLogy(); h[1]->Draw(); c_all->cd(9); gPad->SetLogy(); h[0]->Draw(); TCanvas *s_all = new TCanvas("s_distrib", "s_distrib", 1000, 700); s_all->Divide(3,3); s_all->cd(1); gPad->SetLogy(); h[15]->Draw(); s_all->cd(2); gPad->SetLogy(); h[14]->Draw(); s_all->cd(3); gPad->SetLogy(); h[13]->Draw(); s_all->cd(4); gPad->SetLogy(); h[12]->Draw(); s_all->cd(5); gPad->SetLogy(); h_SumS_SIPM->Draw(); s_all->cd(6); gPad->SetLogy(); h[11]->Draw(); s_all->cd(7); gPad->SetLogy(); h[10]->Draw(); s_all->cd(8); gPad->SetLogy(); h[9]->Draw(); s_all->cd(9); gPad->SetLogy(); h[8]->Draw(); return; }
24.877273
98
0.490407
[ "vector" ]
5cd4ed1ab942d1034e247cd84a3305f0e7157368
18,168
cpp
C++
my_md_source/my_metadata_client_lua_functs.cpp
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
5
2018-11-28T19:38:23.000Z
2021-03-15T20:44:07.000Z
my_md_source/my_metadata_client_lua_functs.cpp
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
null
null
null
my_md_source/my_metadata_client_lua_functs.cpp
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
1
2018-07-18T15:22:36.000Z
2018-07-18T15:22:36.000Z
/* * Copyright 2018 National Technology & Engineering Solutions of * Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, * the U.S. Government retains certain rights in this software. * * The MIT License (MIT) * * Copyright (c) 2018 Sandia Corporation * * 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 <string> #include <my_metadata_client.h> //note: this is just for the logging functions #include <my_metadata_client_lua_functs.h> extern lua_State *L; using namespace std; static bool debug_logging = false; static bool testing_logging = false; static bool extreme_debug_logging = false; static bool zero_rank_logging = false; static bool error_logging = true; static debugLog testing_log = debugLog(testing_logging, zero_rank_logging); static debugLog debug_log = debugLog(debug_logging, false); static debugLog error_log = debugLog(error_logging, zero_rank_logging); static debugLog extreme_debug_log = debugLog(extreme_debug_logging, false); int stringify_function(const std::string &path_to_function, const std::string &funct_name, string &code_string) { //stringify the function // extreme_debug_log << "path to funct: " << path_to_function.c_str() << endl; if (luaL_loadfile(L, path_to_function.c_str()) || lua_pcall(L, 0, 0, 0)) { error_log << "cannot load the given lua function path: " << lua_tostring(L, -1) << "\n"; return RC_ERR; } luaL_loadstring(L, "return string.dump(...)"); lua_getglobal(L, funct_name.c_str()); if (!lua_isfunction(L, -1)) { error_log << "couldn't load " << funct_name << " function in stringify" << endl; return RC_ERR; } if(lua_pcall(L, 1, 1, 0)) { string errmsg = lua_tostring(L, -1); error_log << "errmsg: " << errmsg << endl; } size_t length = lua_strlen(L, -1); code_string.assign(lua_tostring(L, -1), length); lua_pop(L, 1); //pop the code string off the stack // testing_log << "at the end of stringify_function, the lua stack size is: " << lua_gettop(L) << endl; return RC_OK; } int register_objector_funct_write (const std::string &funct_name, const std::string &path_to_function, uint64_t job_id) { // testing_log << "at the start of register_objector_funct_write, the lua stack size is: " << lua_gettop(L) << endl; string registry_name = to_string(job_id) + "o"; //todo - do I really need to check this if I make sure to only register once? lua_getglobal(L, registry_name.c_str()); if (!lua_isfunction(L, -1)) { extreme_debug_log << registry_name << " not found in registry for write" << endl; if (luaL_loadfile(L, path_to_function.c_str()) || lua_pcall(L, 0, 0, 0)) { error_log << "cannot load the given lua function path: " << lua_tostring(L, -1) << "\n"; return RC_ERR; } lua_getglobal(L, funct_name.c_str()); if (!lua_isfunction(L, -1)) { error_log << "error. couldn't load " << funct_name << " function in write" << endl; return RC_ERR; } lua_setglobal(L, registry_name.c_str()); extreme_debug_log << "just registered in write " << registry_name << endl; } else { extreme_debug_log << "already registered in write " << registry_name << endl; } lua_pop(L, 1); //pop the return (function or nil) from getglobal off the stack // testing_log << "at the end of register_objector_funct_write, the lua stack size is: " << lua_gettop(L) << endl; return RC_OK; } static int register_and_load_objector_funct_read (const std::string &objector_funct, uint64_t job_id) { // testing_log << "at the start of register_and_load_objector_funct_read, the lua stack size is: " << lua_gettop(L) << endl; string registry_name = to_string(job_id) + "o"; //todo - do I really need to check this if I make sure to only register once? lua_getglobal(L, registry_name.c_str()); if (!lua_isfunction(L, -1)) { lua_pop(L, 1); //pop the returned nil off the stack if(objector_funct.size() == 0) { error_log << "register_and_load_objector_funct_read called before objector_funct has been assigned" << endl; return RC_ERR; } // testing_log << "before loading buffer in register_and_load_objector_funct_read, the lua stack size is: " << lua_gettop(L) << endl; if(luaL_loadbuffer(L, objector_funct.c_str(), objector_funct.size(), "funct")) { error_log << "errmsg: " << lua_tostring(L, -1) << endl; return RC_ERR; } // testing_log << "after loading buffer in register_and_load_objector_funct_read, the lua stack size is: " << lua_gettop(L) << endl; lua_setglobal(L, registry_name.c_str()); // testing_log << "after set global in register_and_load_objector_funct_read, the lua stack size is: " << lua_gettop(L) << endl; lua_getglobal(L, registry_name.c_str()); extreme_debug_log << "just registered in read " << registry_name << endl; } else { extreme_debug_log << "already registered in read " << registry_name << endl; } // testing_log << "at the end of register_and_load_objector_funct_read, the lua stack size is: " << lua_gettop(L) << endl; return RC_OK; } static int register_and_load_rank_to_bounding_box_funct (const md_catalog_run_entry &run) { string registry_name = to_string(run.job_id); //todo - do I really need to check this if I make sure to only register once? lua_getglobal(L, registry_name.c_str()); if (!lua_isfunction(L, -1)) { lua_pop(L, 1); //pop the returned nil off the stack if(run.rank_to_dims_funct.size() == 0) { error_log << "register_and_load_rank_to_bounding_box_funct called before rank_to_dims_funct has been assigned" << endl; return RC_ERR; } if(luaL_loadbuffer(L, run.rank_to_dims_funct.c_str(), run.rank_to_dims_funct.size(), "funct")) { error_log << "errmsg: " << lua_tostring(L, -1) << endl; return RC_ERR; } lua_setglobal(L, registry_name.c_str()); lua_getglobal(L, registry_name.c_str()); extreme_debug_log << "just registered in read " << registry_name << endl; // lua_getglobal(L, registry_name.c_str()); } else { extreme_debug_log << "already registered in read " << registry_name << endl; } return RC_OK; } int rankToBoundingBox(const md_catalog_run_entry &run, const md_catalog_var_entry &var, int rank, vector<md_dim_bounds> &bounding_box) { string errmsg; int rc; uint64_t ndx = (var.dims[0].max - var.dims[0].min + 1) / run.npx; //ndx = nx / npx uint64_t ndy = 0; uint64_t ndz = 0; if (2 <= var.num_dims) { ndy = (var.dims[1].max - var.dims[1].min + 1) / run.npy; //ndy = ny / npy } if (3 <= var.num_dims) { ndz = (var.dims[2].max - var.dims[2].min + 1) / run.npz; //ndz = nz / npz } rc = register_and_load_rank_to_bounding_box_funct(run); if (rc != RC_OK) { error_log << "error in register_and_load_rank_to_bounding_box_funct \n"; } uint64_t npy = 1; uint64_t npz = 1; if (var.num_dims >= 2) { npy = run.npy; // extreme_debug_log << "nx: " << var.dims[0].max - var.dims[0].min + 1 << " ny: " << var.dims[1].max - var.dims[1].min + 1 << endl; } if (var.num_dims == 3) { npz = run.npz; // extreme_debug_log << "nx: " << var.dims[0].max - var.dims[0].min + 1 << " ny: " << var.dims[1].max - var.dims[1].min + 1 << " nz: " << var.dims[2].max - var.dims[2].min + 1 << endl; } lua_pushinteger(L, run.npx); lua_pushinteger(L, npy); lua_pushinteger(L, npz); lua_pushinteger(L, ndx); lua_pushinteger(L, ndy); lua_pushinteger(L, ndz); lua_pushinteger(L, rank); extreme_debug_log << "rank: " << rank << " npx: " << run.npx << " npy: " << npy << " npz: " << npz << endl; extreme_debug_log << "ndx: " << ndx << " ndy: " << ndy << " ndz: " << ndz << endl; if(lua_pcall(L, 7, 6, 0)) { errmsg = lua_tostring(L, -1); error_log << "errmsg: " << errmsg << endl; return RC_ERR; } else { // bounding_box.reserve(var.num_dims); // bounding_box.reserve(3); for(int i = 0; i < 3; i++) { // for(int i = 0; i < var.num_dims; i++) { bounding_box[i].min = lua_tonumber(L, -1); //should return 0s for any dimension not used lua_pop(L, 1); bounding_box[i].max = lua_tonumber(L, -1); lua_pop(L, 1); // md_dim_bounds dims; // dims.min = lua_tonumber(L, -1);//should return 0s for any dimension not used // lua_pop(L, 1); // dims.max = lua_tonumber(L, -1); // lua_pop(L, 1); // bounding_box.push_back(dims); } // for(int j = var.num_dims; j < 3; j++) { //pop off the 0s for any dimension we don't need // lua_pop(L, 1); // lua_pop(L, 1); // bounding_box[j].min = 0; //should return 0s for any dimension not used // bounding_box[j].max = 0; //should return 0s for any dimension not used // } if(extreme_debug_logging) { printf("Rank: %d, Bounding box: (%d, %d, %d),(%d, %d, %d)\n",rank,bounding_box[0].min,bounding_box[1].min,bounding_box[2].min, bounding_box[0].max,bounding_box[1].max,bounding_box[2].max); } } // testing_log << "at the end of rankToBoundingBox, the lua stack size is: " << lua_gettop(L) << endl; return RC_OK; } static int callBoundingBoxToObjNamesAndCounts(const md_catalog_run_entry &run, const md_catalog_var_entry &var, const vector<md_dim_bounds> &bounding_box, bool get_counts) { string errmsg; int rc; uint64_t ndx = (var.dims[0].max - var.dims[0].min + 1) / run.npx; //ndx = nx / npx uint64_t ndy = 0; uint64_t ndz = 0; // extreme_debug_log << "ndx: " << ndx << endl; // extreme_debug_log << "var.num_dims: " << var.num_dims << " var.dims.size(): " << var.dims.size() << endl; if (2 <= var.num_dims) { ndy = (var.dims[1].max - var.dims[1].min + 1) / run.npy; //ndy = ny / npy // extreme_debug_log << "ndy: " << ndy << endl; } if (3 <= var.num_dims) { ndz = (var.dims[2].max - var.dims[2].min + 1) / run.npz; //ndz = nz / npz // extreme_debug_log << "ndz: " << ndz << endl; } uint64_t ceph_obj_size = 8000000; //todo string registry_name = to_string(run.job_id) + "o"; extreme_debug_log << "in callBoundingBoxToObjNamesAndCounts registry name: " << registry_name << endl; if (get_counts) { rc = register_and_load_objector_funct_read (run.objector_funct, run.job_id); if (rc != RC_OK) { error_log << "error with register_and_load_objector_funct_read \n"; return rc; } } else { lua_getglobal(L, registry_name.c_str()); if (!lua_isfunction(L, -1)) { error_log << "error couldn't load objector function for " << registry_name << " by callBoundingBoxToObjNamesAndCounts in write \n"; return RC_ERR; } } extreme_debug_log << "get_counts: " << get_counts << " job_id: " << run.job_id << " run name: " << run.name << " timestep_id: " << var.timestep_id << endl; extreme_debug_log << "ndx: " << ndx << " ndy: " << ndy << " ndz: " << ndz << endl; extreme_debug_log << "ceph_obj_size: " << ceph_obj_size << " var name: " << var.name << " var version: " << var.version << " var.data_size: " << var.data_size << endl; extreme_debug_log << "bounding_box.size(): " << bounding_box.size() << endl; if(extreme_debug_logging) { printf("Bounding box: (%d, %d, %d),(%d, %d, %d)\n",bounding_box[0].min,bounding_box[1].min,bounding_box[2].min,bounding_box[0].max,bounding_box[1].max,bounding_box[2].max); } lua_pushboolean(L, get_counts); lua_pushinteger(L, run.job_id); lua_pushstring(L, run.name.c_str()); lua_pushinteger(L, var.timestep_id); lua_pushinteger(L, ndx); lua_pushinteger(L, ndy); lua_pushinteger(L, ndz); lua_pushinteger(L, ceph_obj_size); lua_pushstring(L, var.name.c_str()); lua_pushinteger(L, var.version); lua_pushinteger(L, var.data_size); lua_pushinteger(L, bounding_box[0].min); lua_pushinteger(L, bounding_box[1].min); lua_pushinteger(L, bounding_box[2].min); lua_pushinteger(L, bounding_box[0].max); lua_pushinteger(L, bounding_box[1].max); lua_pushinteger(L, bounding_box[2].max); // for(int i =0; i<var.num_dims; i++) { // lua_pushinteger(L, var.dims[i].min); // lua_pushinteger(L, var.dims[i].max); // } // if(lua_pcall(L, 15 + 2*var.num_dims, 1, 0)) { // error_log << "errmsg: " << errmsg << endl; // return RC_ERR; // } for(int i =0; i<var.num_dims; i++) { lua_pushinteger(L, var.dims[i].min); lua_pushinteger(L, var.dims[i].max); } for(int i = var.num_dims; i<3; i++) { lua_pushinteger(L, 0); lua_pushinteger(L, 0); } // if(lua_pcall(L, 15 + 2*var.num_dims, 1, 0)) { // error_log << "errmsg: " << errmsg << endl; // return RC_ERR; // } if(lua_pcall(L, 23, 1, 0)) { errmsg = lua_tostring(L, -1); error_log << "errmsg: " << errmsg << endl; return RC_ERR; } // testing_log << "at the end of callBoundingBoxToObjNamesAndCounts, the lua stack size is: " << lua_gettop(L) << endl; return RC_OK; } // int boundingBoxToObjNames(const md_catalog_run_entry &run, const string &objector_funct_name, const md_catalog_var_entry &var, const vector<md_dim_bounds> &bounding_box, // vector<string> &obj_names) { int boundingBoxToObjNames(const md_catalog_run_entry &run, const md_catalog_var_entry &var, const vector<md_dim_bounds> &bounding_box, vector<string> &obj_names) { int rc; // note - if you stop registering functs right after creating them, you will need to add this back in // rc = register_objector_funct_write (objector_funct_name, run.job_id); // if (rc != RC_OK) { // error_log << "error with register_objector_funct_write \n"; // return rc; // } bool get_counts = false; rc = callBoundingBoxToObjNamesAndCounts(run, var, bounding_box, get_counts); if (rc != RC_OK) { error_log << "error with callBoundingBoxToObjNames \n"; return rc; } if (lua_istable(L, -1)) { lua_pushnil(L); // first key debug_log << "Matching object names: \n"; while (lua_next(L, -2) != 0) { string obj_name = (string)lua_tostring(L, -1); debug_log << obj_name << endl; obj_names.push_back(obj_name); lua_pop(L, 1); } lua_pop(L, 1); //pop the nil back off the stack debug_log << "End of matching object names \n"; } // testing_log << "at the end of boundingBoxToObjNames, the lua stack size is: " << lua_gettop(L) << endl; return RC_OK; } int boundingBoxToObjNamesAndCounts(const md_catalog_run_entry &run, const md_catalog_var_entry &var, const vector<md_dim_bounds> &bounding_box, vector<string> &obj_names, vector<uint64_t> &offsets_and_counts) { int rc; bool get_counts = true; rc = callBoundingBoxToObjNamesAndCounts(run, var, bounding_box, get_counts); if (rc != RC_OK) { error_log << "error with callBoundingBoxToObjNamesAndCounts \n"; return rc; } extreme_debug_log << "var.num_dims: " << var.num_dims << endl; if (lua_istable(L, -1)) { lua_pushnil(L); // first key testing_log << "Matching object names: \n"; while (lua_next(L, -2) != 0) { for(int i=0; i< (2*var.num_dims); i++) { uint32_t temp = lua_tonumber(L, -1); extreme_debug_log << "temp_new: " << temp << endl; offsets_and_counts.push_back(temp); lua_pop(L, 1); lua_next(L, -2); } string obj_name = (string)lua_tostring(L, -1); obj_names.push_back(obj_name); lua_pop(L, 1); testing_log << "obj_name: " << obj_name << endl; // extreme_debug_log << "obj name: " << obj_name << " and we want to start at (" << x_start_indx << "," << y_start_indx << "," << z_start_indx << ") and to retrieve "; // extreme_debug_log << "counts: (" << x_count << "," << y_count << "," << z_count << ")" << endl; } lua_pop(L, 1); //pop the nil back off the stack testing_log << "End of matching object names \n"; } // testing_log << "at the end of boundingBoxToObjNamesAndCounts, the lua stack size is: " << lua_gettop(L) << endl; return RC_OK; }
40.553571
195
0.612891
[ "object", "vector" ]
5cd7f801567f4750918d628e5f923ae88dbeca17
2,215
hpp
C++
include/codegen/include/System/Runtime/Serialization/ObjectHolderList.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Runtime/Serialization/ObjectHolderList.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Runtime/Serialization/ObjectHolderList.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Runtime::Serialization namespace System::Runtime::Serialization { // Forward declaring type: ObjectHolder class ObjectHolder; // Forward declaring type: ObjectHolderListEnumerator class ObjectHolderListEnumerator; } // Completed forward declares // Type namespace: System.Runtime.Serialization namespace System::Runtime::Serialization { // Autogenerated type: System.Runtime.Serialization.ObjectHolderList class ObjectHolderList : public ::Il2CppObject { public: // System.Runtime.Serialization.ObjectHolder[] m_values // Offset: 0x10 ::Array<System::Runtime::Serialization::ObjectHolder*>* m_values; // System.Int32 m_count // Offset: 0x18 int m_count; // System.Void .ctor(System.Int32 startingSize) // Offset: 0xFFBC7C static ObjectHolderList* New_ctor(int startingSize); // System.Void Add(System.Runtime.Serialization.ObjectHolder value) // Offset: 0xFFBCF8 void Add(System::Runtime::Serialization::ObjectHolder* value); // System.Runtime.Serialization.ObjectHolderListEnumerator GetFixupEnumerator() // Offset: 0xFFBE54 System::Runtime::Serialization::ObjectHolderListEnumerator* GetFixupEnumerator(); // private System.Void EnlargeArray() // Offset: 0xFFBDB0 void EnlargeArray(); // System.Int32 get_Version() // Offset: 0xFFBF20 int get_Version(); // System.Int32 get_Count() // Offset: 0xFFBF28 int get_Count(); // System.Void .ctor() // Offset: 0xFFBC74 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static ObjectHolderList* New_ctor(); }; // System.Runtime.Serialization.ObjectHolderList } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::Runtime::Serialization::ObjectHolderList*, "System.Runtime.Serialization", "ObjectHolderList"); #pragma pack(pop)
38.859649
126
0.714673
[ "object" ]
5cdf858348d6010939ca9bcea50af5d715ca9d1e
8,085
cc
C++
headless/lib/browser/headless_printing_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
headless/lib/browser/headless_printing_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
headless/lib/browser/headless_printing_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 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 "base/memory/ptr_util.h" #include "base/values.h" #include "headless/lib/browser/headless_devtools_manager_delegate.h" #include "headless/lib/browser/headless_print_manager.h" #include "printing/features/features.h" #include "printing/units.h" #include "testing/gtest/include/gtest/gtest.h" namespace headless { TEST(ParsePrintSettingsTest, Landscape) { HeadlessPrintSettings settings; EXPECT_FALSE(settings.landscape); auto params = base::MakeUnique<base::DictionaryValue>(); params->SetBoolean("landscape", true); std::unique_ptr<base::DictionaryValue> response = ParsePrintSettings(0, params.get(), &settings); EXPECT_TRUE(settings.landscape); EXPECT_EQ(nullptr, response); } TEST(ParsePrintSettingsTest, HeaderFooter) { HeadlessPrintSettings settings; EXPECT_FALSE(settings.display_header_footer); auto params = base::MakeUnique<base::DictionaryValue>(); params->SetBoolean("displayHeaderFooter", true); std::unique_ptr<base::DictionaryValue> response = ParsePrintSettings(0, params.get(), &settings); EXPECT_TRUE(settings.display_header_footer); EXPECT_EQ(nullptr, response); } TEST(ParsePrintSettingsTest, PrintBackground) { HeadlessPrintSettings settings; EXPECT_FALSE(settings.should_print_backgrounds); auto params = base::MakeUnique<base::DictionaryValue>(); params->SetBoolean("printBackground", true); std::unique_ptr<base::DictionaryValue> response = ParsePrintSettings(0, params.get(), &settings); EXPECT_TRUE(settings.should_print_backgrounds); EXPECT_EQ(nullptr, response); } TEST(ParsePrintSettingsTest, Scale) { HeadlessPrintSettings settings; EXPECT_DOUBLE_EQ(1, settings.scale); auto params = base::MakeUnique<base::DictionaryValue>(); params->SetDouble("scale", 0.5); std::unique_ptr<base::DictionaryValue> response = ParsePrintSettings(0, params.get(), &settings); EXPECT_DOUBLE_EQ(0.5, settings.scale); EXPECT_EQ(nullptr, response); params->SetDouble("scale", -1); response = ParsePrintSettings(0, params.get(), &settings); EXPECT_NE(nullptr, response); params->SetDouble("scale", 10); response = ParsePrintSettings(0, params.get(), &settings); EXPECT_NE(nullptr, response); } TEST(ParsePrintSettingsTest, PageRanges) { HeadlessPrintSettings settings; EXPECT_EQ("", settings.page_ranges); auto params = base::MakeUnique<base::DictionaryValue>(); params->SetString("pageRanges", "abcd"); params->SetBoolean("ignoreInvalidPageRanges", true); std::unique_ptr<base::DictionaryValue> response = ParsePrintSettings(0, params.get(), &settings); // Pass pageRanges text to settings directly and return no error, even if // it is invalid. The validation is deferred to HeadlessPrintMangager once the // total page count is available. See the PageRangeTextToPagesTest. EXPECT_EQ("abcd", settings.page_ranges); EXPECT_TRUE(settings.ignore_invalid_page_ranges); EXPECT_EQ(nullptr, response); } TEST(ParsePrintSettingsTest, Paper) { HeadlessPrintSettings settings; auto params = base::MakeUnique<base::DictionaryValue>(); std::unique_ptr<base::DictionaryValue> response = ParsePrintSettings(0, params.get(), &settings); EXPECT_EQ(printing::kLetterWidthInch * printing::kPointsPerInch, settings.paper_size_in_points.width()); EXPECT_EQ(printing::kLetterHeightInch * printing::kPointsPerInch, settings.paper_size_in_points.height()); EXPECT_EQ(nullptr, response); params->SetDouble("paperWidth", 1); params->SetDouble("paperHeight", 2); response = ParsePrintSettings(0, params.get(), &settings); EXPECT_EQ(1 * printing::kPointsPerInch, settings.paper_size_in_points.width()); EXPECT_EQ(2 * printing::kPointsPerInch, settings.paper_size_in_points.height()); EXPECT_EQ(nullptr, response); params->SetDouble("paperWidth", -1); params->SetDouble("paperHeight", 2); response = ParsePrintSettings(0, params.get(), &settings); EXPECT_NE(nullptr, response); params->SetDouble("paperWidth", 1); params->SetDouble("paperHeight", -2); response = ParsePrintSettings(0, params.get(), &settings); EXPECT_NE(nullptr, response); } TEST(ParsePrintSettingsTest, Margin) { HeadlessPrintSettings settings; auto params = base::MakeUnique<base::DictionaryValue>(); std::unique_ptr<base::DictionaryValue> response = ParsePrintSettings(0, params.get(), &settings); int default_margin = 1000 * printing::kPointsPerInch / printing::kHundrethsMMPerInch; EXPECT_DOUBLE_EQ(default_margin, settings.margins_in_points.top); EXPECT_DOUBLE_EQ(default_margin, settings.margins_in_points.bottom); EXPECT_DOUBLE_EQ(default_margin, settings.margins_in_points.left); EXPECT_DOUBLE_EQ(default_margin, settings.margins_in_points.right); EXPECT_EQ(nullptr, response); params->SetDouble("marginTop", 1); params->SetDouble("marginBottom", 2); params->SetDouble("marginLeft", 3); params->SetDouble("marginRight", 4); response = ParsePrintSettings(0, params.get(), &settings); EXPECT_DOUBLE_EQ(1 * printing::kPointsPerInch, settings.margins_in_points.top); EXPECT_DOUBLE_EQ(2 * printing::kPointsPerInch, settings.margins_in_points.bottom); EXPECT_DOUBLE_EQ(3 * printing::kPointsPerInch, settings.margins_in_points.left); EXPECT_DOUBLE_EQ(4 * printing::kPointsPerInch, settings.margins_in_points.right); EXPECT_EQ(nullptr, response); params->SetDouble("marginTop", -1); response = ParsePrintSettings(0, params.get(), &settings); EXPECT_NE(nullptr, response); } TEST(PageRangeTextToPagesTest, General) { using PM = HeadlessPrintManager; std::vector<int> pages; std::vector<int> expected_pages; // "-" is full range of pages. PM::PageRangeStatus status = PM::PageRangeTextToPages("-", false, 10, &pages); expected_pages = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; EXPECT_EQ(expected_pages, pages); EXPECT_EQ(PM::PRINT_NO_ERROR, status); // If no start page is specified, we start at first page. status = PM::PageRangeTextToPages("-5", false, 10, &pages); expected_pages = {0, 1, 2, 3, 4}; EXPECT_EQ(expected_pages, pages); EXPECT_EQ(PM::PRINT_NO_ERROR, status); // If no end page is specified, we end at last page. status = PM::PageRangeTextToPages("5-", false, 10, &pages); expected_pages = {4, 5, 6, 7, 8, 9}; EXPECT_EQ(expected_pages, pages); EXPECT_EQ(PM::PRINT_NO_ERROR, status); // Multiple ranges are separated by commas. status = PM::PageRangeTextToPages("1-3,9-10,4-6", false, 10, &pages); expected_pages = {0, 1, 2, 3, 4, 5, 8, 9}; EXPECT_EQ(expected_pages, pages); EXPECT_EQ(PM::PRINT_NO_ERROR, status); // White space is ignored. status = PM::PageRangeTextToPages("1- 3, 9-10,4 -6", false, 10, &pages); expected_pages = {0, 1, 2, 3, 4, 5, 8, 9}; EXPECT_EQ(expected_pages, pages); EXPECT_EQ(PM::PRINT_NO_ERROR, status); // End page beyond number of pages is supported and capped to number of pages. status = PM::PageRangeTextToPages("1-10", false, 5, &pages); expected_pages = {0, 1, 2, 3, 4}; EXPECT_EQ(expected_pages, pages); EXPECT_EQ(PM::PRINT_NO_ERROR, status); // Start page beyond number of pages results in error. status = PM::PageRangeTextToPages("1-3,9-10,4-6", false, 5, &pages); EXPECT_EQ(PM::LIMIT_ERROR, status); // Invalid page ranges are ignored if |ignore_invalid_page_ranges| is true. status = PM::PageRangeTextToPages("9-10,4-6,3-1", true, 5, &pages); expected_pages = {3, 4}; EXPECT_EQ(expected_pages, pages); EXPECT_EQ(PM::PRINT_NO_ERROR, status); // Invalid input results in error. status = PM::PageRangeTextToPages("abcd", false, 10, &pages); EXPECT_EQ(PM::SYNTAX_ERROR, status); // Invalid input results in error. status = PM::PageRangeTextToPages("1-3,9-a10,4-6", false, 10, &pages); EXPECT_EQ(PM::SYNTAX_ERROR, status); } } // namespace headless
37.604651
80
0.727767
[ "vector" ]
5ce72b08792e007a34c896b82f27d9753c747563
15,968
cpp
C++
src/frameworks/native/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 The Android Open Source Project * * 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 <android-base/stringprintf.h> #include <compositionengine/CompositionEngine.h> #include <compositionengine/Layer.h> #include <compositionengine/LayerFE.h> #include <compositionengine/Output.h> #include <compositionengine/impl/LayerCompositionState.h> #include <compositionengine/impl/OutputCompositionState.h> #include <compositionengine/impl/OutputLayer.h> #include <compositionengine/impl/OutputLayerCompositionState.h> #include "DisplayHardware/HWComposer.h" namespace android::compositionengine { OutputLayer::~OutputLayer() = default; namespace impl { namespace { FloatRect reduce(const FloatRect& win, const Region& exclude) { if (CC_LIKELY(exclude.isEmpty())) { return win; } // Convert through Rect (by rounding) for lack of FloatRegion return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect(); } } // namespace std::unique_ptr<compositionengine::OutputLayer> createOutputLayer( const CompositionEngine& compositionEngine, std::optional<DisplayId> displayId, const compositionengine::Output& output, std::shared_ptr<compositionengine::Layer> layer, sp<compositionengine::LayerFE> layerFE) { auto result = std::make_unique<OutputLayer>(output, layer, layerFE); result->initialize(compositionEngine, displayId); return result; } OutputLayer::OutputLayer(const Output& output, std::shared_ptr<Layer> layer, sp<LayerFE> layerFE) : mOutput(output), mLayer(layer), mLayerFE(layerFE) {} OutputLayer::~OutputLayer() = default; void OutputLayer::initialize(const CompositionEngine& compositionEngine, std::optional<DisplayId> displayId) { if (!displayId) { return; } auto& hwc = compositionEngine.getHwComposer(); mState.hwc.emplace(std::shared_ptr<HWC2::Layer>(hwc.createLayer(*displayId), [&hwc, displayId](HWC2::Layer* layer) { hwc.destroyLayer(*displayId, layer); })); } const compositionengine::Output& OutputLayer::getOutput() const { return mOutput; } compositionengine::Layer& OutputLayer::getLayer() const { return *mLayer; } compositionengine::LayerFE& OutputLayer::getLayerFE() const { return *mLayerFE; } const OutputLayerCompositionState& OutputLayer::getState() const { return mState; } OutputLayerCompositionState& OutputLayer::editState() { return mState; } Rect OutputLayer::calculateInitialCrop() const { const auto& layerState = mLayer->getState().frontEnd; // apply the projection's clipping to the window crop in // layerstack space, and convert-back to layer space. // if there are no window scaling involved, this operation will map to full // pixels in the buffer. FloatRect activeCropFloat = reduce(layerState.geomLayerBounds, layerState.geomActiveTransparentRegion); const Rect& viewport = mOutput.getState().viewport; const ui::Transform& layerTransform = layerState.geomLayerTransform; const ui::Transform& inverseLayerTransform = layerState.geomInverseLayerTransform; // Transform to screen space. activeCropFloat = layerTransform.transform(activeCropFloat); activeCropFloat = activeCropFloat.intersect(viewport.toFloatRect()); // Back to layer space to work with the content crop. activeCropFloat = inverseLayerTransform.transform(activeCropFloat); // This needs to be here as transform.transform(Rect) computes the // transformed rect and then takes the bounding box of the result before // returning. This means // transform.inverse().transform(transform.transform(Rect)) != Rect // in which case we need to make sure the final rect is clipped to the // display bounds. Rect activeCrop{activeCropFloat}; if (!activeCrop.intersect(layerState.geomBufferSize, &activeCrop)) { activeCrop.clear(); } return activeCrop; } FloatRect OutputLayer::calculateOutputSourceCrop() const { const auto& layerState = mLayer->getState().frontEnd; const auto& outputState = mOutput.getState(); if (!layerState.geomUsesSourceCrop) { return {}; } // the content crop is the area of the content that gets scaled to the // layer's size. This is in buffer space. FloatRect crop = layerState.geomContentCrop.toFloatRect(); // In addition there is a WM-specified crop we pull from our drawing state. Rect activeCrop = calculateInitialCrop(); const Rect& bufferSize = layerState.geomBufferSize; int winWidth = bufferSize.getWidth(); int winHeight = bufferSize.getHeight(); // The bufferSize for buffer state layers can be unbounded ([0, 0, -1, -1]) // if display frame hasn't been set and the parent is an unbounded layer. if (winWidth < 0 && winHeight < 0) { return crop; } // Transform the window crop to match the buffer coordinate system, // which means using the inverse of the current transform set on the // SurfaceFlingerConsumer. uint32_t invTransform = layerState.geomBufferTransform; if (layerState.geomBufferUsesDisplayInverseTransform) { /* * the code below applies the primary display's inverse transform to the * buffer */ uint32_t invTransformOrient = outputState.orientation; // calculate the inverse transform if (invTransformOrient & HAL_TRANSFORM_ROT_90) { invTransformOrient ^= HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_FLIP_H; } // and apply to the current transform invTransform = (ui::Transform(invTransformOrient) * ui::Transform(invTransform)).getOrientation(); } if (invTransform & HAL_TRANSFORM_ROT_90) { // If the activeCrop has been rotate the ends are rotated but not // the space itself so when transforming ends back we can't rely on // a modification of the axes of rotation. To account for this we // need to reorient the inverse rotation in terms of the current // axes of rotation. bool is_h_flipped = (invTransform & HAL_TRANSFORM_FLIP_H) != 0; bool is_v_flipped = (invTransform & HAL_TRANSFORM_FLIP_V) != 0; if (is_h_flipped == is_v_flipped) { invTransform ^= HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_FLIP_H; } std::swap(winWidth, winHeight); } const Rect winCrop = activeCrop.transform(invTransform, bufferSize.getWidth(), bufferSize.getHeight()); // below, crop is intersected with winCrop expressed in crop's coordinate space float xScale = crop.getWidth() / float(winWidth); float yScale = crop.getHeight() / float(winHeight); float insetL = winCrop.left * xScale; float insetT = winCrop.top * yScale; float insetR = (winWidth - winCrop.right) * xScale; float insetB = (winHeight - winCrop.bottom) * yScale; crop.left += insetL; crop.top += insetT; crop.right -= insetR; crop.bottom -= insetB; return crop; } Rect OutputLayer::calculateOutputDisplayFrame() const { const auto& layerState = mLayer->getState().frontEnd; const auto& outputState = mOutput.getState(); // apply the layer's transform, followed by the display's global transform // here we're guaranteed that the layer's transform preserves rects Region activeTransparentRegion = layerState.geomActiveTransparentRegion; const ui::Transform& layerTransform = layerState.geomLayerTransform; const ui::Transform& inverseLayerTransform = layerState.geomInverseLayerTransform; const Rect& bufferSize = layerState.geomBufferSize; Rect activeCrop = layerState.geomCrop; if (!activeCrop.isEmpty() && bufferSize.isValid()) { activeCrop = layerTransform.transform(activeCrop); if (!activeCrop.intersect(outputState.viewport, &activeCrop)) { activeCrop.clear(); } activeCrop = inverseLayerTransform.transform(activeCrop, true); // This needs to be here as transform.transform(Rect) computes the // transformed rect and then takes the bounding box of the result before // returning. This means // transform.inverse().transform(transform.transform(Rect)) != Rect // in which case we need to make sure the final rect is clipped to the // display bounds. if (!activeCrop.intersect(bufferSize, &activeCrop)) { activeCrop.clear(); } // mark regions outside the crop as transparent activeTransparentRegion.orSelf(Rect(0, 0, bufferSize.getWidth(), activeCrop.top)); activeTransparentRegion.orSelf( Rect(0, activeCrop.bottom, bufferSize.getWidth(), bufferSize.getHeight())); activeTransparentRegion.orSelf(Rect(0, activeCrop.top, activeCrop.left, activeCrop.bottom)); activeTransparentRegion.orSelf( Rect(activeCrop.right, activeCrop.top, bufferSize.getWidth(), activeCrop.bottom)); } // reduce uses a FloatRect to provide more accuracy during the // transformation. We then round upon constructing 'frame'. Rect frame{ layerTransform.transform(reduce(layerState.geomLayerBounds, activeTransparentRegion))}; if (!frame.intersect(outputState.viewport, &frame)) { frame.clear(); } const ui::Transform displayTransform{outputState.transform}; return displayTransform.transform(frame); } uint32_t OutputLayer::calculateOutputRelativeBufferTransform() const { const auto& layerState = mLayer->getState().frontEnd; const auto& outputState = mOutput.getState(); /* * Transformations are applied in this order: * 1) buffer orientation/flip/mirror * 2) state transformation (window manager) * 3) layer orientation (screen orientation) * (NOTE: the matrices are multiplied in reverse order) */ const ui::Transform& layerTransform = layerState.geomLayerTransform; const ui::Transform displayTransform{outputState.orientation}; const ui::Transform bufferTransform{layerState.geomBufferTransform}; ui::Transform transform(displayTransform * layerTransform * bufferTransform); if (layerState.geomBufferUsesDisplayInverseTransform) { /* * the code below applies the primary display's inverse transform to the * buffer */ uint32_t invTransform = outputState.orientation; // calculate the inverse transform if (invTransform & HAL_TRANSFORM_ROT_90) { invTransform ^= HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_FLIP_H; } /* * Here we cancel out the orientation component of the WM transform. * The scaling and translate components are already included in our bounds * computation so it's enough to just omit it in the composition. * See comment in BufferLayer::prepareClientLayer with ref to b/36727915 for why. */ transform = ui::Transform(invTransform) * displayTransform * bufferTransform; } // this gives us only the "orientation" component of the transform return transform.getOrientation(); } // namespace impl void OutputLayer::updateCompositionState(bool includeGeometry) { if (includeGeometry) { mState.displayFrame = calculateOutputDisplayFrame(); mState.sourceCrop = calculateOutputSourceCrop(); mState.bufferTransform = static_cast<Hwc2::Transform>(calculateOutputRelativeBufferTransform()); if ((mLayer->getState().frontEnd.isSecure && !mOutput.getState().isSecure) || (mState.bufferTransform & ui::Transform::ROT_INVALID)) { mState.forceClientComposition = true; } } } void OutputLayer::writeStateToHWC(bool includeGeometry) const { // Skip doing this if there is no HWC interface if (!mState.hwc) { return; } auto& hwcLayer = (*mState.hwc).hwcLayer; if (!hwcLayer) { ALOGE("[%s] failed to write composition state to HWC -- no hwcLayer for output %s", mLayerFE->getDebugName(), mOutput.getName().c_str()); return; } if (includeGeometry) { // Output dependent state if (auto error = hwcLayer->setDisplayFrame(mState.displayFrame); error != HWC2::Error::None) { ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)", mLayerFE->getDebugName(), mState.displayFrame.left, mState.displayFrame.top, mState.displayFrame.right, mState.displayFrame.bottom, to_string(error).c_str(), static_cast<int32_t>(error)); } if (auto error = hwcLayer->setSourceCrop(mState.sourceCrop); error != HWC2::Error::None) { ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: " "%s (%d)", mLayerFE->getDebugName(), mState.sourceCrop.left, mState.sourceCrop.top, mState.sourceCrop.right, mState.sourceCrop.bottom, to_string(error).c_str(), static_cast<int32_t>(error)); } if (auto error = hwcLayer->setZOrder(mState.z); error != HWC2::Error::None) { ALOGE("[%s] Failed to set Z %u: %s (%d)", mLayerFE->getDebugName(), mState.z, to_string(error).c_str(), static_cast<int32_t>(error)); } if (auto error = hwcLayer->setTransform(static_cast<HWC2::Transform>(mState.bufferTransform)); error != HWC2::Error::None) { ALOGE("[%s] Failed to set transform %s: %s (%d)", mLayerFE->getDebugName(), toString(mState.bufferTransform).c_str(), to_string(error).c_str(), static_cast<int32_t>(error)); } // Output independent state const auto& outputIndependentState = mLayer->getState().frontEnd; if (auto error = hwcLayer->setBlendMode( static_cast<HWC2::BlendMode>(outputIndependentState.blendMode)); error != HWC2::Error::None) { ALOGE("[%s] Failed to set blend mode %s: %s (%d)", mLayerFE->getDebugName(), toString(outputIndependentState.blendMode).c_str(), to_string(error).c_str(), static_cast<int32_t>(error)); } if (auto error = hwcLayer->setPlaneAlpha(outputIndependentState.alpha); error != HWC2::Error::None) { ALOGE("[%s] Failed to set plane alpha %.3f: %s (%d)", mLayerFE->getDebugName(), outputIndependentState.alpha, to_string(error).c_str(), static_cast<int32_t>(error)); } if (auto error = hwcLayer->setInfo(outputIndependentState.type, outputIndependentState.appId); error != HWC2::Error::None) { ALOGE("[%s] Failed to set info %s (%d)", mLayerFE->getDebugName(), to_string(error).c_str(), static_cast<int32_t>(error)); } } } void OutputLayer::dump(std::string& out) const { using android::base::StringAppendF; StringAppendF(&out, " - Output Layer %p (Composition layer %p) (%s)\n", this, mLayer.get(), mLayerFE->getDebugName()); mState.dump(out); } } // namespace impl } // namespace android::compositionengine
41.048843
100
0.6689
[ "transform" ]
5ce944ab547da416ec793ee257cdbaba2e59520a
1,256
cpp
C++
projects/project/src/shader.cpp
TheAlexP/Engine
5a1bed59e4d152c075da00398cdd16fe37b3af1d
[ "MIT" ]
null
null
null
projects/project/src/shader.cpp
TheAlexP/Engine
5a1bed59e4d152c075da00398cdd16fe37b3af1d
[ "MIT" ]
null
null
null
projects/project/src/shader.cpp
TheAlexP/Engine
5a1bed59e4d152c075da00398cdd16fe37b3af1d
[ "MIT" ]
null
null
null
#include "shader.h" shader::shader(char* filename) { std::ifstream fileStream(filename, std::ios::in); if (!fileStream.is_open()) { std::cerr << "Could not read file " << filename << ". File does not exist." << std::endl; } std::string line = ""; while (!fileStream.eof()) { std::getline(fileStream, line); shaderProgram = shaderProgram + line + "\n"; } fileStream.close(); } shader::~shader() { } void shader::setup(GLenum type) { GLint result = GL_FALSE; int logLength; const GLchar* shaderSrc = shaderProgram.c_str(); shaderId = glCreateShader(type); glShaderSource(shaderId, 1, &shaderSrc, 0); glCompileShader(shaderId); glGetShaderiv(shaderId, GL_COMPILE_STATUS, &result); glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logLength); std::vector<GLchar> shaderError((logLength > 1) ? logLength : 1); glGetShaderInfoLog(shaderId, logLength, NULL, &shaderError[0]); std::cout << &shaderError[0] << std::endl; } void shader::attach(GLuint programId) { this->programId = programId; glAttachShader(programId, shaderId); } void shader::bind(GLuint index, const char * name) { glBindAttribLocation(programId, index, name); } void shader::destroy() { glDetachShader(programId, shaderId); glDeleteShader(shaderId); }
19.625
91
0.702229
[ "vector" ]
5cecf3e2d1b6ffe879453a094f10d68c9b836985
11,626
cpp
C++
tools/montecarlo_cpp/Montecarlo.cpp
Ulukele/neuron_poker
9dc5b9bc0095fe3f79501b103517bdcce80139c1
[ "MIT" ]
403
2019-06-28T09:40:19.000Z
2022-03-31T21:18:09.000Z
tools/montecarlo_cpp/Montecarlo.cpp
Ulukele/neuron_poker
9dc5b9bc0095fe3f79501b103517bdcce80139c1
[ "MIT" ]
42
2019-07-01T20:03:51.000Z
2022-02-10T00:16:57.000Z
tools/montecarlo_cpp/Montecarlo.cpp
Ulukele/neuron_poker
9dc5b9bc0095fe3f79501b103517bdcce80139c1
[ "MIT" ]
155
2019-06-30T12:25:47.000Z
2022-03-29T16:21:16.000Z
#include "Montecarlo.h" #include <array> #include <vector> #include <iostream> #include <tuple> #include <algorithm> #include <iostream> #include <algorithm> #include <random> #include <iterator> bool eval_best_hand(const std::vector<CardsWithTableCombined>& all_cards_with_table_combined) // returns true if first player has best hand { std::vector<std::tuple< std::vector<int>, std::vector<int>, std::string>> all_players_score; std::vector<std::tuple< std::vector<int>, std::vector<int>, std::string>> all_players_score_original; bool best_hand; for (const auto& cards_with_table : all_cards_with_table_combined) { auto result = calc_score(cards_with_table); all_players_score.emplace_back(result); } all_players_score_original = all_players_score; std::sort(all_players_score.begin(), all_players_score.end(), std::greater<>()); if (all_players_score[0] == all_players_score_original[0]) best_hand = true; // first player is best hand else best_hand = false; // different player is best hand return best_hand; } Score get_rcounts(const CardsWithTableCombined& all_cards_with_table_combined, std::vector<std::size_t> available_ranks, const std::string original_ranks) { Score rcounts; for (const auto& card : all_cards_with_table_combined) { available_ranks.emplace_back(original_ranks.find(card.substr(0, 1))); } for (int i = 0; i <= 12; i++) { int count = std::count(available_ranks.begin(), available_ranks.end(), i); if (count > 0) { rcounts.emplace_back(std::make_pair(count, i)); } } return rcounts; } std::tuple< std::vector<int>, std::vector<int>, std::string> calc_score(const CardsWithTableCombined& all_cards_with_table_combined) { const std::string original_ranks = "23456789TJQKA"; const std::vector<std::string> original_suits{ "C","D","H","S" }; std::vector<std::size_t> available_ranks; std::vector<std::string> available_suits; std::vector<int> score; std::vector<int> card_ranks; std::vector<int> sorted_card_ranks; std::string hand_type; bool flush = false; bool straight = false; Score rcounts; std::vector<std::tuple<int, std::string>> rsuits; rcounts = get_rcounts(all_cards_with_table_combined, available_ranks, original_ranks); // sort tuple and split into score and card ranks std::sort(rcounts.begin(), rcounts.end(), std::greater<std::tuple<int, int>>()); for (auto it = std::make_move_iterator(rcounts.begin()), end = std::make_move_iterator(rcounts.end()); it != end; ++it) { score.push_back(std::get<0>(*it)); // amount of occurrences card_ranks.push_back(std::get<1>(*it)); // ranks of individual cards } bool potential_threeofakind = score[0] == 3; bool potential_twopair = score == std::vector<int> {2, 2, 1, 1, 1}; bool potential_pair = score == std::vector<int> {2, 1, 1, 1, 1, 1}; auto sub_score2 = slice(score, 0, 2); auto sub_score4 = slice(score, 0, 5); auto sub_score0 = slice(score, 0, 0); // # fullhouse(three of a kind and pair, or two three of a kind) if (sub_score2 == std::vector<int> {3, 2} || sub_score2 == std::vector<int> {3, 3}) { // make adjustment card_ranks = slice(card_ranks, 0, 2); score = { 3,2 }; } // edge case: convert three pair to two pair //const auto x = &score[3]; else if (sub_score4 == std::vector<int>{2, 2, 2, 1}) { score = { 2,2,1 }; int kicker = std::max(card_ranks[2], card_ranks[3]); card_ranks = { card_ranks[0], card_ranks[1], kicker }; } else if (score[0] == 4) { // four of a kind score = { 4, }; // avoid for example 11, 8, 9 sorted_card_ranks = card_ranks; std::sort(sorted_card_ranks.begin(), sorted_card_ranks.end(), std::greater <>()); card_ranks = { sorted_card_ranks[0], sorted_card_ranks[1] }; } else if (score.size() >= 5) { // high card, flush, straight and straight flush // straight // adjust for 5 high straight if (std::find(card_ranks.begin(), card_ranks.end(), 12) != card_ranks.end()) card_ranks.push_back(-1); sorted_card_ranks = card_ranks; std::sort(sorted_card_ranks.begin(), sorted_card_ranks.end(), std::greater <>()); // sort again for (int i = 0; i < sorted_card_ranks.size() - 4; ++i) { straight = sorted_card_ranks[i] - sorted_card_ranks[i + 4] == 4; if (straight == true) { card_ranks = { sorted_card_ranks[i], sorted_card_ranks[i + 1], sorted_card_ranks[i + 2], sorted_card_ranks[i + 3], sorted_card_ranks[i + 4] }; break; } } //flush for (std::string card : all_cards_with_table_combined) { available_suits.emplace_back(card.substr(1, 1)); } std::vector<int> suit_counts; std::vector<std::string> suit_cards; for (const auto& suit : original_suits) { // why can original_suits not be a string and suit a char? int count = std::count(available_suits.begin(), available_suits.end(), suit); if (count > 0) { rsuits.emplace_back(std::make_pair(count, suit)); } } std::sort(rsuits.begin(), rsuits.end(), std::greater<std::tuple<int, std::string>>()); flush = std::get<0>(rsuits[0]) >= 5; // the most occurred suit appear at least 5 times if (flush == true) { auto flush_suit = std::get<1>(rsuits[0]); CardsWithTableCombined flush_hand; for (auto card : all_cards_with_table_combined) { if (card[1] == flush_suit[0]) { flush_hand.insert(card); } } Score rcounts_flush = get_rcounts(flush_hand, available_ranks, original_ranks); // sort tuple and split into score and card ranks std::sort(rcounts_flush.begin(), rcounts_flush.end(), std::greater<std::tuple<int, int>>()); card_ranks.clear(); score.clear(); for (auto it = std::make_move_iterator(rcounts_flush.begin()), end = std::make_move_iterator(rcounts_flush.end()); it != end; ++it) { score.push_back(std::get<0>(*it)); // ranks of individual cards card_ranks.push_back(std::get<1>(*it)); // amount of occurrences } // # check for straight in flush // if 12 in card_ranks and -1 not in card_ranks : # adjust if 5 high straight if (std::find(card_ranks.begin(), card_ranks.end(), 12) != card_ranks.end() && !(std::find(card_ranks.begin(), card_ranks.end(), -1) != card_ranks.end())) { card_ranks.push_back(-1); } for (int i = 0; i < card_ranks.size() - 4; i++) { straight = card_ranks[i] - card_ranks[i + 4] == 4; if (straight == true) { break; } } } // no pair, straight, flush, or straight flush if (flush == false && straight == false) score = { 1 }; else if (flush == false && straight == true) score = { 3, 1, 2 }; else if (flush == true && straight == false) score = { 3, 1, 3 }; else if (flush == true && straight == true) score = { 5 }; } if (score[0] == 1 && potential_threeofakind == true) score = { 3,1 }; else if (score[0] == 1 && potential_twopair == true) score = { 2, 2, 1 }; else if (score[0] == 1 && potential_pair == true) score = { 2, 1, 1 }; if (score[0] == 5) // # crdRanks=crdRanks[:5] # five card rule makes no difference {:5] would be incorrect hand_type = "StraightFlush"; else if (score[0] == 4) hand_type = "FoufOfAKind"; // crdRanks = crdRanks[:2] # already implemented above else if (slice(score, 0, 2) == std::vector<int> {3, 2}) hand_type = "FullHouse"; // # crdRanks = crdRanks[:2] # already implmeneted above else if (slice(score, 0, 3) == std::vector<int> {3, 1, 3}) { hand_type = "Flush"; card_ranks = slice(card_ranks, 0, 5); } else if (slice(score, 0, 3) == std::vector<int> {3, 1, 2}) { hand_type = "Straight"; card_ranks = slice(card_ranks, 0, 5); } else if (slice(score, 0, 2) == std::vector<int> {3, 1}) { hand_type = "ThreeOfAKind"; card_ranks = slice(card_ranks, 0, 3); } else if (slice(score, 0, 2) == std::vector<int> {3, 1}) { hand_type = "ThreeOfAKind"; card_ranks = slice(card_ranks, 0, 3); } else if (slice(score, 0, 2) == std::vector<int> {2, 2}) { hand_type = "TwoPair"; card_ranks = slice(card_ranks, 0, 3); } else if (score[0] == 2) { hand_type = "Pair"; card_ranks = slice(card_ranks, 0, 4); } else if (score[0] == 1) { hand_type = "HighCard"; card_ranks = slice(card_ranks, 0, 5); } else throw std::runtime_error("Card Type error!"); auto res = std::make_tuple(score, card_ranks, hand_type); return res; } double montecarlo(const std::set<std::string>& my_cards, std::set<std::string> cards_on_table, const int number_of_players, const int iterations) { if (cards_on_table.size() < 3) cards_on_table.clear(); int wins = 0; for (int i = 0; i < iterations; i++) { Deck deck; deck.remove_visible_cards(my_cards, cards_on_table); deck.distribute_cards(number_of_players); std::vector<CardsWithTableCombined> cards_with_table_combined = deck.get_cards_combined(); bool first_player_has_best_hand = eval_best_hand(cards_with_table_combined); if (first_player_has_best_hand == true) wins += 1; } double equity = (wins / (double)iterations); // std::cout << "Equity: " << equity << std::endl; return equity; } Deck::Deck() { std::string combined; //std::cout << "Constructing deck..." << std::endl; for (char& r : ranks) { for (char& s : suits) { combined = std::string() + r + s; full_deck.insert(combined); }; }; //std::cout << "Cards in deck: " << full_deck.size() << std::endl; } void Deck::remove_visible_cards(const Hand& my_cards_, const std::set<std::string>& cards_on_table_) { // remove my_cards and cards_on_table from full_deck set_difference(full_deck.begin(), full_deck.end(), my_cards_.begin(), my_cards_.end(), std::inserter(remaining_cards_tmp, remaining_cards_tmp.end())); // remove visible table cards from deck set_difference(remaining_cards_tmp.begin(), remaining_cards_tmp.end(), cards_on_table_.begin(), cards_on_table_.end(), std::inserter(remaining_cards, remaining_cards.end())); //std::cout << "Remaining cards: " << remaining_cards.size() << std::endl; this->my_cards = my_cards_.cards; this->cards_on_table = cards_on_table_; //std::cout << "Removed my cards from deck...\n"; } void Deck::distribute_cards(int number_players) { constexpr size_t cards_in_hand = 2; std::vector<std::string> shuffled_deck(remaining_cards.begin(), remaining_cards.end()); std::shuffle(shuffled_deck.begin(), shuffled_deck.end(), std::mt19937_64(std::random_device()())); std::vector<Hand> player_hands(number_players); // empty container auto hand_it = player_hands.begin(); *hand_it = Hand(my_cards); // set my own cards hand_it++; auto card_it = shuffled_deck.begin(); while (hand_it != player_hands.end()) { *hand_it = Hand(std::set<std::string>{*++card_it, * ++card_it}); ++hand_it; } while (cards_on_table.size() < 5) { cards_on_table.emplace(*++card_it); } // print out the hands //for (auto const& player_hand : player_hands) { // std::cout << "Cards: "; // for (const auto& card : player_hand.cards) // std::cout << card << " "; // std::cout << std::endl; //} this->player_hands = player_hands; //std::cout << "Cards on table: "; //print_set(cards_on_table); } std::vector<CardsWithTableCombined> Deck::get_cards_combined() { CardsWithTableCombined cards_with_table_combined; std::vector<CardsWithTableCombined> all_cards_with_table_combined; for (const auto& player_hand : player_hands) { cards_with_table_combined = player_hand.cards; cards_with_table_combined.insert(cards_on_table.begin(), cards_on_table.end()); all_cards_with_table_combined.push_back(cards_with_table_combined); } return all_cards_with_table_combined; } void Deck::print_set(const std::set<std::string>& set) { for (const auto& card : set) std::cout << card << " "; std::cout << std::endl; }
33.796512
147
0.674179
[ "vector" ]
5cf4bf0ed6f651880f0cbc03f81ea8f8375a3947
550
cpp
C++
codes/moderncpp/functors/functors01/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
3
2022-01-25T07:33:43.000Z
2022-03-30T10:25:09.000Z
codes/moderncpp/functors/functors01/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
null
null
null
codes/moderncpp/functors/functors01/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
2
2022-01-17T13:39:12.000Z
2022-03-30T10:25:12.000Z
#include <iostream> #include <algorithm> int increment(int x) { return ( x + 1 ); } int main( int argc, char **argv ) { { int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof( arr ) / sizeof( arr[ 0 ] ); // Apply increment to all elements of // arr[] and store the modified elements // back in arr[] std::transform( arr, arr+n, arr, increment ); for ( int i = 0; i < n; ++ i ) { std::cout << arr[i] << " "; } std::cout << std::endl; } return 0; }
21.153846
53
0.46
[ "transform" ]
9dd86e584ae1d7fafc508600437be25ce49a4444
5,090
cpp
C++
Source/Config.cpp
Xanfre/dmm
d56ee25bf28bba596310c36963892550eaf878b3
[ "MIT" ]
5
2020-11-29T16:36:48.000Z
2021-12-20T20:25:14.000Z
Source/Config.cpp
pshjt/ss2bmm
c8434a630f9a3b8e06e000af35e9a7ff132bd881
[ "MIT" ]
null
null
null
Source/Config.cpp
pshjt/ss2bmm
c8434a630f9a3b8e06e000af35e9a7ff132bd881
[ "MIT" ]
3
2021-03-28T23:13:25.000Z
2022-01-24T07:11:08.000Z
#include <Precompiled.hpp> #include "Message.hpp" #include "Config.hpp" Config::Config() { initialize(); } Config::Config(const std::string& fileName) { initialize(); assignFile(fileName); } Config::~Config() { } void Config::assignFile(const std::string& fileName) { fileName_ = fileName; } bool Config::load() { if (!wxFileExists(fileName_)) return true; std::ifstream file(fileName_); if (file.fail()) { errorMessage_ = makeErrorMessage(Message::ErrorMessageType::ERROR_ACCESS_FILE, fileName_); return false; } std::vector<std::string> fileLines; std::string line; while (std::getline(file, line)) fileLines.push_back(line); for (const auto& currentLine : fileLines) { std::string name, value; bool isKey = tokenize(name, value, currentLine); if (isKey) { auto it = findKey(name); if (it != keys_.end()) it->value = value; } } setVariables(); return true; } bool Config::saveOverwriting(const std::string& frontComment) { std::ofstream file(fileName_); if (file.fail()) { errorMessage_ = makeErrorMessage(Message::ErrorMessageType::ERROR_WRITE_FILE, fileName_); return false; } if (!frontComment.empty()) file << frontComment << std::endl; getVariables(); for (const auto& i : keys_) { if (i.isReadOnly) continue; std::string line; computeKeyLine(i, line); file << line << std::endl; } if (file.fail()) { errorMessage_ = makeErrorMessage(Message::ErrorMessageType::ERROR_WRITE_FILE, fileName_); return false; } return true; } bool Config::saveUpdating() { std::vector<std::string> fileLines; if (wxFileExists(fileName_)) { std::ifstream file(fileName_); if (file.fail()) { errorMessage_ = makeErrorMessage(Message::ErrorMessageType::ERROR_ACCESS_FILE, fileName_); return false; } std::string line; while (std::getline(file, line)) fileLines.push_back(line); Utils::trimTrailingNewLines(fileLines); } getVariables(); bool isFileChanged = false; for (const auto& key : keys_) { if (key.isReadOnly) continue; bool isKeyLineFound = false; auto it = fileLines.rbegin(); while (!isKeyLineFound && it != fileLines.rend()) { std::string name, value; bool isKey = tokenize(name, value, *it); if (isKey) if (Utils::stringIsEqualNoCase(key.name, name)) { isKeyLineFound = true; bool isNameTheSame = key.name.compare(name) == 0; bool isValueTheSame = key.value.compare(value) == 0; if (!isNameTheSame || !isValueTheSame) { computeKeyLine(key, *it); isFileChanged = true; } } ++it; } if (!isKeyLineFound) { std::string line; computeKeyLine(key, line); fileLines.push_back(line); isFileChanged = true; } } if (isFileChanged) { std::ofstream file(fileName_); if (file.fail()) { errorMessage_ = makeErrorMessage(Message::ErrorMessageType::ERROR_WRITE_FILE, fileName_); return false; } for (const auto& line : fileLines) file << line << std::endl; if (file.fail()) { errorMessage_ = makeErrorMessage(Message::ErrorMessageType::ERROR_WRITE_FILE, fileName_); return false; } } return true; } std::string Config::getErrorMessage() const { return errorMessage_; } void Config::configVariable(std::string& variable, const std::string& name, const char* defaultValue, bool isReadOnly /*= false*/) { configVariable(variable, name, std::string(defaultValue), isReadOnly); } void Config::initialize() { operationType_ = OperationType::ADD; } void Config::getVariables() { operationType_ = OperationType::GET; keysIterator_ = keys_.begin(); configVariables(); operationType_ = OperationType::NONE; } void Config::setVariables() { operationType_ = OperationType::SET; keysIterator_ = keys_.begin(); configVariables(); operationType_ = OperationType::NONE; } template <> void Config::addVariable(std::string& variable, const std::string& name, const std::string& defaultValue, bool isReadOnly) { variable = defaultValue; addKey(name, defaultValue, isReadOnly); } template <> void Config::setVariable(std::string& variable) { variable = keysIterator_++->value; } template <> void Config::getVariable(const std::string& variable) { keysIterator_++->value = variable; } void Config::addKey(const std::string& name, const std::string& defaultValue, bool isReadOnly) { assert(findKey(name) == keys_.end()); Key key; key.name = name; key.defaultValue = defaultValue; key.value = key.defaultValue; key.isReadOnly = isReadOnly; keys_.push_back(key); } std::vector<Config::Key>::iterator Config::findKey(const std::string& name) { return std::find_if(keys_.begin(), keys_.end(), PredicateIsKeyNameEqualNoCase(name)); } void Config::computeKeyLine(const Key& key, std::string& line) { line = key.name; if (!key.value.empty()) { line += " "; line += key.value; } } bool Config::tokenize(std::string& token, std::string& remainder, const std::string& sequence) { if (!Utils::tokenize(token, remainder, sequence)) return false; if (token[0] == ';') return false; return true; }
17.985866
105
0.684479
[ "vector" ]
9de04963cac58170dc3dc73eb3141b62db41f40c
903
hpp
C++
NINJA/BinaryHeap.hpp
TravisWheelerLab/NINJA
4523a0eb073a68ffd00dcf537a9466a164c3a156
[ "MIT" ]
3
2019-12-07T11:46:41.000Z
2022-01-26T01:18:03.000Z
NINJA/BinaryHeap.hpp
TravisWheelerLab/NINJA
4523a0eb073a68ffd00dcf537a9466a164c3a156
[ "MIT" ]
36
2016-05-22T18:17:30.000Z
2022-01-26T01:01:07.000Z
NINJA/BinaryHeap.hpp
TravisWheelerLab/NINJA
4523a0eb073a68ffd00dcf537a9466a164c3a156
[ "MIT" ]
4
2019-08-07T17:10:52.000Z
2020-09-27T03:08:55.000Z
#ifndef BINARYHEAP_HPP #define BINARYHEAP_HPP #include "ExceptionHandler.hpp" #include <cassert> #include <climits> #include <cstdio> struct Int { int *pointer; int length; }; struct Float { float *pointer; int length; }; class BinaryHeap { public: //constructors BinaryHeap(); BinaryHeap(int maxCapacity); BinaryHeap(const int *val1s, Int keys); BinaryHeap(const int *val1s, Int keys, int maxCapacity); ~BinaryHeap(); int size() const; //return BinaryHeap size //functions int insert(int val1, int key) const; //insert element void deleteMin() const; //Remove the smallest item from the priority queue bool isEmpty() const; //check if empty void makeEmpty() const; //empty heap static bool binHeapTest(bool verbose); std::vector<std::pair<int, int> > *heap; static const int DEFAULT_CAPACITY = 1000; }; #endif
18.06
78
0.675526
[ "vector" ]
9de4675e510e864b4fb52fefbae6de2d4f2a8333
1,309
hpp
C++
TabGraph/include/Driver/OpenGL/Renderer/Light/PointLightRenderer.hpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-08-28T09:35:18.000Z
2020-08-28T09:35:18.000Z
TabGraph/include/Driver/OpenGL/Renderer/Light/PointLightRenderer.hpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
null
null
null
TabGraph/include/Driver/OpenGL/Renderer/Light/PointLightRenderer.hpp
Gpinchon/TabGraph
29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb
[ "Apache-2.0" ]
1
2020-10-08T11:21:13.000Z
2020-10-08T11:21:13.000Z
/* * @Author: gpinchon * @Date: 2021-04-11 20:51:53 * @Last Modified by: gpinchon * @Last Modified time: 2021-04-11 20:52:16 */ #pragma once #include "Renderer/Light/LightRenderer.hpp" #include <glm/glm.hpp> class Geometry; class Framebuffer; class PointLight; namespace Shader { class Program; }; namespace Renderer { class PointLightRenderer : public LightRenderer { public: PointLightRenderer(PointLight &); virtual void Render(const Renderer::Options&) override; virtual void UpdateLightProbe(const Renderer::Options&, LightProbe&) override; protected: void _RenderDeferredLighting(PointLight&, const Renderer::Options&); void _RenderShadow(PointLight&, const Renderer::Options&); void _RenderShadowInfinite(PointLight&, const Renderer::Options&); void _RenderShadowFinite(PointLight&, const Renderer::Options&); std::shared_ptr<Shader::Program> _deferredShader; std::shared_ptr<Shader::Program> _probeShader; std::shared_ptr<Framebuffer> _shadowBuffer; std::shared_ptr<Geometry> _deferredGeometry; }; }; glm::mat4 PointLightShadowViewMatrix(PointLight&); glm::mat4 PointLightShadowProjectionMatrixInfinite(PointLight&, const Renderer::Options&); glm::mat4 PointLightShadowProjectionMatrixFinite(PointLight&);
31.166667
91
0.741024
[ "geometry", "render" ]
9df593038f1e3c3018f436990fb57948f4b49e1b
1,131
cpp
C++
atcoder/arc/125/b.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
2
2021-06-09T12:27:07.000Z
2021-06-11T12:02:03.000Z
atcoder/arc/125/b.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
1
2021-09-08T12:00:05.000Z
2021-09-08T14:52:30.000Z
atcoder/arc/125/b.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
null
null
null
/* * @Description: * @Version: 2.0 * @Autor: tusikalanse * @Date: 2021-08-22 19:50:49 * @LastEditors: tusikalanse * @LastEditTime: 2021-08-22 20:30:40 */ #include <bits/stdc++.h> using namespace std; using LL = long long; LL gcd(LL a, LL b) { return b == 0 ? a : gcd(b, a % b); } const int INF = 0x3f3f3f3f; const LL INFL = 0x3f3f3f3f3f3f3f3f; const int mod = 998244353; //-------------------end head-------------- LL n; LL ans; vector<LL> square; LL getans(LL x) { LL l = 1, r = x, now = 0; while (l <= r) { LL mid = l + r >> 1; if (mid * (2 * x - mid) <= n) { now = mid; l = mid + 1; } else { r = mid - 1; } } return now; } int main() { cin >> n; LL x; for (x = 1; x * x <= n; ++x) { ans += x; ans %= mod; } for (LL now = getans(x), R; x <= n && now != 0; x = R + 1, now--) { R = (n + now * now) / (2 * now); //cout << now << " " << x << " " << R << endl; ans += (R - x + 1) % mod * now % mod; ans %= mod; } cout << ans << endl; return 0; }
20.196429
71
0.420866
[ "vector" ]
9df786e6288d5cbf557f49a353ba1753a2589843
8,255
hpp
C++
external/mapnik/include/mapnik/vertex_cache.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/vertex_cache.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/vertex_cache.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_VERTEX_CACHE_HPP #define MAPNIK_VERTEX_CACHE_HPP // mapnik #include <mapnik/pixel_position.hpp> #include <mapnik/debug.hpp> #include <mapnik/config.hpp> #include <mapnik/util/noncopyable.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore_agg.hpp> #include "agg_basics.h" #pragma GCC diagnostic pop // stl #include <vector> #include <memory> #include <map> namespace mapnik { class vertex_cache; using vertex_cache_ptr = std::unique_ptr<vertex_cache>; // Caches all path points and their lengths. Allows easy moving in both directions. class MAPNIK_DECL vertex_cache : util::noncopyable { struct segment { segment(double x, double y, double _length) : pos(x, y), length(_length) {} pixel_position pos; //Last point of this segment, first point is implicitly defined by the previous segement in this vector double length; }; // The first segment always has the length 0 and just defines the starting point. struct segment_vector { segment_vector() : vector(), length(0.) {} void add_segment(double x, double y, double len) { if (len == 0. && !vector.empty()) return; //Don't add zero length segments vector.emplace_back(x, y, len); length += len; } using iterator = std::vector<segment>::iterator; std::vector<segment> vector; double length; }; public: // This class has no public members to avoid acciedential modification. // It should only be used with save_state/restore_state. class state { segment_vector::iterator current_segment; double position_in_segment; pixel_position current_position; pixel_position segment_starting_point; double position_; friend class vertex_cache; public: pixel_position const& position() const { return current_position; } }; class scoped_state : util::noncopyable { public: scoped_state(vertex_cache &pp) : pp_(pp), state_(pp.save_state()), restored_(false) {} void restore() { pp_.restore_state(state_); restored_ = true; } ~scoped_state() { if (!restored_) pp_.restore_state(state_); } state const& get_state() const { return state_; } private: vertex_cache &pp_; state state_; bool restored_; }; /////////////////////////////////////////////////////////////////////// template <typename T> vertex_cache(T &path); vertex_cache(vertex_cache && rhs); double length() const { return current_subpath_->length; } pixel_position const& current_position() const { return current_position_; } double angle(double width=0.); double current_segment_angle(); double linear_position() const { return position_; } // Returns a parallel line in the specified distance. vertex_cache & get_offseted(double offset, double region_width); // Skip a certain amount of space. // This functions automatically calculate new points if the position is not exactly // on a point on the path. bool forward(double length); // Go backwards. bool backward(double length); // Move in any direction (based on sign of length). Returns false if it reaches either end of the path. bool move(double length); // Move to given distance. bool move_to_distance(double distance); // Work on next subpath. Returns false if the is no next subpath. bool next_subpath(); // Compatibility with standard path interface void rewind(unsigned); unsigned vertex(double *x, double *y); // State state save_state() const; void restore_state(state const& s); // Go back to initial state. void reset(); // position on this line closest to the target position double position_closest_to(pixel_position const &target_pos); private: void rewind_subpath(); bool next_segment(); bool previous_segment(); void find_line_circle_intersection( double cx, double cy, double radius, double x1, double y1, double x2, double y2, double & ix, double & iy) const; // Position as calculated by last move/forward/next call. pixel_position current_position_; // First pixel of current segment. pixel_position segment_starting_point_; // List of all subpaths. std::vector<segment_vector> subpaths_; // Currently active subpath. std::vector<segment_vector>::iterator current_subpath_; // Current segment for normal operation (move()). segment_vector::iterator current_segment_; // Current segment in compatibility mode (vertex(), rewind()). segment_vector::iterator vertex_segment_; // Currently active subpath in compatibility mode. std::vector<segment_vector>::iterator vertex_subpath_; // State is initialized (after first call to next_subpath()). bool initialized_; // Position from start of segment. double position_in_segment_; // Angle for current segment. mutable double angle_; // Is the value in angle_ valid? // Used to avoid unnecessary calculations. mutable bool angle_valid_; using offseted_lines_map = std::map<double, vertex_cache_ptr>; // Cache of all offseted lines already computed. offseted_lines_map offseted_lines_; // Linear position, i.e distance from start of line. double position_; }; template <typename T> vertex_cache::vertex_cache(T & path) : current_position_(), segment_starting_point_(), subpaths_(), current_subpath_(), current_segment_(), vertex_segment_(), vertex_subpath_(), initialized_(false), position_in_segment_(0.), angle_(0.), angle_valid_(false), offseted_lines_(), position_(0.) { path.rewind(0); unsigned cmd; double new_x = 0., new_y = 0., old_x = 0., old_y = 0.; bool first = true; //current_subpath_ uninitalized while (!agg::is_stop(cmd = path.vertex(&new_x, &new_y))) { if (agg::is_move_to(cmd)) { //Create new sub path subpaths_.emplace_back(); current_subpath_ = subpaths_.end()-1; current_subpath_->add_segment(new_x, new_y, 0); first = false; } else if (agg::is_line_to(cmd)) { if (first) { MAPNIK_LOG_ERROR(vertex_cache) << "No starting point in path!\n"; continue; } double dx = old_x - new_x; double dy = old_y - new_y; double segment_length = std::sqrt(dx*dx + dy*dy); current_subpath_->add_segment(new_x, new_y, segment_length); } else if (agg::is_closed(cmd) && !current_subpath_->vector.empty()) { segment const & first_segment = current_subpath_->vector[0]; double dx = old_x - first_segment.pos.x; double dy = old_y - first_segment.pos.y; double segment_length = std::sqrt(dx*dx + dy*dy); current_subpath_->add_segment(first_segment.pos.x, first_segment.pos.y, segment_length); } old_x = new_x; old_y = new_y; } } } #endif
34.395833
131
0.643004
[ "vector" ]
9dffe8f2e0774c4db51ae4884b4348780df20604
11,686
cpp
C++
realsense/rs-align.cpp
IamWangYunKai/BallDetection
71671f40d451eae174efad944fb324b1cd9ec89e
[ "MIT" ]
null
null
null
realsense/rs-align.cpp
IamWangYunKai/BallDetection
71671f40d451eae174efad944fb324b1cd9ec89e
[ "MIT" ]
null
null
null
realsense/rs-align.cpp
IamWangYunKai/BallDetection
71671f40d451eae174efad944fb324b1cd9ec89e
[ "MIT" ]
null
null
null
#include <librealsense2/rs.hpp> #include <librealsense2/rs_advanced_mode.hpp> #include "example.hpp" #include <imgui.h> #include "imgui_impl_glfw.h" #include <sstream> #include <iostream> #include <fstream> #include <algorithm> #include <cstring> #include <ctime> #include <thread> #include <chrono> #include <mutex> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "cv-helpers.hpp" #include "opencv2/dnn/dnn.hpp" #include "actionmodule.h" using namespace rs400; using namespace rs2; using namespace std; using namespace cv; const size_t inWidth = 600; const size_t inHeight = 900; const float WHRatio = inWidth / (float)inHeight; int mat_columns; int mat_rows; int length_to_mid; int pixal_to_bottom; int pixal_to_left; double alpha = 0; double last_x_meter = 0; double this_x_meter = 0; double last_y_meter = 0; double this_y_meter = 0; double y_vel = 0; double x_vel = 0; double velocity; double alphaset[5] = { 0 }; double alpha_mean = 0; double move_distance = 0; double first_magic_distance = 5; int count = 0; int magic_distance_flag = 1; string move_direction; int last_frame_length = 50; int last_frame_pixal = 480; rs2_stream find_stream_to_align(const std::vector<rs2::stream_profile>& streams); double depth_length_coefficient(double depth) { double length; length = 48.033*depth + 5.4556; return length; } //mutex mtx; template <typename T> void change(T *p, T *q) { T tmp; tmp = *p; *p = *q; *q = tmp; } void get_video(rs2::pipeline &pipe, rs2::frameset *latest_frameset, rs2::frameset *new_frameset) { while (true) { *new_frameset = pipe.wait_for_frames(); change(latest_frameset, new_frameset); } } void frame_transfer(rs2::align &align, rs2::pipeline &pipe, rs2::frameset *latest_frameset, Mat *pt_color_mat, Mat *pt_new_color_mat, Mat *pt_depth_mat, Mat *pt_new_depth_mat) { while (true) { auto processed = align.process(*latest_frameset); rs2::video_frame color_frame = processed.get_color_frame(); rs2::depth_frame depth_frame = processed.get_depth_frame(); *pt_new_color_mat = frame_to_mat(color_frame); *pt_new_depth_mat = depth_frame_to_meters(pipe, depth_frame); change(pt_color_mat, pt_new_color_mat); change(pt_depth_mat, pt_new_depth_mat); } } int main(int argc, char * argv[]) try{ context ctx; auto devices = ctx.query_devices(); size_t device_count = devices.size(); if (!device_count){ cout << "No device detected. Is it plugged in?\n"; return EXIT_SUCCESS; } auto dev = devices[0]; if (dev.is<rs400::advanced_mode>()){ auto advanced_mode_dev = dev.as<rs400::advanced_mode>(); // Check if advanced-mode is enabled if (!advanced_mode_dev.is_enabled()){ // Enable advanced-mode advanced_mode_dev.toggle_advanced_mode(true); } } else{ cout << "Current device doesn't support advanced-mode!\n"; return EXIT_FAILURE; } clock_t time, time2, time3; // Create a pipeline to easily configure and start the camera rs2::pipeline pipe; //Calling pipeline's start() without any additional parameters will start the first device // with its default streams. //The start function returns the pipeline profile which the pipeline used to start the device rs2::pipeline_profile profile = pipe.start(); //////////////////////// auto config_profile = profile.get_stream(RS2_STREAM_COLOR).as<video_stream_profile>(); Size cropSize; if (config_profile.width() / (float)config_profile.height() > WHRatio){ cropSize = Size(static_cast<int>(config_profile.height() * WHRatio), config_profile.height()); } else{ cropSize = Size(config_profile.width(), static_cast<int>(config_profile.width() / WHRatio)); } Rect crop(Point((config_profile.width() - cropSize.width) / 2, (config_profile.height() - cropSize.height) / 2), cropSize); const auto window_name = "Display Image"; namedWindow(window_name, WINDOW_AUTOSIZE); namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control" int iLowH = 0; int iHighH = 38; int iLowS = 71; int iHighS = 255; int iLowV = 203; int iHighV = 255; //Create trackbars in "Control" window cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179) cvCreateTrackbar("HighH", "Control", &iHighH, 179); cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255) cvCreateTrackbar("HighS", "Control", &iHighS, 255); cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255) cvCreateTrackbar("HighV", "Control", &iHighV, 255); std::ifstream config("F:/config.json"); std::string str((std::istreambuf_iterator<char>(config)), std::istreambuf_iterator<char>()); rs400::advanced_mode dev4json = profile.get_device(); dev4json.load_json(str); ///////////////////// //Pipeline could choose a device that does not have a color stream //If there is no color stream, choose to align depth to another stream rs2_stream align_to = find_stream_to_align(profile.get_streams()); // Create a rs2::align object. // rs2::align allows us to perform alignment of depth frames to others frames //The "align_to" is the stream type to which we plan to align depth frames. rs2::align align(align_to); // Define a variable for controlling the distance to clip float depth_clipping_distance = 1.f; rs2::frameset new_frameset, latest_frameset; new_frameset = latest_frameset = pipe.wait_for_frames(); std::thread t{ get_video, pipe, &latest_frameset, &new_frameset }; t.detach(); std::chrono::milliseconds dura(100); std::this_thread::sleep_for(dura); auto processed = align.process(latest_frameset); rs2::video_frame color_frame = processed.get_color_frame(); rs2::depth_frame depth_frame = processed.get_depth_frame(); Mat latest_color_mat = frame_to_mat(color_frame); Mat latest_depth_mat = depth_frame_to_meters(pipe, depth_frame); Mat new_color_mat = latest_color_mat; Mat new_depth_mat = latest_depth_mat; std::thread t2{ frame_transfer, align, pipe, &latest_frameset, &latest_color_mat,&new_color_mat,&latest_depth_mat,&new_depth_mat }; t2.detach(); std::this_thread::sleep_for(dura); while (cvGetWindowHandle(window_name)){ // Application still alive? time = clock(); Mat Gcolor_mat; GaussianBlur(latest_color_mat, Gcolor_mat, Size(11, 11), 0); //cvtColor(Gcolor_mat, Gcolor_mat, COLOR_BGR2RGB); //imshow(window_name, Gcolor_mat); Gcolor_mat = Gcolor_mat(crop); auto depth_mat2 = latest_depth_mat(crop); Mat imgHSV; vector<Mat> hsvSplit; cvtColor(Gcolor_mat, imgHSV, COLOR_BGR2HSV); split(imgHSV, hsvSplit); equalizeHist(hsvSplit[2], hsvSplit[2]); merge(hsvSplit, imgHSV); Mat imgThresholded; inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); Mat element = getStructuringElement(MORPH_RECT, Size(5, 5)); morphologyEx(imgThresholded, imgThresholded, MORPH_OPEN, element); morphologyEx(imgThresholded, imgThresholded, MORPH_CLOSE, element); vector<vector<cv::Point>> contours; cv::findContours(imgThresholded, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); double maxArea = 0; vector<cv::Point> maxContour; for (size_t i = 0; i < contours.size(); i++){ double area = cv::contourArea(contours[i]); if (area > maxArea){ maxArea = area; maxContour = contours[i]; } } cv::Rect maxRect = cv::boundingRect(maxContour); // auto object = maxRect & Rect (0,0,depth_mat.cols, depth_mat.rows ); auto object = maxRect; auto moment = cv::moments(maxContour, true); Scalar depth_m; if (moment.m00 == 0) { moment.m00 = 1; } Point moment_center(moment.m10 / moment.m00, moment.m01 / moment.m00); depth_m = depth_mat2.at<double>((int)moment.m01 / moment.m00, (int)moment.m10 / moment.m00); double magic_distance = depth_m[0] * 1.062; std::ostringstream ss; ss << " Ball Detected "; ss << std::setprecision(3) << magic_distance << " meters away"; String conf(ss.str()); rectangle(Gcolor_mat, object, Scalar(0, 255, 0)); int baseLine = 0; Size labelSize = getTextSize(ss.str(), FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); auto center = (object.br() + object.tl())*0.5; center.x = center.x - labelSize.width / 2; center.y = center.y + 30; rectangle(Gcolor_mat, Rect(Point(center.x, center.y - labelSize.height), Size(labelSize.width, labelSize.height + baseLine)), Scalar(255, 255, 255), CV_FILLED); putText(Gcolor_mat, ss.str(), center, FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0)); ///////////////////////////////////////////////////////////////// length_to_mid = (moment.m10 / moment.m00 - 200)*depth_length_coefficient(magic_distance) / 320; pixal_to_left = moment.m10 / moment.m00; pixal_to_bottom = (480 - moment.m01 / moment.m00); cout << endl << "length to midline =" << length_to_mid << " "; if (magic_distance_flag == 1 && abs(length_to_mid) == 0) { first_magic_distance = magic_distance; magic_distance_flag = 0; } imshow(window_name, Gcolor_mat); if (waitKey(1) >= 0) break; // imshow("heatmap", depth_mat); this_x_meter = magic_distance; this_y_meter = abs(length_to_mid); if (pixal_to_bottom == 480 && last_frame_pixal<100) { ZActionModule::instance()->sendPacket(2, 10, 0, 0, true); std::this_thread::sleep_for(std::chrono::milliseconds(1)); cout << "0" << endl; } else { if (pixal_to_left == 0 && last_frame_length > 0) { ZActionModule::instance()->sendPacket(2, 0, 0, 30); std::this_thread::sleep_for(std::chrono::milliseconds(1)); cout << "1" << endl; } else if (pixal_to_left == 0 && last_frame_length < 0) { ZActionModule::instance()->sendPacket(2, 0, 0, -30); std::this_thread::sleep_for(std::chrono::milliseconds(1)); cout << "2" << endl; } else { int flag = 1; if (length_to_mid >0) { flag = 1; } else if (length_to_mid < 0) { flag = -1; } else { flag = 0; } ZActionModule::instance()->sendPacket(2, 0, 0, 3.0 * length_to_mid + flag * 5); std::this_thread::sleep_for(std::chrono::milliseconds(1)); last_frame_length = length_to_mid; last_frame_pixal = pixal_to_bottom; } } //waitKey(3); cout << "All " << 1000 * ((double)(clock() - time)) / CLOCKS_PER_SEC << endl; }//end of while return EXIT_SUCCESS; } catch (const rs2::error & e) { std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl; return EXIT_FAILURE; } catch (const std::exception & e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } rs2_stream find_stream_to_align(const std::vector<rs2::stream_profile>& streams) { //Given a vector of streams, we try to find a depth stream and another stream to align depth with. //We prioritize color streams to make the view look better. //If color is not available, we take another stream that (other than depth) rs2_stream align_to = RS2_STREAM_ANY; bool depth_stream_found = false; bool color_stream_found = false; for (rs2::stream_profile sp : streams){ rs2_stream profile_stream = sp.stream_type(); if (profile_stream != RS2_STREAM_DEPTH){ if (!color_stream_found) //Prefer color align_to = profile_stream; if (profile_stream == RS2_STREAM_COLOR){ color_stream_found = true; } } else{ depth_stream_found = true; } } if(!depth_stream_found) throw std::runtime_error("No Depth stream available"); if (align_to == RS2_STREAM_ANY) throw std::runtime_error("No stream found to align with Depth"); return align_to; }
32.104396
177
0.690655
[ "object", "vector" ]
3b098e29b3eb643584d0838fece86b87c301ee2d
18,432
cpp
C++
src/tMSBE-v4.4/classDynamicInterpolation.cpp
sm321430/tMSBE-v4.0
8e4a36bb29379270deda6cc1bef7476d9018d9d1
[ "Unlicense" ]
null
null
null
src/tMSBE-v4.4/classDynamicInterpolation.cpp
sm321430/tMSBE-v4.0
8e4a36bb29379270deda6cc1bef7476d9018d9d1
[ "Unlicense" ]
null
null
null
src/tMSBE-v4.4/classDynamicInterpolation.cpp
sm321430/tMSBE-v4.0
8e4a36bb29379270deda6cc1bef7476d9018d9d1
[ "Unlicense" ]
null
null
null
#ifndef __DYNAMICINTERPOLATION_CPP_INCLUDED__ #define __DYNAMICINTERPOLATION_CPP_INCLUDED__ #include <stdlib.h> #include <iostream> #include <math.h> #include "fileIO.cpp" //#define DYANMIC_INTERPOLATION_DIAGNOSTIC using namespace std; //! Interpolate data using adaptivly updated gridpoints /*! Interpolate a function T = f(x,y,z) where size(T) = Nk\n Uses Trilinear interpolation, and is thus exact for functions of the form: 1+x+y+z+xy+xz+yz+xyz\n When file_save() (or file_load()) is called the program saves (or loads) the current interpolation grid to file (or from file).\n The filename is the variable 'newName' given to the program at init.\n All points are compared up to ERROR_TOL and no duplicates are written to file \n Tip: When increasing the resolution use the same grids as before but with dx/n where n is a whole number, then the old points are loaded from file. \n Warning: \n 1. When evaluating a point that contains the upper domain boundary (x1,y1 or z1) the program crashes This can be fixed with cases, or one keeps away from the boundary.\n 2. The Program crashes if a point outside of the domain is used However, it isnt much of a problem to expand the domain dynamically \n 2018: Added more comments Isak Kilen */ class DynamicInterpolation { public: //! A constructor DynamicInterpolation() { //F = NULL; FXYZ = NULL; fxyz = NULL; x_target_ind = -1; y_target_ind = -1; z_target_ind = -1; x_target = NULL; y_target = NULL; z_target = NULL; } //! A constructor DynamicInterpolation(const std::string & newName, int Nk, double x0, double x1, double dx, double y0, double y1, double dy, double z0, double z1, double dz) { ERROR_TOL = 1.0e-12; if (dx <= 0) { cout << "DynamicInterpolation:: Need dx > 0" << endl; cout << "dx = " << dx << endl; exit(-1); } if (dy <= 0) { cout << "DynamicInterpolation:: Need dy > 0" << endl; cout << "dy = " << dy << endl; exit(-1); } if (dz <= 0) { cout << "DynamicInterpolation:: Need dz > 0" << endl; cout << "dz = " << dz << endl; exit(-1); } if (x0 >= x1) { cout << "DynamicInterpolation:: Need x0 < x1" << endl; cout << "x0 = " << x0 << endl; cout << "x1 = " << x1 << endl; cout << "dx = " << dx << endl; exit(-1); } if (y0 >= y1) { cout << "DynamicInterpolation:: Need y0 < y1" << endl; cout << "y0 = " << y0 << endl; cout << "y1 = " << y1 << endl; cout << "dy = " << dy << endl; exit(-1); } if (z0 >= z1) { cout << "DynamicInterpolation:: Need z0 < z1" << endl; cout << "z0 = " << z0 << endl; cout << "z1 = " << z1 << endl; cout << "dz = " << dz << endl; exit(-1); } file_name = newName; //F = f; X0 = x0; X1 = x1; DX = dx; Y0 = y0; Y1 = y1; DY = dy; Z0 = z0; Z1 = z1; DZ = dz; num_x = floor((X1-X0)/DX)+1; num_y = floor((Y1-Y0)/DY)+1; num_z = floor((Z1-Z0)/DZ)+1; num_output = Nk; FXYZ = new double***[num_x]; for(int i = 0; i < num_x; i++) { FXYZ[i] = new double**[num_y]; for(int j = 0; j < num_y; j++) { FXYZ[i][j] = new double*[num_z]; for(int k = 0; k < num_z; k++) { FXYZ[i][j][k] = NULL; } } } // The edges of the interpolation cube and their index x_target = new double[2]; y_target = new double[2]; z_target = new double[2]; x_target_ind = -1; y_target_ind = -1; z_target_ind = -1; // TMP storage for interpolation fxyz = new double***[2]; for(int i = 0; i < 2; i++) { fxyz[i] = new double**[2]; for(int j = 0; j < 2; j++) { fxyz[i][j] = new double*[2]; for(int k = 0; k < 2; k++) { fxyz[i][j][k] = NULL; } } } // Try to find as many old data points as possible cout << "DynamicInterpolation:: Trying to load as many values as possible from file: " << file_name << endl; int num = file_load(); cout << "DynamicInterpolation:: Found and loaded " << num << " points from file" << endl; } //! A destructor ~DynamicInterpolation() { if (x_target != NULL) { delete [] x_target; delete [] y_target; delete [] z_target; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { delete [] fxyz[i][j]; } delete [] fxyz[i]; } delete [] fxyz; for(int i = 0; i < num_x; i++) { for(int j = 0; j < num_y; j++) { for(int k = 0; k < num_z; k++) { if (FXYZ[i][j][k] != NULL) { delete [] FXYZ[i][j][k]; } } delete [] FXYZ[i][j]; } delete [] FXYZ[i]; } delete [] FXYZ; } } //! A copy-constructor DynamicInterpolation(const DynamicInterpolation &obj) { file_name = obj.file_name; X0 = obj.X0; X1 = obj.X1; DX = obj.DX; num_x = obj.num_x; Y0 = obj.Y0; Y1 = obj.Y1; DY = obj.DY; num_y = obj.num_y; Z0 = obj.Z0; Z1 = obj.Z1; DZ = obj.DZ; num_z = obj.num_z; x_target_ind = obj.x_target_ind; y_target_ind = obj.y_target_ind; z_target_ind = obj.z_target_ind; x_target = NULL; y_target = NULL; z_target = NULL; num_output = obj.num_output; ERROR_TOL = obj.ERROR_TOL; FXYZ = NULL; fxyz = NULL; if (obj.FXYZ != NULL) { FXYZ = new double***[num_x]; for(int i = 0; i < num_x; i++) { FXYZ[i] = new double**[num_y]; for(int j = 0; j < num_y; j++) { FXYZ[i][j] = new double*[num_z]; for(int k = 0; k < num_z; k++) { FXYZ[i][j][k] = NULL; } } } // The edges of the interpolation cube and their index x_target = new double[2]; y_target = new double[2]; z_target = new double[2]; x_target_ind = -1; y_target_ind = -1; z_target_ind = -1; // TMP storage for interpolation fxyz = new double***[2]; for(int i = 0; i < 2; i++) { fxyz[i] = new double**[2]; for(int j = 0; j < 2; j++) { fxyz[i][j] = new double*[2]; for(int k = 0; k < 2; k++) { fxyz[i][j][k] = NULL; } } } } } //! Initialize interpolation function /*! Given that one wants to calculate the point (x,y,z), the interpolation requests that we evaluate the points in newPoints (x,y,z) the point where the interpolation routine should evaluate\n \param new_points -> A 8 X 3 list of new points to evaluate, where only the first 'num_new_points' points are required \param num_new_points -> The number of new points to evaluate */ void prepare_interpolation(double x, double y, double z, double **new_points, int *num_new_points) { if ((x < X0)||(x >= X1)) { cout << "DynamicInterpolation::prepare_interpolation() x is out of bounds, increase domain size" << endl; cout << "x = " << x << endl; cout << "x0 = " << X0 << endl; cout << "x1 = " << X1 << endl; exit(-1); } if ((y < Y0)||(y >= Y1)) { cout << "DynamicInterpolation::prepare_interpolation() y is out of bounds, increase domain size" << endl; cout << "y = " << y << endl; cout << "y0 = " << Y0 << endl; cout << "y1 = " << Y1 << endl; exit(-1); } if ((z < Z0)||(z >= Z1)) { cout << "DynamicInterpolation::prepare_interpolation() z is out of bounds, increase domain size" << endl; cout << "z = " << z << endl; cout << "z0 = " << Z0 << endl; cout << "z1 = " << Z1 << endl; exit(-1); } // Find correct index x_target_ind = floor((x-X0)/DX); x_target[0] = X0 + x_target_ind*DX; x_target[1] = X0 + (x_target_ind+1.0)*DX; y_target_ind = floor((y-Y0)/DY); y_target[0] = Y0 + y_target_ind*DY; y_target[1] = Y0 + (y_target_ind+1.0)*DY; z_target_ind = floor((z-Z0)/DZ); z_target[0] = Z0 + z_target_ind*DZ; z_target[1] = Z0 + (z_target_ind+1.0)*DZ; // 1. Check if x CAN be interpolated from previous data *num_new_points = 0; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { if (FXYZ[x_target_ind+i][y_target_ind+j][z_target_ind+k] == NULL) { #ifdef DYANMIC_INTERPOLATION_DIAGNOSTIC cout << "DynamicInterpolation::prepare_interpolation() Request new point at (x"<< i <<", y"<< j <<", z"<< k <<") = (" << x_target[i] << ", " << y_target[j] << ", " << z_target[k] << ") ... " << endl; #endif // Generate new point new_points[*num_new_points][0] = x_target[i]; new_points[*num_new_points][1] = y_target[j]; new_points[*num_new_points][2] = z_target[k]; new_points[*num_new_points][3] = x_target_ind+i; new_points[*num_new_points][4] = y_target_ind+j; new_points[*num_new_points][5] = z_target_ind+k; *num_new_points += 1; #ifdef DYANMIC_INTERPOLATION_DIAGNOSTIC } else { cout << "DynamicInterpolation::prepare_interpolation() Found old point (x"<< i <<", y"<< j <<", z"<< k <<") = (" << x_target[i] << ", " << y_target[j] << ", " << z_target[k] << ") " << endl; #endif } } } } } //! Update interpolation grid at the given locations /*! Add data to the interpolation grid at x,y,z x,y,z has to be a gridpoint, found from prepare_interpolation() new_data is an array of length num_output */ void update_interpolation_grid(int x_ind, int y_ind, int z_ind, double *new_data) { //int x_ind = floor((x-X0)/DX); //int y_ind = floor((y-Y0)/DY); //int z_ind = floor((z-Z0)/DZ); //cout << "DynamicInterpolation::update_interpolation_grid() index = " << x_ind << ", " << y_ind << ", " << z_ind << endl; if (FXYZ[x_ind][y_ind][z_ind] == NULL) { #ifdef DYANMIC_INTERPOLATION_DIAGNOSTIC cout << "DynamicInterpolation::update_interpolation_grid() Adding new point (" << x << ", " << y << ", " << z << ")" << endl; #endif FXYZ[x_ind][y_ind][z_ind] = new double[num_output]; for(int i = 0; i < num_output; i++) { FXYZ[x_ind][y_ind][z_ind][i] = new_data[i]; } } else { cout << "DynamicInterpolation::update_interpolation_grid() Point already calculated, cannot update" << endl; cout << "x = " << x_ind << endl; cout << "y = " << y_ind << endl; cout << "z = " << z_ind << endl; exit(-1); } } //! Evaluate interpolation at a given location /*! Evaluate the function at the point x,y,z\n Requires that one calls:\n 1. prepare_interpolation(): In order to figure out if new points are needed in the interpolation grid\n 2. User calculates all new points outside of this program\n 3. update_interpolation_grid(): To update the function \n then call this function with \n \param output -> Where the data should be stored \param x,y,z -> The target point */ void evalF(double *output, double x, double y, double z) { // Find correct index x_target_ind = floor((x-X0)/DX); x_target[0] = X0 + x_target_ind*DX; x_target[1] = X0 + (x_target_ind+1.0)*DX; y_target_ind = floor((y-Y0)/DY); y_target[0] = Y0 + y_target_ind*DY; y_target[1] = Y0 + (y_target_ind+1.0)*DY; z_target_ind = floor((z-Z0)/DZ); z_target[0] = Z0 + z_target_ind*DZ; z_target[1] = Z0 + (z_target_ind+1.0)*DZ; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { // Store pointer to target data array fxyz[i][j][k] = FXYZ[x_target_ind+i][y_target_ind+j][z_target_ind+k]; } } } // 3. Interpolate and return // 3D - Trilinear interpolation double dy0 = y - y_target[0]; double dy1 = y_target[1]-y; double dx0 = x - x_target[0]; double dx1 = x_target[1]-x; double DXDY = DX*DY; // For speed double dz_target = (z_target[1]-z_target[0]); // For speed for(int i = 0; i < num_output; i++) { double interp_z0 = dy1*(fxyz[0][0][0][i]*dx1 + fxyz[1][0][0][i]*dx0) + dy0*(fxyz[0][1][0][i]*dx1 + fxyz[1][1][0][i]*dx0); double interp_z1 = dy1*(fxyz[0][0][1][i]*dx1 + fxyz[1][0][1][i]*dx0) + dy0*(fxyz[0][1][1][i]*dx1 + fxyz[1][1][1][i]*dx0); double r1 = (z-z_target[0])/dz_target; double interp = interp_z0 + (interp_z1 - interp_z0)*r1; output[i] = interp/(DXDY); } } //! Load previously saved gridpoints into interpolation grid /*! Load from file, any data points that correspond to the current grid File has data stored as: "x y z data_array" on each line */ int file_load() { int num_points_found = 0; // Test if file exists, otherwise do nothing if (fileExists(file_name)) { // Read lines one by one and testgrid FILE *fid = fopen(file_name.c_str(),"r"); if (fid == NULL) { cout << "DynamicInterpolation::file_load() Cannot open file for checking" << endl; exit(-1); } double xf, yf, zf; double *tmp = new double[num_output]; while (fscanf(fid, "%lg %lg %lg", &xf, &yf, &zf) == 3) { // Ensure that the gridpoint fits into the current grid bool in_grid = true; if ((xf < X0)||(xf >= X1)) { in_grid = false; } if ((yf < Y0)||(yf >= Y1)) { in_grid = false; } if ((zf < Z0)||(zf >= Z1)) { in_grid = false; } if (in_grid) { // Is point in my current grid? double ind_x = (xf-X0)/DX; double ind_y = (yf-Y0)/DY; double ind_z = (zf-Z0)/DZ; if (((fabs(round(ind_x)-ind_x)<ERROR_TOL)&&(fabs(round(ind_y)-ind_y))<ERROR_TOL)&&(fabs(round(ind_z)-ind_z)<ERROR_TOL)) { // Read rest of line for(int i = 0; i < num_output; i++) { int id = fscanf(fid," %lg",&(tmp[i])); } num_points_found++; //cout << "DynamicInterpolation::file_load(): "<< num_points_found << " found (" << xf << ", " << yf << ", " << zf << ") = (" << round(ind_x) << ", " << round(ind_y) << ", " << round(ind_z) << ")" << endl; // Put into correct location update_interpolation_grid(round(ind_x), round(ind_y), round(ind_z), tmp); } else { cout << "DynamicInterpolation::file_load() Gridpoint doesnt match. skipping: " << ind_x << ", " << ind_y << ", " << ind_z << endl; cout << "x: " << ind_x << ", floor(x) = " << round(ind_x) << ", diff = " << fabs(ind_x-round(ind_x)) << endl; cout << "y: " << ind_y << ", floor(y) = " << round(ind_y) << ", diff = " << fabs(ind_y-round(ind_y)) << endl; cout << "z: " << ind_z << ", floor(z) = " << round(ind_z) << ", diff = " << fabs(ind_z-round(ind_z)) << endl; // Skip rest of line //int id = fscanf(fid, "%*[^\n]\n", NULL); int id = fscanf(fid, "%*[^\n]\n"); } } } delete [] tmp; } return num_points_found; } //! Save current grid to file, do not overwrite old data /*! File has data stored as: "x y z data_array" on each line */ void file_save() { // Append new data to back of old file, or create if does not exist FILE *fid = fopen(file_name.c_str(),"a+"); if (fid != NULL) { // Check if each point exists in file already for(int i = 0; i < num_x; i++) { for(int j = 0; j < num_y; j++) { for(int k = 0; k < num_z; k++) { // Check if point exists in grid if (FXYZ[i][j][k] != NULL) { double x = X0 + i*DX; double y = Y0 + j*DY; double z = Z0 + k*DZ; // Check if point is in the file already if (!file_does_point_exist(x,y,z)) { fprintf(fid,"% .16e % .16e % .16e",x,y,z); for(int m = 0; m < num_output; m++) { fprintf(fid," % .16e",FXYZ[i][j][k][m]); } fprintf(fid,"\n"); } } } } } } else { cout << "DynamicInterpolation::file_save() Could not open file for saving, out of storage??" << endl; } fclose(fid); } private: //! Check if a (x,y,z) point exists in a saved-file /*! Return true if point (x,y,z) exists in the file. Otherwise return false */ bool file_does_point_exist(double x,double y,double z) { FILE *fid = fopen(file_name.c_str(),"r"); if (fid == NULL) { cout << "DynamicInterpolation::file_does_not_exist() Cannot open file for checking" << endl; exit(-1); } double xf, yf, zf; while (fscanf(fid, "%lg %lg %lg", &xf, &yf, &zf) == 3) { double dist = sqrt((xf-x)*(xf-x) + (yf-y)*(yf-y) + (zf-z)*(zf-z)); if (dist<ERROR_TOL) { fclose(fid); return true; } // Read until newline, put whatever is there nowhere //int id = fscanf(fid, "%*[^\n]\n", NULL); int id = fscanf(fid, "%*[^\n]\n"); } fclose(fid); return false; } //! File name to read/write from std::string file_name; //! Interpolation X-GRID lower limit double X0; //! Interpolation X-GRID upper limit double X1; //! Interpolation X-GRID spacing double DX; //! Interpolation X-GRID number of elements int num_x; //! Interpolation Y-GRID lower limit double Y0; //! Interpolation Y-GRID upper limit double Y1; //! Interpolation Y-GRID spacing double DY; //! Interpolation Y-GRID number of elements int num_y; //! Interpolation Z-GRID lower limit double Z0; //! Interpolation Z-GRID upper limit double Z1; //! Interpolation Z-GRID spacing double DZ; //! Interpolation Z-GRID number of elements int num_z; //! Interpolation x-index int x_target_ind; //! Interpolation y-index int y_target_ind; //! Interpolation z-index int z_target_ind; //! X-range for interpolatoin double *x_target; //! Y-range for interpolatoin double *y_target; //! Z-range for interpolatoin double *z_target; //! The output-dimension of the target function int num_output; //! The computed function values used in interpolations double ****FXYZ; //! Temporary storage for interpolation function double ****fxyz; //! File IO error tolerance double ERROR_TOL; //void (*F)(double*, double,double, double); // Function that should be interpolated }; #endif
26.947368
212
0.551975
[ "3d" ]
3b1678074e0d56d10b58ec37ca70c58f004fad74
2,005
cpp
C++
buildVS2013/predict_labels/tools/prediction_example.cpp
jwyang/JULE-Caffe
797292223e9e9021e31730c87b9abc86f08fce0c
[ "MIT" ]
22
2016-11-14T18:43:50.000Z
2020-03-05T05:51:19.000Z
buildVS2013/predict_labels/tools/prediction_example.cpp
jwyang/JULE-Caffe
797292223e9e9021e31730c87b9abc86f08fce0c
[ "MIT" ]
2
2017-04-20T03:05:41.000Z
2019-08-25T14:07:33.000Z
buildVS2013/predict_labels/tools/prediction_example.cpp
jwyang/JULE-Caffe
797292223e9e9021e31730c87b9abc86f08fce0c
[ "MIT" ]
6
2016-11-22T19:37:45.000Z
2020-02-18T13:52:22.000Z
#include <cstring> #include <cstdlib> #include <vector> #include <string> #include <iostream> #include <stdio.h> #include <assert.h> #include "caffe/caffe.hpp" #include "caffe/util/io.hpp" #include "caffe/blob.hpp" using namespace caffe; using namespace std; int main(int argc, char** argv) { LOG(INFO) << argv[0] << " [GPU] [Device ID]"; //Setting CPU or GPU if (argc >= 2 && strcmp(argv[1], "GPU") == 0) { Caffe::set_mode(Caffe::GPU); int device_id = 0; if (argc == 3) { device_id = atoi(argv[2]); } Caffe::SetDevice(device_id); LOG(INFO) << "Using GPU #" << device_id; } else { LOG(INFO) << "Using CPU"; Caffe::set_mode(Caffe::CPU); } // Set to TEST Phase Caffe::set_phase(Caffe::TEST); // Load net // Assume you are in Caffe master directory Net<float> net("./examples/prediction_example/prediction_example.prototxt"); // Load pre-trained net (binary proto) // Assume you are already trained the cifar10 example. net.CopyTrainedLayersFrom("./examples/cifar10/cifar10_quick_iter_5000.caffemodel"); float loss = 0.0; vector<Blob<float>*> results = net.ForwardPrefilled(&loss); LOG(INFO) << "Result size: "<< results.size(); // Log how many blobs were loaded LOG(INFO) << "Blob size: "<< net.input_blobs().size(); LOG(INFO)<< "-------------"; LOG(INFO)<< " prediction : "; // Get probabilities const boost::shared_ptr<Blob<float> >& probLayer = net.blob_by_name("prob"); const float* probs_out = probLayer->cpu_data(); // Get argmax results const boost::shared_ptr<Blob<float> >& argmaxLayer = net.blob_by_name("argmax"); // Display results LOG(INFO) << "---------------------------------------------------------------"; const float* argmaxs = argmaxLayer->cpu_data(); for (int i = 0; i < argmaxLayer->num(); i++) { LOG(INFO) << "Pattern:"<< i << " class:" << argmaxs[i*argmaxLayer->height() + 0] << " Prob=" << probs_out[i*probLayer->height() + 0]; } LOG(INFO)<< "-------------"; return 0; }
25.0625
135
0.61197
[ "vector" ]
3b1d161941ba4283253d8c0f89d5f8cf62c0f4a7
2,592
hpp
C++
src/include/Navigator/NavigatorMode.hpp
grigorievich/Viy
c78cfb55e548ce40b9fe3756e4ce2a923b84a552
[ "Apache-2.0" ]
14
2017-09-08T09:20:37.000Z
2020-09-20T10:56:22.000Z
src/include/Navigator/NavigatorMode.hpp
grigorievich/Viy
c78cfb55e548ce40b9fe3756e4ce2a923b84a552
[ "Apache-2.0" ]
null
null
null
src/include/Navigator/NavigatorMode.hpp
grigorievich/Viy
c78cfb55e548ce40b9fe3756e4ce2a923b84a552
[ "Apache-2.0" ]
2
2018-02-14T16:52:33.000Z
2018-06-20T22:16:02.000Z
#ifndef NAVIGATOR_MODE_HPP #define NAVIGATOR_MODE_HPP #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/RenderTexture.hpp> #include <SFML/Graphics/Font.hpp> #include <SFML/Graphics/Sprite.hpp> #include <SFML/System/Time.hpp> #include <SFML/Window/Event.hpp> #include <SFML/Graphics/Text.hpp> #include <RecordSystem.hpp> #include <Navigator/Signals.hpp> #include <NavigatorModeRenderer.hpp> #include <ResourceHolder.hpp> #include <ResourceIdentifiers.hpp> #include <utility> //pair class NavigatorMode { friend class NavigatorModeRenderer; public: enum Mode {Normal, Search, Rename}; enum ItemKind { ParentFolder, CurrentFolder, NestedFolder, NestedRecord }; public: NavigatorMode(RecordSystem &recordSystem, sf::RenderTexture &renderTexture, NavigatorSignals &signals); void render(sf::RenderTarget &target, const sf::RenderStates &states) const; void update(sf::Time dt); void refresh() { mNeedUpdate = true; update(sf::Time::Zero); }; virtual void handleEvent(const sf::Event &event); virtual void atSwitchingOn(); virtual void atSwitchingOff(); void resize(int width, int height); sf::Vector2u getSize() const { return mRenderer.getSize(); } private: virtual void processTasks() = 0; virtual void updateFromRecordSystem() = 0; virtual void adjustView(); void scrollDown(); void scrollUp(); protected: std::pair<ItemKind, unsigned int> getItemInfo(unsigned int index) const; virtual void enter(); protected: struct View { //Item could be: parent folder, nested folder or nested record. //Current folder is skipped. int topItem = 0, currentItem = 0, //relative to the top >= 0 maxItems = 10, totalItems = 0; } mView; RecordSystem &mRecordSystem; protected: //make const Folder * mCurrentFolder; std::vector<const Folder *> mPathToCurrentFolder; bool mNeedUpdate = true; NavigatorSignals &mSignals; private: NavigatorModeRenderer mRenderer; }; #endif
24
85
0.559799
[ "render", "vector" ]
3b2b911a83daaf511523ff09c7cef229d368465a
1,694
cpp
C++
BloomFramework/src/Graphics/SpriteText.cpp
LumpBloom7/BloomFramework
d714c014343be0fe29e119bcf827fe2b59a7ef4f
[ "MIT" ]
2
2019-12-23T19:39:38.000Z
2020-06-22T11:51:11.000Z
BloomFramework/src/Graphics/SpriteText.cpp
BloomCreativeWorks/BloomFramework
d714c014343be0fe29e119bcf827fe2b59a7ef4f
[ "MIT" ]
27
2018-08-16T14:47:45.000Z
2019-10-01T21:42:48.000Z
BloomFramework/src/Graphics/SpriteText.cpp
LumpBloom7/BloomFramework
d714c014343be0fe29e119bcf827fe2b59a7ef4f
[ "MIT" ]
6
2018-08-12T07:59:37.000Z
2019-12-23T19:39:40.000Z
#include "Exception.h" #include "Graphics/SpriteText.h" namespace bloom::graphics { SpriteText::SpriteText(SDL_Renderer* targetRenderer, std::shared_ptr<Font> fontPtr, std::string_view text, TextStyle style) : Drawable(targetRenderer), m_fontPtr(std::move(fontPtr)), m_text(text), m_style(style) { refreshTexture(); } void SpriteText::render(std::optional<SDL_Rect> srcRect, SDL_Point destPoint, SDL_RendererFlip flip) { if (m_refreshRequired) refreshTexture(); if (m_texture) Drawable::render(srcRect, SDL_Rect{ destPoint.x, destPoint.y, m_width, m_height }, flip); } void SpriteText::refreshTexture() { if (m_texture) { SDL_DestroyTexture(m_texture); m_texture = nullptr; } if (m_text.empty()) { m_width = m_height = 0; return; } SDL_Surface* textSurface = nullptr; switch (m_style.blendingMode) { case TextStyle::BlendingMode::normal: textSurface = TTF_RenderUTF8_Solid(*m_fontPtr, m_text.c_str(), m_style.foregroundColor); break; case TextStyle::BlendingMode::shaded: textSurface = TTF_RenderUTF8_Shaded(*m_fontPtr, m_text.c_str(), m_style.foregroundColor, m_style.backgroundColor); break; case TextStyle::BlendingMode::blended: textSurface = TTF_RenderUTF8_Blended(*m_fontPtr, m_text.c_str(), m_style.foregroundColor); break; } if (!textSurface) throw Exception{ "SpriteText::refreshTexture", TTF_GetError() }; m_texture = SDL_CreateTextureFromSurface(c_renderer, textSurface); SDL_FreeSurface(textSurface); if (!m_texture) throw Exception{ "SpriteText::refreshTexture", SDL_GetError()}; SDL_QueryTexture(m_texture, nullptr, nullptr, &m_width, &m_height); m_refreshRequired = false; } }
30.25
126
0.739079
[ "render" ]
3b2e1eddf8587e9ebd22d688fd717ab92e543680
348
hpp
C++
SQL/ProductMysql.hpp
useryoung-2019/MyHttpServer
ce23c1bf161edba08a82d54de6693167a8917d18
[ "MIT" ]
null
null
null
SQL/ProductMysql.hpp
useryoung-2019/MyHttpServer
ce23c1bf161edba08a82d54de6693167a8917d18
[ "MIT" ]
null
null
null
SQL/ProductMysql.hpp
useryoung-2019/MyHttpServer
ce23c1bf161edba08a82d54de6693167a8917d18
[ "MIT" ]
null
null
null
#ifndef PRODUCTMYSQL_H #define PRODUCTMYSQL_H #include"MysqlConnectPool.hpp" #include"AbstractProductSQL.hpp" class ProductMysql:public AbstractProductSQL { public: bool selectFromSQL(string& name, pair<string, string>& ret); bool selectFromSQL(string& str, vector<pair<string, string>>& ret); bool IDUIntoSQL(string& str); }; #endif
23.2
71
0.764368
[ "vector" ]
3b377e7ab6df09855bec7526eb1c42e561882434
7,371
cpp
C++
src/Render/GHTextureDataFactoryASTC.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
src/Render/GHTextureDataFactoryASTC.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
src/Render/GHTextureDataFactoryASTC.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
#include "GHTextureDataFactoryASTC.h" #include <cstdint> #include <assert.h> #include "GHPlatform/GHDebugMessage.h" #include "GHTextureFormat.h" #include "GHTextureData.h" #include "GHMath/GHPoint.h" struct ASTCHeader { uint8_t magic[4]; uint8_t blockDim_x; uint8_t blockDim_y; uint8_t blockDim_z; uint8_t xsize[3]; uint8_t ysize[3]; uint8_t zsize[3]; }; static GHTextureFormat::Enum getGHTextureFormat(const ASTCHeader& header) { if (header.blockDim_z != 1) { assert(header.blockDim_z == 1); GHDebugMessage::outputString("Only 2D ASTC textures are supported"); return GHTextureFormat::TF_UNKNOWN; } if (header.blockDim_x == 4) { if (header.blockDim_y == 4) { return GHTextureFormat::TF_ASTC_4x4; } } else if (header.blockDim_x == 5) { if (header.blockDim_y == 4) { return GHTextureFormat::TF_ASTC_5x4; } else if (header.blockDim_y == 5) { return GHTextureFormat::TF_ASTC_5x5; } } else if (header.blockDim_x == 6) { if (header.blockDim_y == 5) { return GHTextureFormat::TF_ASTC_6x5; } else if (header.blockDim_y == 6) { return GHTextureFormat::TF_ASTC_6x6; } } else if (header.blockDim_x == 8) { if (header.blockDim_y == 5) { return GHTextureFormat::TF_ASTC_8x5; } else if (header.blockDim_y == 6) { return GHTextureFormat::TF_ASTC_8x6; } else if (header.blockDim_y == 8) { return GHTextureFormat::TF_ASTC_8x8; } } else if (header.blockDim_x == 10) { if (header.blockDim_y == 5) { return GHTextureFormat::TF_ASTC_10x5; } else if (header.blockDim_y == 6) { return GHTextureFormat::TF_ASTC_10x6; } else if (header.blockDim_y == 8) { return GHTextureFormat::TF_ASTC_10x8; } else if (header.blockDim_y == 10) { return GHTextureFormat::TF_ASTC_10x10; } } else if (header.blockDim_x == 12) { if (header.blockDim_y == 10) { return GHTextureFormat::TF_ASTC_12x10; } else if (header.blockDim_y == 12) { return GHTextureFormat::TF_ASTC_12x12; } } return GHTextureFormat::TF_UNKNOWN; } static void getBlockDimFromTextureFormat(GHTextureFormat::Enum textureFormat, GHPoint3i& outBlockDim) { switch (textureFormat) { case GHTextureFormat::TF_ASTC_4x4: outBlockDim.setCoords(4,4,1); break; case GHTextureFormat::TF_ASTC_5x4: outBlockDim.setCoords(5,4,1); break; case GHTextureFormat::TF_ASTC_5x5: outBlockDim.setCoords(5,5,1); break; case GHTextureFormat::TF_ASTC_6x5: outBlockDim.setCoords(6,5,1); break; case GHTextureFormat::TF_ASTC_6x6: outBlockDim.setCoords(6,6,1); break; case GHTextureFormat::TF_ASTC_8x5: outBlockDim.setCoords(8,5,1); break; case GHTextureFormat::TF_ASTC_8x6: outBlockDim.setCoords(8,6,1); break; case GHTextureFormat::TF_ASTC_8x8: outBlockDim.setCoords(8,8,1); break; case GHTextureFormat::TF_ASTC_10x5: outBlockDim.setCoords(10,5,1); break; case GHTextureFormat::TF_ASTC_10x6: outBlockDim.setCoords(10,6,1); break; case GHTextureFormat::TF_ASTC_10x8: outBlockDim.setCoords(10,8,1); break; case GHTextureFormat::TF_ASTC_10x10: outBlockDim.setCoords(10,10,1); break; case GHTextureFormat::TF_ASTC_12x10: outBlockDim.setCoords(12,10,1); break; case GHTextureFormat::TF_ASTC_12x12: outBlockDim.setCoords(12,12,1); break; case GHTextureFormat::TF_ASTC_3x3x3: outBlockDim.setCoords(3,3,3); break; case GHTextureFormat::TF_ASTC_4x3x3: outBlockDim.setCoords(4,3,3); break; case GHTextureFormat::TF_ASTC_4x4x3: outBlockDim.setCoords(4,4,3); break; case GHTextureFormat::TF_ASTC_4x4x4: outBlockDim.setCoords(4,4,4); break; case GHTextureFormat::TF_ASTC_5x4x4: outBlockDim.setCoords(5,4,4); break; case GHTextureFormat::TF_ASTC_5x5x4: outBlockDim.setCoords(5,5,4); break; case GHTextureFormat::TF_ASTC_5x5x5: outBlockDim.setCoords(5,5,5); break; case GHTextureFormat::TF_ASTC_6x5x5: outBlockDim.setCoords(6,5,5); break; case GHTextureFormat::TF_ASTC_6x6x5: outBlockDim.setCoords(6,6,5); break; case GHTextureFormat::TF_ASTC_6x6x6: outBlockDim.setCoords(6,6,6); break; default: assert(false && "invalid ASTC texture format (note: 3d texture support hasn't been added yet)"); } } static uint32_t getTextureBufferSize(const GHPoint3i& blockDim, const GHPoint2i textureDim) { // todo: support 3d textures. uint32_t xBlocks = (textureDim[0] + blockDim[0] - 1) / blockDim[0]; uint32_t yBlocks = (textureDim[1] + blockDim[1] - 1) / blockDim[1]; return xBlocks * yBlocks * 16; } static GHTextureData* createAstcTextureDataFromMemoryCommon(const GHPoint3i& blockDim, const GHPoint2i textureDim, GHTextureFormat::Enum textureFormat, void* dataSource, void* textureStart, size_t textureSize, size_t mipLevels) { //The main texture counts as a mip level if (mipLevels == 0) { mipLevels = 1; } GHTextureData* ret = new GHTextureData(); ret->mDataSource = (int8_t*)dataSource; ret->mSrgb = false; // todo? ret->mDepth = 4; // not correct but doesn't matter? ret->mChannelType = GHTextureChannelType::TC_UBYTE; // not really correct but doesn't matter? ret->mTextureFormat = textureFormat; void* mipData = textureStart; ret->mMipLevels.resize(mipLevels); GHPoint2i mipDim = textureDim; for (size_t i = 0; i < mipLevels; ++i) { uint32_t mipSize = getTextureBufferSize(blockDim, mipDim); ret->mMipLevels[i].mData = mipData; ret->mMipLevels[i].mDataSize = mipSize; ret->mMipLevels[i].mHeight = mipDim[1]; ret->mMipLevels[i].mWidth = mipDim[0]; mipData = ((uint8_t*)mipData) + mipSize; mipDim[0] >>= 1; mipDim[1] >>= 1; if (mipDim[0] < 1) { mipDim[0] = 1; } if (mipDim[1] < 1) { mipDim[1] = 1; } } return ret; } GHTextureData* GHTextureDataFactoryASTC::createFromMemory(void* data, size_t dataSize) const { if (dataSize < sizeof(ASTCHeader)) { return 0; } ASTCHeader* header = (ASTCHeader*)data; GHTextureFormat::Enum textureFormat = getGHTextureFormat(*header); if (textureFormat == GHTextureFormat::TF_UNKNOWN) { GHDebugMessage::outputString("Unhandled ASTC format"); return 0; } void* textureStart = (int8_t*)data + sizeof(ASTCHeader); size_t textureSize = dataSize - sizeof(ASTCHeader); size_t mipLevels = 0; // todo: miplevels. It seems .astc does not support them? int w = ((int)header->xsize[2] << 16) | ((int)header->xsize[1] << 8) | ((int)header->xsize[0]); int h = ((int)header->ysize[2] << 16) | ((int)header->ysize[1] << 8) | ((int)header->ysize[0]); return createAstcTextureDataFromMemoryCommon(GHPoint3i(header->blockDim_x, header->blockDim_y, header->blockDim_z), GHPoint2i(w, h), textureFormat, data, textureStart, textureSize, mipLevels); } GHTextureData* GHTextureDataFactoryASTC::createFromMemoryWithMips(void* data, size_t dataSize, GHTextureFormat::Enum textureFormat, unsigned int width, unsigned int height, unsigned int mipCount, bool headerExists) { GHTextureData* ret = 0; if (headerExists) { ret = createFromMemory(data, dataSize); } else { GHPoint3i blockDim; getBlockDimFromTextureFormat(textureFormat, blockDim); ret = createAstcTextureDataFromMemoryCommon(blockDim, GHPoint2i(width, height), textureFormat, data, data, dataSize, mipCount); } assert(ret); assert(ret->mTextureFormat == textureFormat); assert(ret->mMipLevels.size() == mipCount || (mipCount == 0 && ret->mMipLevels.size() == 1)); assert(ret->mMipLevels[0].mWidth == width); assert(ret->mMipLevels[0].mHeight == height); return ret; }
32.328947
227
0.72324
[ "3d" ]
3b385f4540d5f2ae81bde14e3e5d177532266a51
7,504
cpp
C++
ugene/src/corelibs/U2View/src/ov_phyltree/TreeViewerTasks.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2View/src/ov_phyltree/TreeViewerTasks.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2View/src/ov_phyltree/TreeViewerTasks.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "TreeViewerTasks.h" #include "TreeViewer.h" #include "TreeViewerFactory.h" #include "TreeViewerState.h" #include "CreateRectangularBranchesTask.h" #include "GraphicsRectangularBranchItem.h" #include <U2Core/Log.h> #include <U2Core/L10n.h> #include <U2Core/AppContext.h> #include <U2Core/ProjectModel.h> #include <U2Core/DocumentModel.h> #include <U2Core/PhyTreeObject.h> #include <U2Core/UnloadedObject.h> #include <U2Core/GObjectTypes.h> #include <U2Core/U2SafePoints.h> #include <QtCore/QSet> namespace U2 { /* TRANSLATOR U2::TreeViewer */ /* TRANSLATOR U2::ObjectViewTask */ ////////////////////////////////////////////////////////////////////////// /// open new view OpenTreeViewerTask::OpenTreeViewerTask(PhyTreeObject* _obj) : ObjectViewTask(TreeViewerFactory::ID), phyObject(_obj) { assert(!phyObject.isNull()); } OpenTreeViewerTask::OpenTreeViewerTask(UnloadedObject* _obj) : ObjectViewTask(TreeViewerFactory::ID), unloadedReference(_obj) { assert(_obj->getLoadedObjectType() == GObjectTypes::PHYLOGENETIC_TREE); documentsToLoad.append(_obj->getDocument()); } OpenTreeViewerTask::OpenTreeViewerTask(Document* doc) : ObjectViewTask(TreeViewerFactory::ID), phyObject(NULL) { assert(!doc->isLoaded()); documentsToLoad.append(doc); } void OpenTreeViewerTask::open() { if (stateInfo.hasError() || (phyObject.isNull() && documentsToLoad.isEmpty())) { return; } if (phyObject.isNull()) { Document* doc = documentsToLoad.first(); QList<GObject*> objects; if (unloadedReference.isValid()) { GObject* obj = doc->findGObjectByName(unloadedReference.objName); if (obj != NULL && obj->getGObjectType() == GObjectTypes::PHYLOGENETIC_TREE) { phyObject = qobject_cast<PhyTreeObject*>(obj); } } else { QList<GObject*> objects = doc->findGObjectByType(GObjectTypes::PHYLOGENETIC_TREE, UOF_LoadedAndUnloaded); phyObject = objects.isEmpty() ? NULL : qobject_cast<PhyTreeObject*>(objects.first()); } if (phyObject.isNull()) { stateInfo.setError(tr("Phylogenetic tree object not found")); return; } } viewName = GObjectViewUtils::genUniqueViewName(phyObject->getDocument(), phyObject); uiLog.details(tr("Opening tree viewer for object %1").arg(phyObject->getGObjectName())); Task* createTask = new CreateTreeViewerTask(viewName, phyObject, stateData); TaskScheduler* scheduler = AppContext::getTaskScheduler(); scheduler->registerTopLevelTask(createTask); } void OpenTreeViewerTask::updateTitle(TreeViewer* tv) { const QString& oldViewName = tv->getName(); GObjectViewWindow* w = GObjectViewUtils::findViewByName(oldViewName); if (w != NULL) { PhyTreeObject* phyObj = tv->getPhyObject(); QString newViewName = GObjectViewUtils::genUniqueViewName(phyObj->getDocument(), phyObj); tv->setName(newViewName); w->setWindowTitle(newViewName); } } ////////////////////////////////////////////////////////////////////////// // open view from state OpenSavedTreeViewerTask::OpenSavedTreeViewerTask(const QString& viewName, const QVariantMap& stateData) : ObjectViewTask(TreeViewerFactory::ID, viewName, stateData) { TreeViewerState state(stateData); GObjectReference ref = state.getPhyObject(); Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { doc = createDocumentAndAddToProject(ref.docUrl, AppContext::getProject(), stateInfo); CHECK_OP_EXT(stateInfo, stateIsIllegal = true, ); } if (!doc->isLoaded()) { documentsToLoad.append(doc); } } void OpenSavedTreeViewerTask::open() { if (stateInfo.hasError()) { return; } TreeViewerState state(stateData); GObjectReference ref = state.getPhyObject(); Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { stateIsIllegal = true; stateInfo.setError(L10N::errorDocumentNotFound(ref.docUrl)); return; } GObject* obj = doc->findGObjectByName(ref.objName); if (obj == NULL || obj->getGObjectType() != GObjectTypes::PHYLOGENETIC_TREE) { stateIsIllegal = true; stateInfo.setError(tr("DNA sequence object not found: %1").arg(ref.objName)); return; } PhyTreeObject* phyObject = qobject_cast<PhyTreeObject*>(obj); assert(phyObject != NULL); Task* createTask = new CreateTreeViewerTask(viewName, phyObject, stateData); TaskScheduler* scheduler = AppContext::getTaskScheduler(); scheduler->registerTopLevelTask(createTask); } void OpenSavedTreeViewerTask::updateRanges(const QVariantMap& stateData, TreeViewer* ctx) { TreeViewerState state(stateData); QTransform m = state.getTransform(); if (m != QTransform()) { ctx->setTransform(m); } qreal zoom = state.getZoom(); ctx->setZoom(zoom); ctx->setSettingsState(stateData); } ////////////////////////////////////////////////////////////////////////// // update UpdateTreeViewerTask::UpdateTreeViewerTask(GObjectView* v, const QString& stateName, const QVariantMap& stateData) : ObjectViewTask(v, stateName, stateData) { } void UpdateTreeViewerTask::update() { if (view.isNull() || view->getFactoryId() != TreeViewerFactory::ID) { return; //view was closed; } TreeViewer* phyView = qobject_cast<TreeViewer*>(view.data()); assert(phyView != NULL); OpenSavedTreeViewerTask::updateRanges(stateData, phyView); } ////////////////////////////////////////////////////////////////////////// /// create view CreateTreeViewerTask::CreateTreeViewerTask(const QString& name, const QPointer<PhyTreeObject>& obj, const QVariantMap& sData) : Task("Open tree viewer", TaskFlag_NoRun), viewName(name), phyObj(obj), subTask(NULL), stateData(sData) {} void CreateTreeViewerTask::prepare() { subTask = new CreateRectangularBranchesTask(phyObj->getTree()->rootNode); addSubTask(subTask); } Task::ReportResult CreateTreeViewerTask::report() { GraphicsRectangularBranchItem* root = dynamic_cast<GraphicsRectangularBranchItem*>(subTask->getResult()); TreeViewer* v = new TreeViewer(viewName, phyObj, root, subTask->getScale()); GObjectViewWindow* w = new GObjectViewWindow(v, viewName, !stateData.isEmpty()); MWMDIManager* mdiManager = AppContext::getMainWindow()->getMDIManager(); mdiManager->addMDIWindow(w); if (!stateData.isEmpty()) { OpenSavedTreeViewerTask::updateRanges(stateData, v); } return Task::ReportResult_Finished; } } // namespace
35.563981
125
0.679638
[ "object" ]
3b392c9e1ead81cbfbe77649bd5836bd6275de68
4,636
hpp
C++
include/BGNet/Core/Messages/ChangeCipherSpecRequest.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/BGNet/Core/Messages/ChangeCipherSpecRequest.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/BGNet/Core/Messages/ChangeCipherSpecRequest.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: BGNet.Core.Messages.BaseReliableResponse #include "BGNet/Core/Messages/BaseReliableResponse.hpp" // Including type: BGNet.Core.Messages.IHandshakeServerToClientMessage #include "BGNet/Core/Messages/IHandshakeServerToClientMessage.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: PacketPool`1<T> template<typename T> class PacketPool_1; } // Completed forward declares // Type namespace: BGNet.Core.Messages namespace BGNet::Core::Messages { // Forward declaring type: ChangeCipherSpecRequest class ChangeCipherSpecRequest; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::BGNet::Core::Messages::ChangeCipherSpecRequest); DEFINE_IL2CPP_ARG_TYPE(::BGNet::Core::Messages::ChangeCipherSpecRequest*, "BGNet.Core.Messages", "ChangeCipherSpecRequest"); // Type namespace: BGNet.Core.Messages namespace BGNet::Core::Messages { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: BGNet.Core.Messages.ChangeCipherSpecRequest // [TokenAttribute] Offset: FFFFFFFF class ChangeCipherSpecRequest : public ::BGNet::Core::Messages::BaseReliableResponse/*, public ::BGNet::Core::Messages::IHandshakeServerToClientMessage*/ { public: // Creating interface conversion operator: operator ::BGNet::Core::Messages::IHandshakeServerToClientMessage operator ::BGNet::Core::Messages::IHandshakeServerToClientMessage() noexcept { return *reinterpret_cast<::BGNet::Core::Messages::IHandshakeServerToClientMessage*>(this); } // static public PacketPool`1<BGNet.Core.Messages.ChangeCipherSpecRequest> get_pool() // Offset: 0x14F61E0 static ::GlobalNamespace::PacketPool_1<::BGNet::Core::Messages::ChangeCipherSpecRequest*>* get_pool(); // public System.Void .ctor() // Offset: 0x14FDC20 // Implemented from: BGNet.Core.Messages.BaseReliableResponse // Base method: System.Void BaseReliableResponse::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ChangeCipherSpecRequest* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::BGNet::Core::Messages::ChangeCipherSpecRequest::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ChangeCipherSpecRequest*, creationType>())); } // public override System.Void Release() // Offset: 0x14FDBC4 // Implemented from: BGNet.Core.Messages.BaseReliableResponse // Base method: System.Void BaseReliableResponse::Release() void Release(); }; // BGNet.Core.Messages.ChangeCipherSpecRequest #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: BGNet::Core::Messages::ChangeCipherSpecRequest::get_pool // Il2CppName: get_pool template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::PacketPool_1<::BGNet::Core::Messages::ChangeCipherSpecRequest*>* (*)()>(&BGNet::Core::Messages::ChangeCipherSpecRequest::get_pool)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(BGNet::Core::Messages::ChangeCipherSpecRequest*), "get_pool", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: BGNet::Core::Messages::ChangeCipherSpecRequest::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: BGNet::Core::Messages::ChangeCipherSpecRequest::Release // Il2CppName: Release template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (BGNet::Core::Messages::ChangeCipherSpecRequest::*)()>(&BGNet::Core::Messages::ChangeCipherSpecRequest::Release)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(BGNet::Core::Messages::ChangeCipherSpecRequest*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
53.287356
221
0.753236
[ "object", "vector" ]
3b3e31871d31c23d2cb3d98f6df42625f3096bd8
30,567
cpp
C++
Source/Hacks/Misc.cpp
Nitsuj1337/Osiris
35a81d3cdc1d97d68c9d91d3cd6d6788a6601a7e
[ "MIT" ]
null
null
null
Source/Hacks/Misc.cpp
Nitsuj1337/Osiris
35a81d3cdc1d97d68c9d91d3cd6d6788a6601a7e
[ "MIT" ]
null
null
null
Source/Hacks/Misc.cpp
Nitsuj1337/Osiris
35a81d3cdc1d97d68c9d91d3cd6d6788a6601a7e
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <iomanip> #include <mutex> #include <numbers> #include <numeric> #include <sstream> #include <vector> #include <imgui/imgui.h> #define IMGUI_DEFINE_MATH_OPERATORS #include <imgui/imgui_internal.h> #include <imgui/imgui_stdlib.h> #include "../ConfigStructs.h" #include "../InputUtil.h" #include "../Interfaces.h" #include "../Memory.h" #include "../ProtobufReader.h" #include "EnginePrediction.h" #include "Misc.h" #include <SDK/Constants/ClassId.h> #include "../SDK/Client.h" #include "../SDK/ClientClass.h" #include "../SDK/ClientMode.h" #include "../SDK/ConVar.h" #include "../SDK/Cvar.h" #include "../SDK/Engine.h" #include "../SDK/EngineTrace.h" #include "../SDK/Entity.h" #include "../SDK/EntityList.h" #include <SDK/Constants/FrameStage.h> #include "../SDK/GameEvent.h" #include "../SDK/GlobalVars.h" #include "../SDK/ItemSchema.h" #include "../SDK/Localize.h" #include "../SDK/LocalPlayer.h" #include "../SDK/NetworkChannel.h" #include "../SDK/Panorama.h" #include "../SDK/Platform.h" #include "../SDK/UserCmd.h" #include "../SDK/UtlVector.h" #include "../SDK/Vector.h" #include "../SDK/WeaponData.h" #include "../SDK/WeaponId.h" #include "../SDK/WeaponSystem.h" #include "../GUI.h" #include "../Helpers.h" #include "../Hooks.h" #include "../GameData.h" #include "../imguiCustom.h" #include <deque> struct PreserveKillfeed { bool enabled = false; bool onlyHeadshots = false; }; struct MiscConfig { MiscConfig() { clanTag[0] = '\0'; } KeyBind menuKey{ KeyBind::INSERT }; bool inverseRagdollGravity{ false }; bool antiAfkKick{ false }; bool bunnyHop{ false }; bool customClanTag{ false }; bool clocktag{ false }; bool animatedClanTag{ false }; bool fastDuck{ false }; bool edgejump{ false }; bool slowwalk{ false }; bool autoAccept{ false }; bool revealRanks{ false }; bool revealSuspect{ false }; bool revealVotes{ false }; bool disablePanoramablur{ false }; bool bypassSvPure{ false }; bool rainbowCrosshair{ false }; bool rainbowHud{ false }; bool velocitygraph{ false }; PreserveKillfeed preserveKillfeed; char clanTag[16]; KeyBind edgejumpkey; KeyBind slowwalkKey; float rainbowCrosshairSpeed{ 1.0f }; int banColor{ 6 }; int skybox{ 0 }; int hopsHitchance{ 100 }; float VelocityY{ 0.0f }; float VelocityX{ 0.0f }; std::string banText{ "Cheater has been permanently banned from official CS:GO servers." }; std::string customSkybox; struct Reportbot { bool enabled = false; bool textAbuse = false; bool griefing = false; bool wallhack = true; bool aimbot = true; bool other = true; int target = 0; int delay = 1; int rounds = 1; } reportbot; } miscConfig; bool Misc::shouldEnableSvPureBypass() noexcept { return miscConfig.bypassSvPure; } bool Misc::shouldRevealSuspect() noexcept { return miscConfig.revealSuspect; } bool Misc::isMenuKeyPressed() noexcept { return miscConfig.menuKey.isPressed(); } void Misc::VelocityGraph() { ImDrawList* drawList = ImGui::GetBackgroundDrawList(); struct Record { float velocity; }; static std::deque<Record> records; int velocity; if (!miscConfig.velocitygraph || !localPlayer || !localPlayer->isAlive()) { records.clear(); return; } std::array<ImVec2, 200> points; Record record{ }; record.velocity = fabsf(localPlayer->velocity().length()); records.push_back(record); while (records.size() > 200) records.pop_front(); for (size_t i = 0; i < records.size(); i++) { ImVec2 pos = ImVec2{ miscConfig.VelocityX + i , miscConfig.VelocityY - (records[i].velocity * 0.2f) }; points[i] = pos; } drawList->AddPolyline(points.data(), records.size(), ImColor{ 255, 255, 255, 255 }, ImDrawFlags_None, 2.f); velocity = round(localPlayer->velocity().length2D()); char buf[5]; snprintf(buf,sizeof buf, "%d", velocity); drawList->AddText(ImVec2{ miscConfig.VelocityX + 10 , miscConfig.VelocityY + 10 }, ImColor{ 255, 255, 255, 255 },buf); } void Misc::edgejump(UserCmd* cmd) noexcept { if (!miscConfig.edgejump || !miscConfig.edgejumpkey.isDown()) return; if (!localPlayer || !localPlayer->isAlive()) return; if (const auto mt = localPlayer->moveType(); mt == MoveType::LADDER || mt == MoveType::NOCLIP) return; if ((EnginePrediction::getFlags() & 1) && !localPlayer->isOnGround()) cmd->buttons |= UserCmd::IN_JUMP; } void Misc::slowwalk(UserCmd* cmd) noexcept { if (!miscConfig.slowwalk || !miscConfig.slowwalkKey.isDown()) return; if (!localPlayer || !localPlayer->isAlive()) return; const auto activeWeapon = localPlayer->getActiveWeapon(); if (!activeWeapon) return; const auto weaponData = activeWeapon->getWeaponData(); if (!weaponData) return; const float maxSpeed = (localPlayer->isScoped() ? weaponData->maxSpeedAlt : weaponData->maxSpeed) / 3; if (cmd->forwardmove && cmd->sidemove) { const float maxSpeedRoot = maxSpeed * static_cast<float>(M_SQRT1_2); cmd->forwardmove = cmd->forwardmove < 0.0f ? -maxSpeedRoot : maxSpeedRoot; cmd->sidemove = cmd->sidemove < 0.0f ? -maxSpeedRoot : maxSpeedRoot; } else if (cmd->forwardmove) { cmd->forwardmove = cmd->forwardmove < 0.0f ? -maxSpeed : maxSpeed; } else if (cmd->sidemove) { cmd->sidemove = cmd->sidemove < 0.0f ? -maxSpeed : maxSpeed; } } void Misc::updateClanTag(bool tagChanged) noexcept { const float svtickrate = 1.f / memory->globalVars->intervalPerTick; int lagCompensation = GameData::getNetOutgoingLatency() / (1000.0f / svtickrate); int ticksPerChange = 1 * svtickrate; // Sec * TickRate //TODO: Add custom speed in menu int OffsetCount = static_cast<int>((memory->globalVars->tickCount + lagCompensation) / ticksPerChange); static int lastOffset = 0; if (miscConfig.clocktag) //Still the same { if (lastOffset == OffsetCount) //Prevent from changing clantag every tick return; const auto time = std::time(nullptr); const auto localTime = std::localtime(&time); char s[11]{}; s[0] = '\0'; snprintf(s, sizeof(s), "[%02d:%02d:%02d]", localTime->tm_hour, localTime->tm_min, localTime->tm_sec); lastOffset = OffsetCount; memory->setClanTag(s, s); } else if (miscConfig.customClanTag) { if (lastOffset == OffsetCount) //Prevent from changing clantag every tick return; std::u32string setTag = Helpers::To_UTF32(std::string(miscConfig.clanTag)); if (setTag.length() < 2) setTag = U"Osiris "; std::replace(setTag.begin(), setTag.end(), U' ', U'\u2800'); if (miscConfig.animatedClanTag) { auto offset = OffsetCount % setTag.length(); std::rotate(setTag.begin(), setTag.begin() + offset, setTag.end()); } lastOffset = OffsetCount; std::string _u8setTag = Helpers::To_UTF8(setTag); memory->setClanTag(_u8setTag.c_str(), _u8setTag.c_str()); } } void Misc::disablePanoramablur() noexcept { static auto blur = interfaces->cvar->findVar("@panorama_disable_blur"); blur->setValue(miscConfig.disablePanoramablur); } bool Misc::changeName(bool reconnect, const char* newName, float delay) noexcept { static auto exploitInitialized{ false }; static auto name{ interfaces->cvar->findVar("name") }; if (reconnect) { exploitInitialized = false; return false; } if (!exploitInitialized && interfaces->engine->isInGame()) { if (PlayerInfo playerInfo; localPlayer && interfaces->engine->getPlayerInfo(localPlayer->index(), playerInfo) && (!strcmp(playerInfo.name, "?empty") || !strcmp(playerInfo.name, "\n\xAD\xAD\xAD"))) { exploitInitialized = true; } else { name->onChangeCallbacks.size = 0; name->setValue("\n\xAD\xAD\xAD"); return false; } } if (static auto nextChangeTime = 0.0f; nextChangeTime <= memory->globalVars->realtime) { name->setValue(newName); nextChangeTime = memory->globalVars->realtime + delay; return true; } return false; } void Misc::bunnyHop(UserCmd* cmd) noexcept { if (!localPlayer) return; int hopsRestricted = 0; int hopsHit = 0; if (miscConfig.bunnyHop && localPlayer->moveType() != MoveType::LADDER) { if (cmd->buttons & UserCmd::IN_JUMP && !(localPlayer->flags() & 1)) { cmd->buttons &= ~UserCmd::IN_JUMP; hopsRestricted = 0; } else if ((rand() % 100 > miscConfig.hopsHitchance && hopsRestricted < 12)) { cmd->buttons &= ~UserCmd::IN_JUMP; hopsRestricted++; hopsHit = 0; } else hopsHit++; } } void Misc::fakeBan(bool set) noexcept { static bool shouldSet = false; if (set) shouldSet = set; if (shouldSet && interfaces->engine->isInGame() && changeName(false, std::string{ "\x1\xB" }.append(std::string{ static_cast<char>(miscConfig.banColor + 1) }).append(miscConfig.banText).append("\x1").c_str(), 5.0f)) shouldSet = false; } void Misc::antiAfkKick(UserCmd* cmd) noexcept { if (miscConfig.antiAfkKick && cmd->commandNumber % 2) cmd->buttons |= 1 << 27; } void Misc::revealRanks(UserCmd* cmd) noexcept { if (miscConfig.revealRanks && cmd->buttons & UserCmd::IN_SCORE) interfaces->client->dispatchUserMessage(50, 0, 0, nullptr); } void Misc::removeCrouchCooldown(UserCmd* cmd) noexcept { if (miscConfig.fastDuck) cmd->buttons |= UserCmd::IN_BULLRUSH; } static std::vector<std::uint64_t> reportedPlayers; static int reportbotRound; [[nodiscard]] static std::string generateReportString() { std::string report; if (miscConfig.reportbot.textAbuse) report += "textabuse,"; if (miscConfig.reportbot.griefing) report += "grief,"; if (miscConfig.reportbot.wallhack) report += "wallhack,"; if (miscConfig.reportbot.aimbot) report += "aimbot,"; if (miscConfig.reportbot.other) report += "speedhack,"; return report; } [[nodiscard]] static bool isPlayerReported(std::uint64_t xuid) { return std::ranges::find(std::as_const(reportedPlayers), xuid) != reportedPlayers.cend(); } [[nodiscard]] static std::vector<std::uint64_t> getXuidsOfCandidatesToBeReported() { std::vector<std::uint64_t> xuids; for (int i = 1; i <= interfaces->engine->getMaxClients(); ++i) { const auto entity = interfaces->entityList->getEntity(i); if (!entity || entity == localPlayer.get()) continue; if (miscConfig.reportbot.target != 2 && (localPlayer->isOtherEnemy(entity) ? miscConfig.reportbot.target != 0 : miscConfig.reportbot.target != 1)) continue; if (PlayerInfo playerInfo; interfaces->engine->getPlayerInfo(i, playerInfo) && !playerInfo.fakeplayer) xuids.push_back(playerInfo.xuid); } return xuids; } void Misc::runReportbot() noexcept { if (!miscConfig.reportbot.enabled) return; if (!localPlayer) return; static auto lastReportTime = 0.0f; if (lastReportTime + miscConfig.reportbot.delay > memory->globalVars->realtime) return; if (reportbotRound >= miscConfig.reportbot.rounds) return; for (const auto& xuid : getXuidsOfCandidatesToBeReported()) { if (isPlayerReported(xuid)) continue; if (const auto report = generateReportString(); !report.empty()) { memory->submitReport(std::to_string(xuid).c_str(), report.c_str()); lastReportTime = memory->globalVars->realtime; reportedPlayers.push_back(xuid); return; } } reportedPlayers.clear(); ++reportbotRound; } void Misc::resetReportbot() noexcept { reportbotRound = 0; reportedPlayers.clear(); } void Misc::preserveKillfeed(bool roundStart) noexcept { if (!miscConfig.preserveKillfeed.enabled) return; static auto nextUpdate = 0.0f; if (roundStart) { nextUpdate = memory->globalVars->realtime + 10.0f; return; } if (nextUpdate > memory->globalVars->realtime) return; nextUpdate = memory->globalVars->realtime + 2.0f; const auto deathNotice = std::uintptr_t(memory->findHudElement(memory->hud, "CCSGO_HudDeathNotice")); if (!deathNotice) return; const auto deathNoticePanel = (*(UIPanel**)(*reinterpret_cast<std::uintptr_t*>(deathNotice WIN32_LINUX(-20 + 88, -32 + 128)) + sizeof(std::uintptr_t))); const auto childPanelCount = deathNoticePanel->getChildCount(); for (int i = 0; i < childPanelCount; ++i) { const auto child = deathNoticePanel->getChild(i); if (!child) continue; if (child->hasClass("DeathNotice_Killer") && (!miscConfig.preserveKillfeed.onlyHeadshots || child->hasClass("DeathNoticeHeadShot"))) child->setAttributeFloat("SpawnTime", memory->globalVars->currenttime); } } void Misc::voteRevealer(GameEvent& event) noexcept { if (!miscConfig.revealVotes) return; const auto entity = interfaces->entityList->getEntity(event.getInt("entityid")); if (!entity || !entity->isPlayer()) return; const auto votedYes = event.getInt("vote_option") == 0; const auto isLocal = localPlayer && entity == localPlayer.get(); const char color = votedYes ? '\x06' : '\x07'; memory->clientMode->getHudChat()->printf(0, " \x0C\u2022Osiris\u2022 %c%s\x01 voted %c%s\x01", isLocal ? '\x01' : color, isLocal ? "You" : entity->getPlayerName().c_str(), color, votedYes ? "Yes" : "No"); } void Misc::onVoteStart(const void* data, int size) noexcept { if (!miscConfig.revealVotes) return; constexpr auto voteName = [](int index) { switch (index) { case 0: return "Kick"; case 1: return "Change Level"; case 6: return "Surrender"; case 13: return "Start TimeOut"; default: return ""; } }; const auto reader = ProtobufReader{ static_cast<const std::uint8_t*>(data), size }; const auto entityIndex = reader.readInt32(2); const auto entity = interfaces->entityList->getEntity(entityIndex); if (!entity || !entity->isPlayer()) return; const auto isLocal = localPlayer && entity == localPlayer.get(); const auto voteType = reader.readInt32(3); memory->clientMode->getHudChat()->printf(0, " \x0C\u2022Osiris\u2022 %c%s\x01 call vote (\x06%s\x01)", isLocal ? '\x01' : '\x06', isLocal ? "You" : entity->getPlayerName().c_str(), voteName(voteType)); } void Misc::onVotePass() noexcept { if (miscConfig.revealVotes) memory->clientMode->getHudChat()->printf(0, " \x0C\u2022Osiris\u2022\x01 Vote\x06 PASSED"); } void Misc::onVoteFailed() noexcept { if (miscConfig.revealVotes) memory->clientMode->getHudChat()->printf(0, " \x0C\u2022Osiris\u2022\x01 Vote\x07 FAILED"); } // ImGui::ShadeVertsLinearColorGradientKeepAlpha() modified to do interpolation in HSV static void shadeVertsHSVColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1) { ImVec2 gradient_extent = gradient_p1 - gradient_p0; float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; ImVec4 col0HSV = ImGui::ColorConvertU32ToFloat4(col0); ImVec4 col1HSV = ImGui::ColorConvertU32ToFloat4(col1); ImGui::ColorConvertRGBtoHSV(col0HSV.x, col0HSV.y, col0HSV.z, col0HSV.x, col0HSV.y, col0HSV.z); ImGui::ColorConvertRGBtoHSV(col1HSV.x, col1HSV.y, col1HSV.z, col1HSV.x, col1HSV.y, col1HSV.z); ImVec4 colDelta = col1HSV - col0HSV; for (ImDrawVert* vert = vert_start; vert < vert_end; vert++) { float d = ImDot(vert->pos - gradient_p0, gradient_extent); float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); float h = col0HSV.x + colDelta.x * t; float s = col0HSV.y + colDelta.y * t; float v = col0HSV.z + colDelta.z * t; ImVec4 rgb; ImGui::ColorConvertHSVtoRGB(h, s, v, rgb.x, rgb.y, rgb.z); vert->col = (ImGui::ColorConvertFloat4ToU32(rgb) & ~IM_COL32_A_MASK) | (vert->col & IM_COL32_A_MASK); } } void Misc::autoAccept(const char* soundEntry) noexcept { if (!miscConfig.autoAccept) return; if (std::strcmp(soundEntry, "UIPanorama.popup_accept_match_beep")) return; if (const auto idx = memory->registeredPanoramaEvents->find(memory->makePanoramaSymbol("MatchAssistedAccept")); idx != -1) { if (const auto eventPtr = memory->registeredPanoramaEvents->memory[idx].value.makeEvent(nullptr)) interfaces->panoramaUIEngine->accessUIEngine()->dispatchEvent(eventPtr); } #ifdef _WIN32 auto window = FindWindowW(L"Valve001", NULL); FLASHWINFO flash{ sizeof(FLASHWINFO), window, FLASHW_TRAY | FLASHW_TIMERNOFG, 0, 0 }; FlashWindowEx(&flash); ShowWindow(window, SW_RESTORE); #endif } void Misc::inverseRagdollGravity() noexcept { static auto ragdollGravity = interfaces->cvar->findVar("cl_ragdoll_gravity"); ragdollGravity->setValue(miscConfig.inverseRagdollGravity ? -600 : 600); } void Misc::skybox(FrameStage stage) noexcept { if (stage != FrameStage::RENDER_START && stage != FrameStage::RENDER_END) return; if (stage == FrameStage::RENDER_START && miscConfig.skybox > 0 && static_cast<std::size_t>(miscConfig.skybox) < skyboxList.size() - 1) { memory->loadSky(skyboxList[miscConfig.skybox]); } else if (miscConfig.skybox == 26 && stage == FrameStage::RENDER_START) { memory->loadSky(miscConfig.customSkybox.c_str()); } else { static const auto sv_skyname = interfaces->cvar->findVar("sv_skyname"); memory->loadSky(sv_skyname->string); } } void Misc::rainbowCrosshair() noexcept { const auto red = interfaces->cvar->findVar("cl_crosshaircolor_r"); const auto green = interfaces->cvar->findVar("cl_crosshaircolor_g"); const auto blue = interfaces->cvar->findVar("cl_crosshaircolor_b"); const auto color = interfaces->cvar->findVar("cl_crosshaircolor"); auto [r, g, b] = rainbowColor(miscConfig.rainbowCrosshairSpeed); r *= 255; g *= 255; b *= 255; static bool enabled = false; static float backupR = 0.0; static float backupG = 0.0; static float backupB = 0.0; static int backupColor = 0; if (miscConfig.rainbowCrosshair) { red->setValue(r); green->setValue(g); blue->setValue(b); color->setValue(5); enabled = true; } else { if (enabled) { red->setValue(backupR); green->setValue(backupG); blue->setValue(backupB); color->setValue(backupColor); } backupR = red->getFloat(); backupG = green->getFloat(); backupB = blue->getFloat(); backupColor = color->getInt(); enabled = false; } } void Misc::rainbowHud() noexcept { const auto cvar = interfaces->cvar->findVar("cl_hud_color"); constexpr float interval = 0.5f; static bool enabled = false; static int backup = 0; static float lastTime = 0.f; float realtime = memory->globalVars->realtime; if (miscConfig.rainbowHud) { static int currentColor = 0; if (realtime - lastTime > interval) { cvar->setValue(currentColor); currentColor++; if (currentColor > 10) currentColor = 0; lastTime = realtime; } enabled = true; } else { if (enabled) cvar->setValue(backup); backup = cvar->getInt(); enabled = false; } } void Misc::updateInput() noexcept { } static bool windowOpen = false; void Misc::menuBarItem() noexcept { if (ImGui::MenuItem("Misc")) { windowOpen = true; ImGui::SetWindowFocus("Misc"); ImGui::SetWindowPos("Misc", { 100.0f, 100.0f }); } } void Misc::tabItem() noexcept { if (ImGui::BeginTabItem("Misc")) { drawGUI(true); ImGui::EndTabItem(); } } void Misc::drawGUI(bool contentOnly) noexcept { if (!contentOnly) { if (!windowOpen) return; ImGui::SetNextWindowSize({ 580.0f, 0.0f }); ImGui::Begin("Misc", &windowOpen, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); } ImGui::Columns(2, nullptr, false); ImGui::SetColumnOffset(1, 270.0f); ImGui::hotkey("Menu Key", miscConfig.menuKey); ImGui::Checkbox("Anti AFK kick", &miscConfig.antiAfkKick); ImGui::Checkbox("Bunny hop", &miscConfig.bunnyHop); ImGui::PushID(0); if (miscConfig.bunnyHop) { ImGui::SliderInt("", &miscConfig.hopsHitchance, 0, 100, "Bunny hop hitchance: %d%"); } ImGui::PopID(); ImGui::Checkbox("Velocity Graph", &miscConfig.velocitygraph); if (miscConfig.velocitygraph) { const ImVec2 dis = ImGui::GetIO().DisplaySize; ImGui::SliderFloat("Graph Y", &miscConfig.VelocityY, 0.0f, dis.y); ImGui::SliderFloat("Graph X", &miscConfig.VelocityX, 0.0f, dis.x); } ImGui::Checkbox("Fast duck", &miscConfig.fastDuck); ImGui::Checkbox("Edge Jump", &miscConfig.edgejump); ImGui::SameLine(); ImGui::PushID("Edge Jump Key"); ImGui::hotkey("", miscConfig.edgejumpkey); ImGui::PopID(); ImGui::Checkbox("Slowwalk", &miscConfig.slowwalk); ImGui::SameLine(); ImGui::PushID("Slowwalk Key"); ImGui::hotkey("", miscConfig.slowwalkKey); ImGui::PopID(); ImGui::Checkbox("Auto accept", &miscConfig.autoAccept); ImGui::Checkbox("Reveal ranks", &miscConfig.revealRanks); ImGui::Checkbox("Reveal suspect", &miscConfig.revealSuspect); ImGui::Checkbox("Reveal votes", &miscConfig.revealVotes); ImGui::NextColumn(); ImGui::Checkbox("Disable HUD blur", &miscConfig.disablePanoramablur); ImGui::Checkbox("Animated clan tag", &miscConfig.animatedClanTag); ImGui::Checkbox("Clock tag", &miscConfig.clocktag); ImGui::Checkbox("Custom clantag", &miscConfig.customClanTag); ImGui::SameLine(); ImGui::PushItemWidth(120.0f); ImGui::PushID(1); if (ImGui::InputText("", miscConfig.clanTag, sizeof(miscConfig.clanTag))) Misc::updateClanTag(true); ImGui::PopID(); ImGui::PushID(3); ImGui::SetNextItemWidth(100.0f); ImGui::Combo("", &miscConfig.banColor, "White\0Red\0Purple\0Green\0Light green\0Turquoise\0Light red\0Gray\0Yellow\0Gray 2\0Light blue\0Gray/Purple\0Blue\0Pink\0Dark orange\0Orange\0"); ImGui::PopID(); ImGui::SameLine(); ImGui::PushID(4); ImGui::InputText("", &miscConfig.banText); ImGui::PopID(); ImGui::SameLine(); if (ImGui::Button("Setup fake ban")) Misc::fakeBan(true); ImGui::SetNextItemWidth(90.0f); ImGui::Checkbox("Preserve Killfeed", &miscConfig.preserveKillfeed.enabled); ImGui::SameLine(); ImGui::PushID("Preserve Killfeed"); if (ImGui::Button("...")) ImGui::OpenPopup(""); if (ImGui::BeginPopup("")) { ImGui::Checkbox("Only Headshots", &miscConfig.preserveKillfeed.onlyHeadshots); ImGui::EndPopup(); } ImGui::PopID(); ImGui::Checkbox("Reportbot", &miscConfig.reportbot.enabled); ImGui::SameLine(); ImGui::PushID("Reportbot"); if (ImGui::Button("...")) ImGui::OpenPopup(""); if (ImGui::BeginPopup("")) { ImGui::PushItemWidth(80.0f); ImGui::Combo("Target", &miscConfig.reportbot.target, "Enemies\0Allies\0All\0"); ImGui::InputInt("Delay (s)", &miscConfig.reportbot.delay); miscConfig.reportbot.delay = (std::max)(miscConfig.reportbot.delay, 1); ImGui::InputInt("Rounds", &miscConfig.reportbot.rounds); miscConfig.reportbot.rounds = (std::max)(miscConfig.reportbot.rounds, 1); ImGui::PopItemWidth(); ImGui::Checkbox("Abusive Communications", &miscConfig.reportbot.textAbuse); ImGui::Checkbox("Griefing", &miscConfig.reportbot.griefing); ImGui::Checkbox("Wall Hacking", &miscConfig.reportbot.wallhack); ImGui::Checkbox("Aim Hacking", &miscConfig.reportbot.aimbot); ImGui::Checkbox("Other Hacking", &miscConfig.reportbot.other); if (ImGui::Button("Reset")) Misc::resetReportbot(); ImGui::EndPopup(); } ImGui::PopID(); ImGui::Checkbox("Inverse ragdoll gravity", &miscConfig.inverseRagdollGravity); ImGui::Combo("Skybox", &miscConfig.skybox, Misc::skyboxList.data(), Misc::skyboxList.size()); if (miscConfig.skybox == 26) { ImGui::InputText("Skybox filename", &miscConfig.customSkybox); if (ImGui::IsItemHovered()) ImGui::SetTooltip("skybox files must be put in csgo/materials/skybox/ directory"); } ImGui::Checkbox("Bypass sv pure", &miscConfig.bypassSvPure); ImGui::Checkbox("Rainbow crosshair", &miscConfig.rainbowCrosshair); ImGui::SameLine(); ImGui::PushItemWidth(100.0f); miscConfig.rainbowCrosshairSpeed = std::clamp(miscConfig.rainbowCrosshairSpeed, 0.0f, 25.0f); ImGui::InputFloat("Speed", &miscConfig.rainbowCrosshairSpeed, 0.1f, 0.15f, "%.2f"); ImGui::PopItemWidth(); ImGui::Checkbox("Rainbow HUD", &miscConfig.rainbowHud); if (ImGui::Button("Unhook")) hooks->uninstall(); ImGui::Columns(1); if (!contentOnly) ImGui::End(); } static void from_json(const json& j, ImVec2& v) { read(j, "X", v.x); read(j, "Y", v.y); } static void from_json(const json& j, PreserveKillfeed& o) { read(j, "Enabled", o.enabled); read(j, "Only Headshots", o.onlyHeadshots); } static void from_json(const json& j, MiscConfig& m) { read(j, "Menu key", m.menuKey); read(j, "Anti AFK kick", m.antiAfkKick); read(j, "Bunny hop", m.bunnyHop); read(j, "Custom clan tag", m.customClanTag); read(j, "Clock tag", m.clocktag); read(j, "Clan tag", m.clanTag, sizeof(m.clanTag)); read(j, "Animated clan tag", m.animatedClanTag); read(j, "Fast duck", m.fastDuck); read(j, "Edge Jump", m.edgejump); read(j, "Edge Jump Key", m.edgejumpkey); read(j, "Slowwalk", m.slowwalk); read(j, "Slowwalk key", m.slowwalkKey); read(j, "Auto accept", m.autoAccept); read(j, "Reveal ranks", m.revealRanks); read(j, "Reveal suspect", m.revealSuspect); read(j, "Reveal votes", m.revealVotes); read(j, "Disable HUD blur", m.disablePanoramablur); read(j, "Ban color", m.banColor); read<value_t::string>(j, "Ban text", m.banText); read<value_t::object>(j, "Reportbot", m.reportbot); read<value_t::object>(j, "Preserve Killfeed", m.preserveKillfeed); read(j, "Skybox", m.skybox); read(j, "Inverse ragdoll gravity", m.inverseRagdollGravity); read<value_t::object>(j, "Custom skybox", m.customSkybox); read(j, "Bunny hop hitchance", m.hopsHitchance); read(j, "Rainbow crosshair", m.rainbowCrosshair); read(j, "Rainbow crosshair speed", m.rainbowCrosshairSpeed); read(j, "Rainbow HUD", m.rainbowHud); read(j, "Bypass sv pure", m.bypassSvPure); read(j, "Velocity Graph", m.velocitygraph); read(j, "Velocity X", m.VelocityX); read(j, "Velocity Y", m.VelocityY); } static void from_json(const json& j, MiscConfig::Reportbot& r) { read(j, "Enabled", r.enabled); read(j, "Target", r.target); read(j, "Delay", r.delay); read(j, "Rounds", r.rounds); read(j, "Abusive Communications", r.textAbuse); read(j, "Griefing", r.griefing); read(j, "Wall Hacking", r.wallhack); read(j, "Aim Hacking", r.aimbot); read(j, "Other Hacking", r.other); } static void to_json(json& j, const MiscConfig::Reportbot& o, const MiscConfig::Reportbot& dummy = {}) { WRITE("Enabled", enabled); WRITE("Target", target); WRITE("Delay", delay); WRITE("Rounds", rounds); WRITE("Abusive Communications", textAbuse); WRITE("Griefing", griefing); WRITE("Wall Hacking", wallhack); WRITE("Aim Hacking", aimbot); WRITE("Other Hacking", other); } static void to_json(json& j, const ImVec2& o, const ImVec2& dummy = {}) { WRITE("X", x); WRITE("Y", y); } static void to_json(json& j, const PreserveKillfeed& o, const PreserveKillfeed& dummy = {}) { WRITE("Enabled", enabled); WRITE("Only Headshots", onlyHeadshots); } static void to_json(json& j, const MiscConfig& o) { const MiscConfig dummy; WRITE("Menu key", menuKey); WRITE("Anti AFK kick", antiAfkKick); WRITE("Bunny hop", bunnyHop); WRITE("Custom clan tag", customClanTag); WRITE("Clock tag", clocktag); if (o.clanTag[0]) j["Clan tag"] = o.clanTag; WRITE("Animated clan tag", animatedClanTag); WRITE("Fast duck", fastDuck); WRITE("Edge Jump", edgejump); WRITE("Edge Jump Key", edgejumpkey); WRITE("Slowwalk", slowwalk); WRITE("Slowwalk key", slowwalkKey); WRITE("Auto accept", autoAccept); WRITE("Reveal ranks", revealRanks); WRITE("Reveal suspect", revealSuspect); WRITE("Reveal votes", revealVotes); WRITE("Disable HUD blur", disablePanoramablur); WRITE("Ban color", banColor); WRITE("Ban text", banText); WRITE("Bypass sv pure", bypassSvPure); WRITE("Reportbot", reportbot); WRITE("Preserve Killfeed", preserveKillfeed); WRITE("Skybox", skybox); WRITE("Inverse ragdoll gravity", inverseRagdollGravity); WRITE("Custom skybox", customSkybox); WRITE("Bunny hop hitchance", hopsHitchance); WRITE("Rainbow crosshair", rainbowCrosshair); WRITE("Rainbow crosshair speed", rainbowCrosshairSpeed); WRITE("Rainbow HUD", rainbowHud); WRITE("Velocity Graph", velocitygraph); WRITE("Velocity X", VelocityX); WRITE("Velocity Y", VelocityY); } json Misc::toJson() noexcept { json j; to_json(j, miscConfig); return j; } void Misc::fromJson(const json& j) noexcept { from_json(j, miscConfig); } void Misc::resetConfig() noexcept { miscConfig = {}; }
31.350769
219
0.644617
[ "object", "vector" ]
8dca62bda3e2d18cd0198cf7cde4c0c637fb691e
964
hpp
C++
Source/WinSandbox/Physics/Collision/CollisionDetector.hpp
wradley/Freight
91eda2ca0af64036202309f6adbf2d80c406e031
[ "MIT" ]
null
null
null
Source/WinSandbox/Physics/Collision/CollisionDetector.hpp
wradley/Freight
91eda2ca0af64036202309f6adbf2d80c406e031
[ "MIT" ]
null
null
null
Source/WinSandbox/Physics/Collision/CollisionDetector.hpp
wradley/Freight
91eda2ca0af64036202309f6adbf2d80c406e031
[ "MIT" ]
null
null
null
#pragma once #include <Freight/pch.hpp> #include "Collider.hpp" #include "Contact.hpp" class CollisionDetector { public: static void Detect(const Collider *a, const Collider *b, std::vector<Contact> &contacts); static void SphereSomething(const SphereCollider *s, const Collider *c, std::vector<Contact> &contacts); static void BoxSomething(const BoxCollider *b, const Collider *c, std::vector<Contact> &contacts); static void SphereSphere(const SphereCollider &a, const SphereCollider &b, std::vector<Contact> &contacts); static void SphereHalfSpace(const SphereCollider &s, const HalfSpace &p, std::vector<Contact> &contacts); static void SphereBox(const SphereCollider &s, const BoxCollider &b, std::vector<Contact> &contacts); static void BoxHalfSpace(const BoxCollider &b, const HalfSpace &h, std::vector<Contact> &contacts); static void BoxBox(const BoxCollider &b, const BoxCollider &h, std::vector<Contact> &contacts); };
50.736842
111
0.75
[ "vector" ]
8dcb6ca22adcb6bb833975e4248ff0ba42a727ab
593
cpp
C++
LeetCode/74.Search_a_2D_Matrix.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
9
2017-10-08T16:22:03.000Z
2021-08-20T09:32:17.000Z
LeetCode/74.Search_a_2D_Matrix.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
null
null
null
LeetCode/74.Search_a_2D_Matrix.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
2
2018-01-15T16:35:44.000Z
2019-03-21T18:30:04.000Z
// 二分搜 class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty() || matrix[0].empty()) return false; int m = matrix.size(), n = matrix[0].size(); int l = 0, r = m * n - 1, x, y; while(l < r) { int mid = (l + r) >> 1; x = mid % n; y = mid / n; if(target == matrix[y][x]) return true; else if(target > matrix[y][x]) l = mid + 1; else r = mid; } if(matrix[l / n][l % n] == target) return true; return false; } };
28.238095
64
0.44688
[ "vector" ]
8deec08c93559a5419b85ef8dfa54af380c24e17
4,482
cc
C++
WirelessMonitoringModule/gr-radar/lib/ofdm_divide_vcvc_impl.cc
Aekai/Wi-Mind
a02a2f4cd10fc362e6a17d3c67c2662c90b1a980
[ "0BSD" ]
1
2021-08-14T13:49:51.000Z
2021-08-14T13:49:51.000Z
WirelessMonitoringModule/gr-radar/lib/ofdm_divide_vcvc_impl.cc
Aekai/Wi-Mind
a02a2f4cd10fc362e6a17d3c67c2662c90b1a980
[ "0BSD" ]
null
null
null
WirelessMonitoringModule/gr-radar/lib/ofdm_divide_vcvc_impl.cc
Aekai/Wi-Mind
a02a2f4cd10fc362e6a17d3c67c2662c90b1a980
[ "0BSD" ]
1
2020-08-18T08:39:58.000Z
2020-08-18T08:39:58.000Z
/* -*- c++ -*- */ /* * Copyright 2014 Communications Engineering Lab, KIT. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This software 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 software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gnuradio/io_signature.h> #include "ofdm_divide_vcvc_impl.h" namespace gr { namespace radar { ofdm_divide_vcvc::sptr ofdm_divide_vcvc::make(int vlen_in, int vlen_out, std::vector<int> discarded_carriers, int num_sync_words, std::string len_key) { return gnuradio::get_initial_sptr (new ofdm_divide_vcvc_impl(vlen_in, vlen_out, discarded_carriers, num_sync_words, len_key)); } /* * The private constructor */ ofdm_divide_vcvc_impl::ofdm_divide_vcvc_impl(int vlen_in, int vlen_out, std::vector<int> discarded_carriers, int num_sync_words, std::string len_key) : gr::tagged_stream_block("ofdm_divide_vcvc", gr::io_signature::make(2, 2, sizeof(gr_complex)*vlen_in), gr::io_signature::make(1, 1, sizeof(gr_complex)*vlen_out), len_key) { d_vlen_in = vlen_in; d_vlen_out = vlen_out; d_discarded_carriers = discarded_carriers; d_num_sync_words = num_sync_words; // Shift discarded carriers for(int k=0; k<discarded_carriers.size(); k++){ d_discarded_carriers[k] = discarded_carriers[k]+vlen_in/2; } // Error handling if(d_vlen_out<d_vlen_in) throw std::runtime_error("Input vector length is greater than output vector length"); } /* * Our virtual destructor. */ ofdm_divide_vcvc_impl::~ofdm_divide_vcvc_impl() { } int ofdm_divide_vcvc_impl::calculate_output_stream_length(const gr_vector_int &ninput_items) { int noutput_items = ninput_items[0]; return noutput_items ; } int ofdm_divide_vcvc_impl::work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in0 = (const gr_complex *) input_items[0]; const gr_complex *in1 = (const gr_complex *) input_items[1]; gr_complex *out = (gr_complex *) output_items[0]; // Set noutput_items noutput_items = ninput_items[0]; // Set output buffer to zero -> is zeropadding std::memset(out,0,sizeof(gr_complex)*noutput_items*d_vlen_out); // Do division and keep spaces between packets if vlen_out>vlen_in // If actual vector is a sync words (given with num_sync_words) do not apply discarded carriers rule int next_discarded_element = 0; // set first discarded element on first vector item if(d_discarded_carriers.size()==0){ // set first discarded element on first vector item d_discarded_carriers.resize(1); d_discarded_carriers[0] = d_vlen_in; // this disables discarded carriers } // Divide items and discard carriers for(int k=0; k<noutput_items; k++){ for(int l=0; l<d_vlen_in; l++){ if(k<d_num_sync_words){ // if actual vector is a sync word out[k*d_vlen_out+l] = (in0[k*d_vlen_in+l])/(in1[k*d_vlen_in+l]); } else{ // if actual vector is NOT a sync word if(l==d_discarded_carriers[next_discarded_element]){ // if actual element shall be discarded and set to zero out[k*d_vlen_out+l] = 0; if(next_discarded_element<d_discarded_carriers.size()-1) next_discarded_element++; // set next discarded element on next vector item else next_discarded_element=0; // if item is last one jump back to first item in vector } else{ // if actual element shall be divided out[k*d_vlen_out+l] = (in0[k*d_vlen_in+l])/(in1[k*d_vlen_in+l]); } } } } // Tell runtime system how many output items we produced. return noutput_items; } } /* namespace radar */ } /* namespace gr */
35.856
153
0.689647
[ "vector" ]
8df1455911565a866b167da58c265e35cdeabca0
1,460
cc
C++
solutions/kattis/beehives.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/kattis/beehives.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/kattis/beehives.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <bitset> #include <chrono> #include <climits> #include <cmath> #include <cstring> #include <deque> #include <ext/pb_ds/assoc_container.hpp> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> // #include "bits/stdc++.h" using namespace std; #ifdef LOCAL #include "../../_library/cc/debug.h" #define FILE "test" #else #define debug(...) 0 #define FILE "cowjog" #endif int main() { cin.tie(nullptr)->sync_with_stdio(false); if (fopen(FILE ".in", "r")) { freopen(FILE ".in", "r", stdin); freopen(FILE ".out", "w", stdout); } // N is small, so we can check the distance between every pair in O(N^2) time double d; int n; while (cin >> d >> n && (d || n)) { vector<pair<double, double>> hives(n); for (auto& [x, y] : hives) { cin >> x >> y; } vector<bool> sour(n); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { double dx = hives[i].first - hives[j].first; double dy = hives[i].second - hives[j].second; if (dx * dx + dy * dy < d * d) { sour[i] = true; sour[j] = true; } } } int sourCnt = accumulate(sour.begin(), sour.end(), 0); cout << sourCnt << " sour, " << n - sourCnt << " sweet\n"; } }
21.791045
79
0.574658
[ "vector" ]
8df651bb8f3aecdf9f4ffe604dec514b28b418f4
4,890
cc
C++
tf_euler/kernels/get_node_type_op.cc
HuangLED/euler
a56b5fe3fe56123af062317ca0b4160ce3b3ace9
[ "Apache-2.0" ]
2,829
2019-01-12T09:16:03.000Z
2022-03-29T14:00:58.000Z
tf_euler/kernels/get_node_type_op.cc
HuangLED/euler
a56b5fe3fe56123af062317ca0b4160ce3b3ace9
[ "Apache-2.0" ]
331
2019-01-17T21:07:49.000Z
2022-03-30T06:38:17.000Z
tf_euler/kernels/get_node_type_op.cc
HuangLED/euler
a56b5fe3fe56123af062317ca0b4160ce3b3ace9
[ "Apache-2.0" ]
578
2019-01-16T10:48:53.000Z
2022-03-21T13:41:34.000Z
/* Copyright 2020 Alibaba Group Holding Limited. 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 <string.h> #include <memory> #include <vector> #include "tensorflow/core/framework/op.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/framework/op_kernel.h" #include "tf_euler/utils/euler_query_proxy.h" namespace tensorflow { class GetNodeType : public AsyncOpKernel { public: explicit GetNodeType(OpKernelConstruction* ctx): AsyncOpKernel(ctx) { } void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override; }; void GetNodeType::ComputeAsync(OpKernelContext* ctx, DoneCallback done) { auto nodes = ctx->input(0); auto nodes_data = nodes.flat<int64>().data(); size_t nodes_size = nodes.flat<int64>().size(); TensorShape output_shape; output_shape.AddDim(nodes_size); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output)); auto query = new euler::Query("v(nodes).label().as(l)"); auto t_nodes = query->AllocInput("nodes", {nodes_size}, euler::kUInt64); std::copy(nodes_data, nodes_data + nodes_size, t_nodes->Raw<int64_t>()); auto callback = [query, output, done] () { auto data = output->flat<int32>().data(); auto res = query->GetResult("l:0"); auto res_data = res->Raw<int32_t>(); std::copy(res_data, res_data + res->NumElements(), data); delete query; done(); }; euler::QueryProxy::GetInstance()->RunAsyncGremlin(query, callback); } REGISTER_KERNEL_BUILDER(Name("GetNodeType").Device(DEVICE_CPU), GetNodeType); class GetNodeTypeId : public OpKernel { public: explicit GetNodeTypeId(OpKernelConstruction* ctx): OpKernel(ctx) { } void Compute(OpKernelContext* ctx) override { auto type_names = ctx->input(0); auto data = type_names.flat<std::string>(); const auto& node_type_map = euler::QueryProxy::GetInstance()->graph_meta().node_type_map(); if (data(0) != "-1") { Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, type_names.shape(), &output)); auto output_data = output->flat<int32>().data(); for (int i = 0; i < data.size(); ++i) { auto it = node_type_map.find(data(i)); OP_REQUIRES(ctx, (it != node_type_map.end()), errors::InvalidArgument( "Invalid node type name: ", data(i))); output_data[i] = it->second; } } else { TensorShape output_shape; output_shape.AddDim(node_type_map.size()); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output)); auto output_data = output->flat<int32>().data(); size_t idx = 0; for (auto it = node_type_map.begin(); it != node_type_map.end(); ++it) { output_data[idx++] = it->second; } } } }; REGISTER_KERNEL_BUILDER( Name("GetNodeTypeId").Device(DEVICE_CPU), GetNodeTypeId); class GetEdgeTypeId : public OpKernel { public: explicit GetEdgeTypeId(OpKernelConstruction* ctx): OpKernel(ctx) { } void Compute(OpKernelContext* ctx) override { auto type_names = ctx->input(0); auto data = type_names.flat<std::string>(); const auto& edge_type_map = euler::QueryProxy::GetInstance()->graph_meta().edge_type_map(); if (data(0) != "-1") { Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, type_names.shape(), &output)); auto output_data = output->flat<int32>().data(); for (int i = 0; i < data.size(); ++i) { auto it = edge_type_map.find(data(i)); OP_REQUIRES(ctx, (it != edge_type_map.end()), errors::InvalidArgument( "Invalid edge type name: ", data(i))); output_data[i] = it->second; } } else { TensorShape output_shape; output_shape.AddDim(edge_type_map.size()); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output)); auto output_data = output->flat<int32>().data(); size_t idx = 0; for (auto it = edge_type_map.begin(); it != edge_type_map.end(); ++it) { output_data[idx++] = it->second; } } } }; REGISTER_KERNEL_BUILDER( Name("GetEdgeTypeId").Device(DEVICE_CPU), GetEdgeTypeId); } // namespace tensorflow
34.680851
80
0.656033
[ "shape", "vector" ]
5c082408e8d28dc9d7f3221f49ff1f34a79c605b
15,514
cpp
C++
src/fplll/fplll/svpcvp.cpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
src/fplll/fplll/svpcvp.cpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
src/fplll/fplll/svpcvp.cpp
Hyper5phere/sphere-decoder
f84cbcb47314547150639bbed017e8e540d32ced
[ "Unlicense" ]
null
null
null
/* Copyright (C) 2008-2011 Xavier Pujol. (C) 2015 Michael Walter. This file is part of fplll. fplll 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. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ #include "svpcvp.h" #include "enum/enumerate.h" #include "enum/topenum.h" FPLLL_BEGIN_NAMESPACE /* Shortest vector problem ======================= */ /* Returns i such that the shortest vector of L(b) belongs to L(b_0,...,b_(i-1)), assuming that the error on rdiag's is less than 100%. If b is LLL-reduced, then for any reasonnable dimension, max(rdiag[0],...,rdiag[i-1]) / min(rdiag[0],...,rdiag[i-1]) is much smaller than numeric_limits<double>::max */ static int last_useful_index(const Matrix<FP_NR<mpfr_t>> &r) { int i; FP_NR<mpfr_t> rdiag_min_value; rdiag_min_value.mul_2si(r(0, 0), 1); for (i = r.get_rows() - 1; i > 0; i--) { if (r(i, i) <= rdiag_min_value) break; } return i + 1; } /* Finds the shortest vector of the basis b and returns its squared norm in basisMin */ static void get_basis_min(Z_NR<mpz_t> &basis_min, const ZZ_mat<mpz_t> &b, int first, int last) { Z_NR<mpz_t> sq_norm; int n = b.get_cols(); sqr_norm(basis_min, b[first], n); for (int i = first + 1; i < last; i++) { sqr_norm(sq_norm, b[i], n); if (sq_norm < basis_min) basis_min = sq_norm; } } static bool enumerate_svp(int d, MatGSO<Z_NR<mpz_t>, FP_NR<mpfr_t>> &gso, FP_NR<mpfr_t> &max_dist, ErrorBoundedEvaluator &evaluator, const vector<enumf> &pruning, int flags) { Enumeration<Z_NR<mpz_t>, FP_NR<mpfr_t>> enumobj(gso, evaluator); bool dual = (flags & SVP_DUAL); if (d == 1 || !pruning.empty() || dual) { enumobj.enumerate(0, d, max_dist, 0, vector<FP_NR<mpfr_t>>(), vector<enumxt>(), pruning, dual); } else { Enumerator enumerator(d, gso.get_mu_matrix(), gso.get_r_matrix()); FP_NR<mpfr_t> bestdist = -1; while (enumerator.enum_next(max_dist)) { if (flags & SVP_VERBOSE) { cerr << enumerator.get_sub_tree(); if (evaluator.eval_mode != EVALMODE_SV) cerr << " (count=2*" << evaluator.size() << ")"; } /* Enumerates short vectors only in enumerator.get_sub_tree() (about maxVolume iterations or less) */ enumobj.enumerate(0, d, max_dist, 0, vector<FP_NR<mpfr_t>>(), enumerator.get_sub_tree(), pruning); if (flags & SVP_VERBOSE) { cerr << "\r" << (char)27 << "[K"; if (evaluator.eval_mode == EVALMODE_SV && !evaluator.empty() && evaluator.begin()->first != bestdist) { bestdist = evaluator.begin()->first; cerr << "Solution norm^2=" << bestdist << " value=" << evaluator.begin()->second << endl; } } } } return !evaluator.empty(); } static int shortest_vector_ex(ZZ_mat<mpz_t> &b, vector<Z_NR<mpz_t>> &sol_coord, SVPMethod method, const vector<double> &pruning, int flags, EvaluatorMode eval_mode, long long &sol_count, vector<vector<Z_NR<mpz_t>>> *subsol_coord = nullptr, vector<enumf> *subsol_dist = nullptr, vector<vector<Z_NR<mpz_t>>> *auxsol_coord = nullptr, vector<enumf> *auxsol_dist = nullptr, int max_aux_sols = 0) { bool findsubsols = (subsol_coord != nullptr) && (subsol_dist != nullptr); bool findauxsols = (auxsol_coord != nullptr) && (auxsol_dist != nullptr) && (max_aux_sols != 0); // d = lattice dimension (note that it might decrease during preprocessing) int d = b.get_rows(); // n = dimension of the space int n = b.get_cols(); FPLLL_CHECK(d > 0 && n > 0, "shortestVector: empty matrix"); FPLLL_CHECK(d <= n, "shortestVector: number of vectors > size of the vectors"); // Sets the floating-point precision // Error bounds on GSO are valid if prec >= minprec double rho; int min_prec = gso_min_prec(rho, d, LLL_DEF_DELTA, LLL_DEF_ETA); int prec = max(53, min_prec + 10); int old_prec = FP_NR<mpfr_t>::set_prec(prec); // Allocates space for vectors and matrices in constructors ZZ_mat<mpz_t> empty_mat; MatGSO<Z_NR<mpz_t>, FP_NR<mpfr_t>> gso(b, empty_mat, empty_mat, GSO_INT_GRAM); FP_NR<mpfr_t> max_dist; Z_NR<mpz_t> int_max_dist; Z_NR<mpz_t> itmp1; // Computes the Gram-Schmidt orthogonalization in floating-point gso.update_gso(); gen_zero_vect(sol_coord, d); // If the last b_i* are too large, removes them to avoid an underflow int new_d = last_useful_index(gso.get_r_matrix()); if (new_d < d) { // FPLLL_TRACE("Ignoring the last " << d - new_d << " vector(s)"); d = new_d; } if (flags & SVP_DUAL) { max_dist = 1.0 / gso.get_r_exp(d - 1, d - 1); if (flags & SVP_VERBOSE) { cout << "max_dist = " << max_dist << endl; } } else { /* Computes a bound for the enumeration. This bound would work for an exact algorithm, but we will increase it later to ensure that the fp algorithm finds a solution */ get_basis_min(int_max_dist, b, 0, d); max_dist.set_z(int_max_dist, GMP_RNDU); } // Initializes the evaluator of solutions ErrorBoundedEvaluator *evaluator; if (method == SVPM_FAST) { evaluator = new FastErrorBoundedEvaluator(d, gso.get_mu_matrix(), gso.get_r_matrix(), eval_mode, max_aux_sols + 1, EVALSTRATEGY_BEST_N_SOLUTIONS, findsubsols); } else if (method == SVPM_PROVED) { ExactErrorBoundedEvaluator *p = new ExactErrorBoundedEvaluator( d, b, gso.get_mu_matrix(), gso.get_r_matrix(), eval_mode, max_aux_sols + 1, EVALSTRATEGY_BEST_N_SOLUTIONS, findsubsols); p->int_max_dist = int_max_dist; evaluator = p; } else { FPLLL_ABORT("shortestVector: invalid evaluator type"); } evaluator->init_delta_def(prec, rho, true); if (!(flags & SVP_OVERRIDE_BND) && (eval_mode == EVALMODE_SV || method == SVPM_PROVED)) { FP_NR<mpfr_t> ftmp1; bool result = evaluator->get_max_error_aux(max_dist, true, ftmp1); FPLLL_CHECK(result, "shortestVector: cannot compute an initial bound"); max_dist.add(max_dist, ftmp1, GMP_RNDU); } // Main loop of the enumeration enumerate_svp(d, gso, max_dist, *evaluator, pruning, flags); int result = RED_ENUM_FAILURE; if (eval_mode != EVALMODE_SV) { result = RED_SUCCESS; sol_count = evaluator->sol_count * 2; } else if (!evaluator->empty()) { /*FP_NR<mpfr_t> fMaxError; validMaxError = evaluator->get_max_error(fMaxError); max_error = fMaxError.get_d(GMP_RNDU);*/ for (int i = 0; i < d; i++) { itmp1.set_f(evaluator->begin()->second[i]); sol_coord[i].add(sol_coord[i], itmp1); } result = RED_SUCCESS; } if (findsubsols) { subsol_coord->clear(); subsol_dist->clear(); subsol_dist->resize(evaluator->sub_solutions.size()); for (size_t i = 0; i < evaluator->sub_solutions.size(); ++i) { (*subsol_dist)[i] = evaluator->sub_solutions[i].first.get_d(); vector<Z_NR<mpz_t>> ss_c; for (size_t j = 0; j < evaluator->sub_solutions[i].second.size(); ++j) { itmp1.set_f(evaluator->sub_solutions[i].second[j]); ss_c.emplace_back(itmp1); } subsol_coord->emplace_back(std::move(ss_c)); } } if (findauxsols) { auxsol_coord->clear(); auxsol_dist->clear(); // iterators over all solutions auto it = evaluator->begin(), itend = evaluator->end(); // skip shortest solution ++it; for (; it != itend; ++it) { auxsol_dist->push_back(it->first.get_d()); vector<Z_NR<mpz_t>> as_c; for (size_t j = 0; j < it->second.size(); ++j) { itmp1.set_f(it->second[j]); as_c.emplace_back(itmp1); } auxsol_coord->emplace_back(std::move(as_c)); } } delete evaluator; FP_NR<mpfr_t>::set_prec(old_prec); return result; } int shortest_vector(ZZ_mat<mpz_t> &b, vector<Z_NR<mpz_t>> &sol_coord, SVPMethod method, int flags) { long long tmp; return shortest_vector_ex(b, sol_coord, method, vector<double>(), flags, EVALMODE_SV, tmp); } int shortest_vector_pruning(ZZ_mat<mpz_t> &b, vector<Z_NR<mpz_t>> &sol_coord, const vector<double> &pruning, int flags) { long long tmp; return shortest_vector_ex(b, sol_coord, SVPM_FAST, pruning, flags, EVALMODE_SV, tmp); } int shortest_vector_pruning(ZZ_mat<mpz_t> &b, vector<Z_NR<mpz_t>> &sol_coord, vector<vector<Z_NR<mpz_t>>> &subsol_coord, vector<enumf> &subsol_dist, const vector<double> &pruning, int flags) { long long tmp; return shortest_vector_ex(b, sol_coord, SVPM_FAST, pruning, flags, EVALMODE_SV, tmp, &subsol_coord, &subsol_dist); } int shortest_vector_pruning(ZZ_mat<mpz_t> &b, vector<Z_NR<mpz_t>> &sol_coord, vector<vector<Z_NR<mpz_t>>> &auxsol_coord, vector<enumf> &auxsol_dist, const int max_aux_sols, const vector<double> &pruning, int flags) { long long tmp; return shortest_vector_ex(b, sol_coord, SVPM_FAST, pruning, flags, EVALMODE_SV, tmp, nullptr, nullptr, &auxsol_coord, &auxsol_dist, max_aux_sols); } /* Closest vector problem ====================== */ static void get_gscoords(const Matrix<FP_NR<mpfr_t>> &matrix, const Matrix<FP_NR<mpfr_t>> &mu, const Matrix<FP_NR<mpfr_t>> &r, const vector<FP_NR<mpfr_t>> &v, vector<FP_NR<mpfr_t>> &vcoord) { int n = matrix.get_rows(), m = matrix.get_cols(); if (static_cast<int>(vcoord.size()) != n) vcoord.resize(n); FPLLL_DEBUG_CHECK(mu.get_rows() == n && mu.get_cols() == n && r.get_rows() == n && r.get_cols() == n && static_cast<int>(v.size()) == m); for (int i = 0; i < n; i++) { vcoord[i] = 0.0; for (int j = 0; j < m; j++) vcoord[i].addmul(v[j], matrix(i, j)); for (int j = 0; j < i; j++) vcoord[i].submul(mu(i, j), vcoord[j]); } for (int i = 0; i < n; i++) { vcoord[i].div(vcoord[i], r(i, i)); } } static void babai(const FP_mat<mpfr_t> &matrix, const Matrix<FP_NR<mpfr_t>> &mu, const Matrix<FP_NR<mpfr_t>> &r, const vector<FP_NR<mpfr_t>> &target, vector<FP_NR<mpfr_t>> &target_coord) { int d = matrix.get_rows(); get_gscoords(matrix, mu, r, target, target_coord); for (int i = d - 1; i >= 0; i--) { target_coord[i].rnd(target_coord[i]); for (int j = 0; j < i; j++) target_coord[j].submul(mu(i, j), target_coord[i]); } } int closest_vector(ZZ_mat<mpz_t> &b, const vector<Z_NR<mpz_t>> &int_target, vector<Z_NR<mpz_t>> &sol_coord, int method, int flags) { // d = lattice dimension (note that it might decrease during preprocessing) int d = b.get_rows(); // n = dimension of the space int n = b.get_cols(); FPLLL_CHECK(d > 0 && n > 0, "closestVector: empty matrix"); FPLLL_CHECK(d <= n, "closestVector: number of vectors > size of the vectors"); // Sets the floating-point precision // Error bounds on GSO are valid if prec >= minprec double rho; int min_prec = gso_min_prec(rho, d, LLL_DEF_DELTA, LLL_DEF_ETA); int prec = max(53, min_prec + 10); int old_prec = FP_NR<mpfr_t>::set_prec(prec); // Allocates space for vectors and matrices in constructors ZZ_mat<mpz_t> empty_mat; MatGSO<Z_NR<mpz_t>, FP_NR<mpfr_t>> gso(b, empty_mat, empty_mat, GSO_INT_GRAM); vector<FP_NR<mpfr_t>> target_coord; FP_NR<mpfr_t> max_dist; Z_NR<mpz_t> itmp1; // Computes the Gram-Schmidt orthogonalization in floating-point gso.update_gso(); gen_zero_vect(sol_coord, d); /* Applies Babai's algorithm. Because we use fp, it might be necessary to do it several times (if ||target|| >> ||b_i||) */ FP_mat<mpfr_t> float_matrix(d, n); vector<FP_NR<mpfr_t>> target(n), babai_sol; vector<Z_NR<mpz_t>> int_new_target = int_target; for (int i = 0; i < d; i++) for (int j = 0; j < n; j++) float_matrix(i, j).set_z(b(i, j)); for (int loop_idx = 0;; loop_idx++) { if (loop_idx >= 0x100 && ((loop_idx & (loop_idx - 1)) == 0)) FPLLL_INFO("warning: possible infinite loop in Babai's algorithm"); for (int i = 0; i < n; i++) { target[i].set_z(int_new_target[i]); } babai(float_matrix, gso.get_mu_matrix(), gso.get_r_matrix(), target, babai_sol); int idx; for (idx = 0; idx < d && babai_sol[idx] >= -1 && babai_sol[idx] <= 1; idx++) { } if (idx == d) break; for (int i = 0; i < d; i++) { itmp1.set_f(babai_sol[i]); sol_coord[i].add(sol_coord[i], itmp1); for (int j = 0; j < n; j++) int_new_target[j].submul(itmp1, b(i, j)); } } // FPLLL_TRACE("BabaiSol=" << sol_coord); get_gscoords(float_matrix, gso.get_mu_matrix(), gso.get_r_matrix(), target, target_coord); /* Computes a very large bound to make the algorithm work until the first solution is found */ max_dist = 0.0; for (int i = 1; i < d; i++) { // get_r_exp(i, i) = r(i, i) because gso is initialized without GSO_ROW_EXPO max_dist.add(max_dist, gso.get_r_exp(i, i)); } vector<int> max_indices; if (method & CVPM_PROVED) { // For Exact CVP, we need to reset enum below depth with maximal r_i max_indices = vector<int>(d); int cur, max_index, previous_max_index; previous_max_index = max_index = d - 1; FP_NR<mpfr_t> max_val; while (max_index > 0) { max_val = gso.get_r_exp(max_index, max_index); for (cur = previous_max_index - 1; cur >= 0; --cur) { if (max_val <= gso.get_r_exp(cur, cur)) { max_val = gso.get_r_exp(cur, cur); max_index = cur; } } for (cur = max_index; cur < previous_max_index; ++cur) max_indices[cur] = max_index; max_indices[previous_max_index] = previous_max_index; previous_max_index = max_index; --max_index; } } FPLLL_TRACE("max_indices " << max_indices); FastErrorBoundedEvaluator evaluator(n, gso.get_mu_matrix(), gso.get_r_matrix(), EVALMODE_CV); // Main loop of the enumeration Enumeration<Z_NR<mpz_t>, FP_NR<mpfr_t>> enumobj(gso, evaluator, max_indices); enumobj.enumerate(0, d, max_dist, 0, target_coord); int result = RED_ENUM_FAILURE; if (!evaluator.empty()) { FPLLL_TRACE("evaluator.bestsol_coord=" << evaluator.begin()->second); if (flags & CVP_VERBOSE) FPLLL_INFO("max_dist=" << max_dist); for (int i = 0; i < d; i++) { itmp1.set_f(evaluator.begin()->second[i]); sol_coord[i].add(sol_coord[i], itmp1); } result = RED_SUCCESS; } FP_NR<mpfr_t>::set_prec(old_prec); return result; } FPLLL_END_NAMESPACE
33.363441
100
0.622406
[ "vector" ]
5c09f925c33092d782b28bec4a10efaffbc0f825
4,289
hpp
C++
src/core/pipelines.hpp
sunnyygou/CS184_Final_Project
e853d758da7aae2011a39034bb78795659baf116
[ "MIT" ]
1
2021-04-17T21:42:12.000Z
2021-04-17T21:42:12.000Z
src/core/pipelines.hpp
sunnyygou/CS184_Final_Project
e853d758da7aae2011a39034bb78795659baf116
[ "MIT" ]
null
null
null
src/core/pipelines.hpp
sunnyygou/CS184_Final_Project
e853d758da7aae2011a39034bb78795659baf116
[ "MIT" ]
1
2021-04-27T06:06:58.000Z
2021-04-27T06:06:58.000Z
#pragma once #include "berkeley_gfx.hpp" #include <vulkan/vulkan.hpp> namespace BG { static bool glslangInitialized = false; class Pipeline { private: vk::UniqueShaderModule AddShaders(std::string shaders, int shaderType); vk::Device m_device; Renderer& r; vk::Viewport m_viewport; vk::Rect2D m_scissor; vk::PipelineVertexInputStateCreateInfo m_vertexInputInfo; vk::PipelineInputAssemblyStateCreateInfo m_inputAssemblyInfo; vk::PipelineViewportStateCreateInfo m_viewportInfo; vk::PipelineRasterizationStateCreateInfo m_rasterizer; vk::PipelineMultisampleStateCreateInfo m_multisampling; std::vector<vk::UniqueShaderModule> m_shaderModules; std::vector<vk::PipelineShaderStageCreateInfo> m_stageCreateInfos; std::vector<vk::AttachmentDescription> m_attachments; vk::AttachmentDescription m_depthAttachment; bool m_useDepthAttachment = false; vk::UniqueDescriptorSetLayout m_descriptorSetLayout; vk::UniquePipelineLayout m_layout; vk::UniqueRenderPass m_renderpass; vk::UniquePipeline m_pipeline; bool m_created = false; std::vector<vk::VertexInputBindingDescription> m_bindingDescriptions; std::vector<vk::VertexInputAttributeDescription> m_attributeDescriptions; std::vector<vk::DescriptorSetLayoutBinding> m_descSetLayoutBindings; std::vector<vk::DescriptorBindingFlags> m_descSetLayoutBindingFlags; std::vector<vk::PushConstantRange> m_pushConstants; std::vector<uint32_t> BuildProgramFromSrc(std::string shaders, int shaderType); std::unordered_map<std::string, uint32_t> m_name2bindings; std::unordered_map<std::string, uint32_t> m_memberOffsets; std::unordered_map<std::string, uint32_t> m_uniformBlockSize; public: void AddFragmentShaders(std::string shaders); void AddVertexShaders(std::string shaders); template <class T> VertexBufferBinding AddVertexBuffer(bool perVertex = true) { vk::VertexInputBindingDescription desc; desc.setStride(sizeof(T)); desc.setInputRate(perVertex ? vk::VertexInputRate::eVertex : vk::VertexInputRate::eInstance); int binding = int(m_bindingDescriptions.size()); desc.setBinding(binding); m_bindingDescriptions.push_back(desc); return VertexBufferBinding{ binding }; } void AddAttribute(VertexBufferBinding binding, int location, vk::Format format, size_t offset); int GetBindingByName(std::string name); uint32_t GetMemberOffset(std::string name); void AddDescriptorUniform(int binding, vk::ShaderStageFlags stage, int count = 1, bool unbound = false); void AddDescriptorTexture(int binding, vk::ShaderStageFlags stage, int count = 1, bool unbound = false); void AddPushConstant(uint32_t offset, uint32_t size, vk::ShaderStageFlags stage); void SetViewport(float width, float height, float x = 0.0, float y = 0.0, float minDepth = 0.0f, float maxDepth = 1.0f); void SetScissor(int x, int y, int width, int height); void AddAttachment(vk::Format format, vk::ImageLayout initialLayout, vk::ImageLayout finalLayout, vk::SampleCountFlagBits samples = vk::SampleCountFlagBits::e1); void AddDepthAttachment(vk::ImageLayout initialLayout = vk::ImageLayout::eUndefined, vk::ImageLayout finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal); void BuildPipeline(); vk::DescriptorSet AllocDescSet(vk::DescriptorPool pool, int variableDescriptorCount = 0); void BindGraphicsUniformBuffer(Pipeline& p, vk::DescriptorSet descSet, const BG::Buffer& buffer, uint32_t offset, uint32_t range, int binding, int arrayElement = 0); void BindGraphicsImageView(Pipeline& p, vk::DescriptorSet descSet, vk::ImageView view, vk::ImageLayout layout, vk::Sampler sampler, int binding, int arrayElement = 0); vk::RenderPass GetRenderPass(); vk::Pipeline GetPipeline(); vk::PipelineLayout GetLayout(); void BindRenderPass( vk::CommandBuffer& buf, vk::Framebuffer& frameBuffer, glm::uvec2 extent, glm::vec4 clearColor = glm::vec4(1.0), glm::ivec2 offset = glm::ivec2(0)); Pipeline(Renderer& r, vk::Device device); static void InitBackend(); }; }
39.348624
171
0.731872
[ "vector" ]
5c0a8a581e3e590f611cf3c96d5466b687a32345
6,753
cpp
C++
FEBioSource2.9/FEBioMech/FEUncoupledElasticMixture.cpp
wzaylor/FEBio_MCLS
f1052733c31196544fb0921aa55ffa5167a25f98
[ "Intel" ]
1
2021-08-24T08:37:21.000Z
2021-08-24T08:37:21.000Z
FEBioSource2.9/FEBioMech/FEUncoupledElasticMixture.cpp
wzaylor/FEBio_MCLS
f1052733c31196544fb0921aa55ffa5167a25f98
[ "Intel" ]
null
null
null
FEBioSource2.9/FEBioMech/FEUncoupledElasticMixture.cpp
wzaylor/FEBio_MCLS
f1052733c31196544fb0921aa55ffa5167a25f98
[ "Intel" ]
1
2021-03-15T08:22:06.000Z
2021-03-15T08:22:06.000Z
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2019 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "stdafx.h" #include "FEUncoupledElasticMixture.h" #include "FECore/FECoreKernel.h" // define the material parameters // BEGIN_PARAMETER_LIST(FEUncoupledElasticMixture, FEUncoupledMaterial) // END_PARAMETER_LIST(); ////////////////////////////////////////////////////////////////////// // Mixture of uncoupled elastic solids ////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- FEUncoupledElasticMixture::FEUncoupledElasticMixture(FEModel* pfem) : FEUncoupledMaterial(pfem) { AddProperty(&m_pMat, "solid"); } //----------------------------------------------------------------------------- FEMaterialPoint* FEUncoupledElasticMixture::CreateMaterialPointData() { FEElasticMixtureMaterialPoint* pt = new FEElasticMixtureMaterialPoint(); int NMAT = Materials(); for (int i=0; i<NMAT; ++i) pt->AddMaterialPoint(m_pMat[i]->CreateMaterialPointData()); return pt; } //----------------------------------------------------------------------------- void FEUncoupledElasticMixture::SetLocalCoordinateSystem(FEElement& el, int n, FEMaterialPoint& mp) { FEElasticMaterial::SetLocalCoordinateSystem(el, n, mp); FEElasticMaterialPoint& pt = *(mp.ExtractData<FEElasticMaterialPoint>()); FEElasticMixtureMaterialPoint& mmp = *(mp.ExtractData<FEElasticMixtureMaterialPoint>()); // check the local coordinate systems for each component for (int j=0; j<Materials(); ++j) { FEElasticMaterial* pmj = GetMaterial(j)->GetElasticMaterial(); FEMaterialPoint& mpj = *mmp.GetPointData(j); FEElasticMaterialPoint& pj = *(mpj.ExtractData<FEElasticMaterialPoint>()); pj.m_Q = pt.m_Q; pmj->SetLocalCoordinateSystem(el, n, mpj); } } //----------------------------------------------------------------------------- bool FEUncoupledElasticMixture::Init() { // NOTE: The calculation of K used to be the sum of all solid K's. // But that doesn't follow the formulation and should be deprecated. // Ideally, this function should be removed, but for backward compatiblity // the old algorithm is retained (for now), only if the parent's K = 0. // Of course, if the user defined K for both the mixture and its components // the behavior will be different. if (m_K == 0.0) { for (int i=0; i < (int)m_pMat.size(); ++i) { m_pMat[i]->Init(); m_K += m_pMat[i]->m_K; // Sum up all the values of the bulk moduli } } return FEUncoupledMaterial::Init(); } //----------------------------------------------------------------------------- void FEUncoupledElasticMixture::AddMaterial(FEUncoupledMaterial* pm) { m_pMat.SetProperty(pm); } //----------------------------------------------------------------------------- mat3ds FEUncoupledElasticMixture::DevStress(FEMaterialPoint& mp) { FEElasticMixtureMaterialPoint& pt = *mp.ExtractData<FEElasticMixtureMaterialPoint>(); vector<double>& w = pt.m_w; assert(w.size() == m_pMat.size()); // get the elastic material point FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>(); // calculate stress mat3ds s; s.zero(); for (int i=0; i < (int)m_pMat.size(); ++i) { // copy the elastic material point data to the components // but don't copy m_Q since correct value was set in SetLocalCoordinateSystem FEElasticMaterialPoint& epi = *pt.GetPointData(i)->ExtractData<FEElasticMaterialPoint>(); epi.m_rt = ep.m_rt; epi.m_r0 = ep.m_r0; epi.m_F = ep.m_F; epi.m_J = ep.m_J; s += epi.m_s = m_pMat[i]->DevStress(*pt.GetPointData(i))*w[i]; } return s; } //----------------------------------------------------------------------------- tens4ds FEUncoupledElasticMixture::DevTangent(FEMaterialPoint& mp) { FEElasticMixtureMaterialPoint& pt = *mp.ExtractData<FEElasticMixtureMaterialPoint>(); vector<double>& w = pt.m_w; assert(w.size() == m_pMat.size()); // get the elastic material point FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>(); // calculate elasticity tensor tens4ds c(0.); for (int i=0; i < (int)m_pMat.size(); ++i) { // copy the elastic material point data to the components // but don't copy m_Q since correct value was set in SetLocalCoordinateSystem FEElasticMaterialPoint& epi = *pt.GetPointData(i)->ExtractData<FEElasticMaterialPoint>(); epi.m_rt = ep.m_rt; epi.m_r0 = ep.m_r0; epi.m_F = ep.m_F; epi.m_J = ep.m_J; c += m_pMat[i]->DevTangent(*pt.GetPointData(i))*w[i]; } return c; } //----------------------------------------------------------------------------- double FEUncoupledElasticMixture::DevStrainEnergyDensity(FEMaterialPoint& mp) { FEElasticMixtureMaterialPoint& pt = *mp.ExtractData<FEElasticMixtureMaterialPoint>(); vector<double>& w = pt.m_w; assert(w.size() == m_pMat.size()); // get the elastic material point FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>(); // calculate strain energy density double sed = 0.0; for (int i=0; i < (int)m_pMat.size(); ++i) { // copy the elastic material point data to the components // but don't copy m_Q since correct value was set in SetLocalCoordinateSystem FEElasticMaterialPoint& epi = *pt.GetPointData(i)->ExtractData<FEElasticMaterialPoint>(); epi.m_rt = ep.m_rt; epi.m_r0 = ep.m_r0; epi.m_F = ep.m_F; epi.m_J = ep.m_J; sed += m_pMat[i]->DevStrainEnergyDensity(*pt.GetPointData(i))*w[i]; } return sed; }
37.104396
99
0.647416
[ "vector", "solid" ]
5c0debb4e27c88b0e8494b9d4353f732bb4eca8d
3,120
cpp
C++
1v1_client/response.cpp
fpeterek/1V1-game-client
41a89a2bb14363ccc9162471ed058d314b7ec13d
[ "Apache-2.0" ]
null
null
null
1v1_client/response.cpp
fpeterek/1V1-game-client
41a89a2bb14363ccc9162471ed058d314b7ec13d
[ "Apache-2.0" ]
null
null
null
1v1_client/response.cpp
fpeterek/1V1-game-client
41a89a2bb14363ccc9162471ed058d314b7ec13d
[ "Apache-2.0" ]
null
null
null
// // response.cpp // 1v1_client // // Created by Filip Peterek on 27/12/2016. // Copyright © 2016 Filip Peterek. All rights reserved. // #include "response.hpp" std::array<std::string, 4> splitResponse(const std::string & response) { std::array<std::string, 4> data; size_t start = 0; size_t end = 0; for (char i = 0; i < 4; ++i) { end = response.find("}", start) + 1; if (end == std::string::npos) { data[i] = "{}"; } data[i] = response.substr(start, end - start); start = end; } return data; } std::vector<std::string> splitString(const std::string & string, const std::string delimiter) { std::vector<std::string> tokens; std::string token; size_t start = 0; size_t end = 0; while ((end = string.find(delimiter, start)) != std::string::npos) { token = string.substr(start, end - start); tokens.emplace_back(token); start = ++end; } tokens.emplace_back(string.substr(start)); return tokens; } entity::entity(std::string & serverData) { serverData.erase(0, 1); serverData.pop_back(); isValid = true; if (serverData == "") { isValid = false; return; } std::vector<std::string> values = splitString(serverData, ","); if (values.size() != 6) { isValid = false; return; } try { pos.x = std::stoi(values[0]); pos.y = std::stoi(values[1]); } catch (std::exception & e) { isValid = false; return; } if (values[2] == "l") { dir = direction::left; } else if (values[2] == "r") { dir = direction::right; } else { isValid = false; return; } try { hp = std::stoi(values[3]); sprite = std::stoi(values[4]); matchesWon = std::stoi(values[5]); } catch (std::exception & e) { isValid = false; } } Response::Response() {} void Response::parseResponse() { _entities = std::map<std::string, entity>(); std::array<std::string, 4> data = splitResponse(_rawResponse); _entities.emplace("p1", entity(data[0])); _entities.emplace("p2", entity(data[1])); _entities.emplace("d1", entity(data[2])); _entities.emplace("d2", entity(data[3])); } const entity & Response::getEntity(const char * entityName) { std::string name = entityName; return _entities.at(name); } const entity & Response::getEntity(std::string & entityName) { return _entities.at(entityName); } Response::Response(const char * serverResponse) { setResponse(serverResponse); } Response::Response(std::string & serverResponse) { setResponse(serverResponse); } void Response::setResponse(std::string & serverResponse) { _rawResponse = serverResponse; parseResponse(); } void Response::setResponse(const char * serverResponse) { _rawResponse = serverResponse; parseResponse(); }
20.526316
95
0.553526
[ "vector" ]
5c18ffd2db9f870873d0040874d96a680758a1a1
1,701
hxx
C++
include/opengm/inference/cgc/generate_starting_point.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
include/opengm/inference/cgc/generate_starting_point.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
include/opengm/inference/cgc/generate_starting_point.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#include <vector> #include <opengm/opengm.hxx> #include <opengm/datastructures/partition.hxx> namespace opengm{ /** * If approxSize > 0, first runs splitBFS to partition nodes into clusters. * * Then, merge neighboring nodes with lambda > threshold. * * The resulting partitioning of the nodes is written into resultArg. */ template<class GM> void startFromThreshold( const GM & gm, std::vector<typename GM::ValueType> & lambdas, std::vector<typename GM::LabelType> & resultArg, const typename GM::ValueType threshold=0.0 ){ typedef typename GM::IndexType IndexType; typedef typename GM::LabelType LabelType; typedef typename GM::ValueType ValueType; resultArg.resize(gm.numberOfVariables()); Partition<IndexType> ufd(gm.numberOfVariables()); for(IndexType fi=0;fi<gm.numberOfFactors();++fi){ OPENGM_CHECK_OP(gm[fi].numberOfVariables(),==,2,""); const IndexType vi0 =gm[fi].variableIndex(0); const IndexType vi1 =gm[fi].variableIndex(1); if(lambdas[fi]>threshold){ ufd.merge(vi0,vi1); } } std::map<IndexType,IndexType> representativeLabeling; ufd.representativeLabeling(representativeLabeling); for(IndexType vi=0;vi<gm.numberOfVariables();++vi){ const IndexType find=ufd.find(vi); const IndexType dense=representativeLabeling[find]; resultArg[vi]=dense; } } } // kate: space-indent on; indent-width 4; replace-tabs on; indent-mode cstyle; remove-trailing-space; replace-trailing-spaces-save;
29.842105
132
0.633157
[ "vector" ]
5c1922894c0954441537c04474a30b04f67652f7
886
cpp
C++
torch/csrc/api/src/nn/options/linear.cpp
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
60,067
2017-01-18T17:21:31.000Z
2022-03-31T21:37:45.000Z
torch/csrc/api/src/nn/options/linear.cpp
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
66,955
2017-01-18T17:21:38.000Z
2022-03-31T23:56:11.000Z
torch/csrc/api/src/nn/options/linear.cpp
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
19,210
2017-01-18T17:45:04.000Z
2022-03-31T23:51:56.000Z
#include <torch/nn/options/linear.h> namespace torch { namespace nn { LinearOptions::LinearOptions(int64_t in_features, int64_t out_features) : in_features_(in_features), out_features_(out_features) {} BilinearOptions::BilinearOptions(int64_t in1_features, int64_t in2_features, int64_t out_features) : in1_features_(in1_features), in2_features_(in2_features), out_features_(out_features) {} UnflattenOptions::UnflattenOptions(int64_t dim, std::vector<int64_t> sizes) : dim_(dim), sizes_(std::move(sizes)) {} UnflattenOptions::UnflattenOptions(const char* dimname, namedshape_t namedshape) : dim_(0), dimname_(std::string(dimname)), namedshape_(std::move(namedshape)) {} UnflattenOptions::UnflattenOptions(std::string dimname, namedshape_t namedshape) : dim_(0), dimname_(std::move(dimname)), namedshape_(std::move(namedshape)) {} } // namespace nn } // namespace torch
38.521739
98
0.77991
[ "vector" ]
5c1c710044c2b3eae56cbe65ec36fd82e2d35646
1,504
cpp
C++
src/gprmc.cpp
kuzen/xw_gps_driver
009e5242b720d3befbcdf2a1dab7986a8a5b5fd3
[ "MIT" ]
7
2021-09-17T00:35:58.000Z
2022-03-21T05:45:27.000Z
src/gprmc.cpp
kuzen/xw_gps_driver
009e5242b720d3befbcdf2a1dab7986a8a5b5fd3
[ "MIT" ]
null
null
null
src/gprmc.cpp
kuzen/xw_gps_driver
009e5242b720d3befbcdf2a1dab7986a8a5b5fd3
[ "MIT" ]
3
2021-10-03T04:28:01.000Z
2022-02-19T13:29:30.000Z
#include "gps_driver/gprmc.h" #include <time.h> #include <string> namespace nmea{ bool Gprmc::decode(const std::vector<std::string>& raw_msg, GprmcData_t& data){ char sign; char ddd, mm; double dddmm; auto toInt = [](std::string s) -> int { return (s.c_str()[0] - '0') * 10 + (s.c_str()[1] - '0'); }; data.status = raw_msg[9].c_str()[0]; // lat sign = raw_msg[4] == "N" ? 1 : -1; dddmm = stod(raw_msg[3]); ddd = int(dddmm / 100); mm = (dddmm - ddd * 100) / 60.0; data.lat = sign * (ddd + mm); // lon sign = raw_msg[6] == "E" ? 1 : -1; dddmm = stod(raw_msg[5]); ddd = int(dddmm / 100); mm = (dddmm - ddd * 100) / 60.0; data.lon = sign * (ddd + mm); // timestamp struct tm t; std::string date = raw_msg[9]; std::string time = raw_msg[1]; t.tm_mday = toInt(date.substr(0, 2)); t.tm_mon = toInt(date.substr(2, 2)); t.tm_year = 100 + toInt(date.substr(4, 2)); t.tm_hour = toInt(time.substr(0, 2)); t.tm_min = toInt(time.substr(2, 2)); t.tm_sec = toInt(time.substr(4, 2)); float ms = (float)(toInt(time.substr(7, 2))) / 100.0; t.tm_isdst = 0; data.timestamp = mktime(&t) + ms; return true; } bool Gprmc::parse(const GprmcData_t& data, sensor_msgs::NavSatFix& msg){ msg.header.stamp = ros::Time(data.timestamp); msg.header.frame_id = this->frameId_; msg.altitude = data.alt; msg.latitude = data.lat; msg.longitude = data.lon; msg.position_covariance = data.position_covariance; msg.position_covariance_type = 0; return true; } }
28.377358
101
0.614362
[ "vector" ]
5c1d8f757c96afb948fa7edc4804ec82a4afdc73
14,011
cpp
C++
lib/caffe-action/src/caffe/layers/video_data_layer.cpp
xiaoye77/Optical-Flow-Guided-Feature
db153fc4c139201d3f73b7ca8be6c80210906ec6
[ "MIT" ]
196
2018-07-07T14:22:37.000Z
2022-03-19T06:21:11.000Z
lib/caffe-action/src/caffe/layers/video_data_layer.cpp
xiaoye77/Optical-Flow-Guided-Feature
db153fc4c139201d3f73b7ca8be6c80210906ec6
[ "MIT" ]
2
2018-07-09T09:19:09.000Z
2018-07-17T15:08:49.000Z
lib/caffe-action/src/caffe/layers/video_data_layer.cpp
ParrtZhang/Optical-Flow-Guided-Feature
07d4501a29002ee7821c38c1820e4a64c1acf6e8
[ "MIT" ]
48
2018-07-10T02:11:20.000Z
2022-02-04T14:26:30.000Z
#include <fstream> #include <iostream> #include <string> #include <utility> #include <vector> #include "caffe/data_layers.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/rng.hpp" #ifdef USE_MPI #include "mpi.h" #include <boost/filesystem.hpp> using namespace boost::filesystem; #endif namespace caffe { template<typename Dtype> VideoDataLayer<Dtype>::~VideoDataLayer<Dtype>() { this->JoinPrefetchThread(); } template<typename Dtype> void VideoDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top) { const int new_height = this->layer_param_.video_data_param().new_height(); const int new_width = this->layer_param_.video_data_param().new_width(); const int new_length = this->layer_param_.video_data_param().new_length(); const int num_segments = this->layer_param_.video_data_param().num_segments(); const string &source = this->layer_param_.video_data_param().source(); LOG(INFO) << "Opening file: " << source; std::ifstream infile(source.c_str()); string filename; int label; int length; while (infile >> filename >> length >> label) { lines_.push_back(std::make_pair(filename, label)); lines_duration_.push_back(length); } if (this->layer_param_.video_data_param().shuffle()) { const unsigned int prefectch_rng_seed = caffe_rng_rand(); prefetch_rng_1_.reset(new Caffe::RNG(prefectch_rng_seed)); prefetch_rng_2_.reset(new Caffe::RNG(prefectch_rng_seed)); ShuffleVideos(); } LOG(INFO) << "A total of " << lines_.size() << " videos."; lines_id_ = 0; //check name patter if (this->layer_param_.video_data_param().name_pattern() == "") { if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_RGB) { name_pattern_ = "image_%04d.jpg"; } else if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_FLOW) { name_pattern_ = "flow_%c_%04d.jpg"; } } else { name_pattern_ = this->layer_param_.video_data_param().name_pattern(); } Datum datum; const unsigned int frame_prefectch_rng_seed = caffe_rng_rand(); frame_prefetch_rng_.reset(new Caffe::RNG(frame_prefectch_rng_seed)); int average_duration = 0; if (this->phase_ == TRAIN) { if (num_segments != 0) average_duration = (int) lines_duration_[lines_id_] / num_segments; // average duration of each segment else LOG(ERROR) << "num_segments is 0"; } else { if (num_segments != 0) average_duration = (int) lines_duration_[lines_id_] / num_segments; // average duration of each segment else LOG(ERROR) << "num_segments is 0"; } vector<int> offsets; if (this->phase_ == TRAIN) { for (int i = 0; i < num_segments; ++i) { caffe::rng_t *frame_rng = static_cast<caffe::rng_t *>(frame_prefetch_rng_->generator()); // randomly select a frame int offset = 0; if (average_duration - new_length + 1 != 0) offset = (*frame_rng)() % (average_duration - new_length + 1); // ensure the frame is at the begining of a segment else LOG(ERROR) << "average_duration - new_length + 1 = 0!"; offsets.push_back(offset + i * average_duration); } } else { for (int i = 0; i < num_segments; ++i) { if (average_duration >= new_length) offsets.push_back(int((average_duration - new_length + 1) / 2 + i * average_duration)); else offsets.push_back(0); } } bool roi_pool_flag = this->layer_param_.video_data_param().roi_pool_flag(); if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_FLOW) CHECK(ReadSegmentFlowToDatum(lines_[lines_id_].first, lines_[lines_id_].second, offsets, new_height, new_width, new_length, &datum, name_pattern_.c_str())); else if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_RGB) CHECK(ReadSegmentRGBToDatum(lines_[lines_id_].first, lines_[lines_id_].second, offsets, new_height, new_width, new_length, &datum, true, name_pattern_.c_str())); else if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_RGB_FLOW) { CHECK(ReadSegmentRGBFlowToDatum(lines_[lines_id_].first, lines_[lines_id_].second, offsets, new_height, new_width, new_length, &datum, true, name_pattern_.c_str())); } else if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_RGB_POSE) { if (this->layer_param_.video_data_param().has_img_list_path()) { LoadJoints(this->layer_param_.video_data_param().img_list_path(), this->person_map, this->layer_param_.video_data_param().img_list_prefix()); if (this->layer_param_.video_data_param().select_joints_size() > 0) { for (int s = 0; s < this->layer_param_.video_data_param().select_joints_size(); s++) select_joints.push_back(this->layer_param_.video_data_param().select_joints(s)); } int roi_w = this->layer_param_.video_data_param().roi_w(); int roi_h = this->layer_param_.video_data_param().roi_h(); CHECK(ReadSegmentRGBPoseToDatum(lines_[lines_id_].first, lines_[lines_id_].second, offsets, new_height, new_width, new_length, &datum, true, roi_pool_flag, name_pattern_.c_str(), this->person_map, 0, select_joints, this->layer_param_.video_data_param().stride(), roi_w, roi_h)); } else { LOG(ERROR) << "img_list_path not set when setting to RGB_POSE modality"; } } const int crop_size = this->layer_param_.transform_param().crop_size(); const int crop_height = this->layer_param_.transform_param().crop_height(); const int crop_width = this->layer_param_.transform_param().crop_width(); const int batch_size = this->layer_param_.video_data_param().batch_size(); const int num_branches = this->layer_param_.transform_param().is_roi_size(); // LOG(INFO) << "CROP FLAG:" << crop_height > 0 && crop_width > 0; if (crop_height > 0 && crop_width > 0) { top[0]->Reshape(batch_size, num_branches * datum.channels(), crop_height, crop_width); this->prefetch_data_.Reshape(batch_size, num_branches * datum.channels(), crop_height, crop_width); this->transformed_data_.Reshape(1, num_branches * datum.channels(), crop_height, crop_width); } else if (crop_size > 0) { top[0]->Reshape(batch_size, num_branches * datum.channels(), crop_size, crop_size); this->prefetch_data_.Reshape(batch_size, num_branches * datum.channels(), crop_size, crop_size); this->transformed_data_.Reshape(1, datum.channels(), crop_size, crop_size); } else { top[0]->Reshape(batch_size, num_branches * datum.channels(), datum.height(), datum.width()); this->prefetch_data_.Reshape(batch_size, num_branches * datum.channels(), datum.height(), datum.width()); this->transformed_data_.Reshape(1, num_branches * datum.channels(), datum.height(), datum.width()); } LOG(INFO) << "output data size: " << top[0]->num() << "," << top[0]->channels() << "," << top[0]->height() << "," << top[0]->width(); top[1]->Reshape(batch_size, 1, 1, 1); // label this->prefetch_label_.Reshape(batch_size, 1, 1, 1); // vector<int> top_shape = this->data_transformer_->InferBlobShape(datum); } template<typename Dtype> void VideoDataLayer<Dtype>::ShuffleVideos() { caffe::rng_t *prefetch_rng1 = static_cast<caffe::rng_t *>(prefetch_rng_1_->generator()); caffe::rng_t *prefetch_rng2 = static_cast<caffe::rng_t *>(prefetch_rng_2_->generator()); shuffle(lines_.begin(), lines_.end(), prefetch_rng1); shuffle(lines_duration_.begin(), lines_duration_.end(), prefetch_rng2); } template<typename Dtype> void VideoDataLayer<Dtype>::InternalThreadEntry() { Datum datum; CHECK(this->prefetch_data_.count()); Dtype *top_data = this->prefetch_data_.mutable_cpu_data(); Dtype *top_label = this->prefetch_label_.mutable_cpu_data(); VideoDataParameter video_data_param = this->layer_param_.video_data_param(); const int batch_size = video_data_param.batch_size(); const int new_height = video_data_param.new_height(); const int new_width = video_data_param.new_width(); const int new_length = video_data_param.new_length(); const int num_segments = video_data_param.num_segments(); const int lines_size = lines_.size(); if (this->phase_ == TEST && this->layer_param_.video_data_param().has_video_id_path()) { string video_id_path = this->layer_param_.video_data_param().video_id_path(); std::ifstream fvideo_id(video_id_path.c_str()); string video_id_str; getline(fvideo_id, video_id_str); lines_id_ = atoi(video_id_str.c_str()); fvideo_id.close(); // LOG(INFO) << "Worker " << Caffe::device_id() << " lines_id_: "<< lines_id_; } for (int item_id = 0; item_id < batch_size; ++item_id) { CHECK_GT(lines_size, lines_id_); vector<int> offsets; int num_offsets = num_segments; if (video_data_param.has_num_offsets()) num_offsets = video_data_param.num_offsets(); int average_duration = (int) (lines_duration_[lines_id_] - new_length) / (num_offsets - 1); if (this->phase_ == TRAIN && video_data_param.random_sample()) { int offset_id_seed = num_offsets > num_segments ? rand() % (num_offsets - num_segments - 1) : 0; for (int i = offset_id_seed; i < offset_id_seed + num_segments; ++i) { if (average_duration > 0) { caffe::rng_t *frame_rng = static_cast<caffe::rng_t *>(frame_prefetch_rng_->generator());//random generator int offset = average_duration - new_length > 0 ? (*frame_rng)() % (average_duration - new_length + 1) : 1; // frame id by 0 // LOG(INFO) << "Average duration: " << average_duration; // LOG(INFO) << "offset: " << offset; // LOG(INFO) << "Pushing " << offset + i * average_duration <<" into offsets!"; offsets.push_back(std::min(offset + i * average_duration, lines_duration_[lines_id_] - new_length)); // segment position in video } else { offsets.push_back(0); } } } else { for (int i = 0; i < num_segments; ++i) { if (average_duration > 0) offsets.push_back(std::min(1 + i * average_duration, lines_duration_[lines_id_] - new_length)); //(average_duration - new_length + 1) / 2 else offsets.push_back(0); } } if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_FLOW) { if (!ReadSegmentFlowToDatum(lines_[lines_id_].first, lines_[lines_id_].second, offsets, new_height, new_width, new_length, &datum, name_pattern_.c_str())) { continue; } } else if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_RGB_FLOW) { if (!ReadSegmentRGBFlowToDatum(lines_[lines_id_].first, lines_[lines_id_].second, offsets, new_height, new_width, new_length, &datum, true, name_pattern_.c_str())) { continue; } } else if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_RGB_POSE) { // if (this->phase_==TEST){ // LOG(INFO) << "Testing video:" << lines_[lines_id_].first; // } bool roi_pool_flag = this->layer_param_.video_data_param().roi_pool_flag(); int roi_w = this->layer_param_.video_data_param().roi_w(); int roi_h = this->layer_param_.video_data_param().roi_h(); // LOG(INFO) << "LINE ID: " << lines_id_ << ", FNAME: " << lines_[lines_id_].first; if (!ReadSegmentRGBPoseToDatum(lines_[lines_id_].first, lines_[lines_id_].second, offsets, new_height, new_width, new_length, &datum, true, roi_pool_flag, name_pattern_.c_str(), this->person_map, item_id, select_joints, this->layer_param_.video_data_param().stride(), roi_w, roi_h)) { continue; } } else { if (!ReadSegmentRGBToDatum(lines_[lines_id_].first, lines_[lines_id_].second, offsets, new_height, new_width, new_length, &datum, true, name_pattern_.c_str())) { continue; } } int offset1 = this->prefetch_data_.offset(item_id); this->transformed_data_.set_cpu_data(top_data + offset1); this->data_transformer_->Transform(datum, &(this->transformed_data_)); if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_RGB_POSE && this->layer_param_.video_data_param().roi_part() == VideoDataParameter_ROI_Part_FACE) { top_label[item_id] = lines_[lines_id_].second == 0 || lines_[lines_id_].second == 1 ? lines_[lines_id_].second : lines_[lines_id_].second == 77 ? 2 : lines_[lines_id_].second == 19 ? 3 : 4; } else if (this->layer_param_.video_data_param().modality() == VideoDataParameter_Modality_RGB_POSE && this->layer_param_.video_data_param().roi_part() == VideoDataParameter_ROI_Part_ARM) { if (lines_[lines_id_].second == 98) { top_label[item_id] = 0; } else if (lines_[lines_id_].second == 22) { top_label[item_id] = 1; } else if (lines_[lines_id_].second == 23) { top_label[item_id] = 2; } else if (lines_[lines_id_].second == 32) { top_label[item_id] = 3; } else if (lines_[lines_id_].second == 34) { top_label[item_id] = 4; } else if (lines_[lines_id_].second == 55) { top_label[item_id] = 5; } else if (lines_[lines_id_].second == 57) { top_label[item_id] = 6; } else if (lines_[lines_id_].second == 78) { top_label[item_id] = 7; } else { top_label[item_id] = 8; } } else { top_label[item_id] = lines_[lines_id_].second; } // LOG(INFO) << "LABEL: " << top_label[item_id]; //LOG() //next iteration if (!this->layer_param_.video_data_param().has_video_id_path()) { lines_id_++; } if (lines_id_ >= lines_size) { DLOG(INFO) << "Restarting data prefetching from start."; lines_id_ = 0; if (this->layer_param_.video_data_param().shuffle()) { ShuffleVideos(); } } } } INSTANTIATE_CLASS(VideoDataLayer); REGISTER_LAYER_CLASS(VideoData); }
43.243827
135
0.690315
[ "vector", "transform" ]
5c211bfce6113509fe599c5ae4bccfb742c41a23
874
cpp
C++
c++/stl/vector/matric.cpp
anhsirksai/coding
4bd49771c0ac7f7bf2d26fecea606955f12e535e
[ "MIT" ]
null
null
null
c++/stl/vector/matric.cpp
anhsirksai/coding
4bd49771c0ac7f7bf2d26fecea606955f12e535e
[ "MIT" ]
null
null
null
c++/stl/vector/matric.cpp
anhsirksai/coding
4bd49771c0ac7f7bf2d26fecea606955f12e535e
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include <iostream> #include <vector> using namespace std; int main() { // An empty vector of vectors. The space // between the 2 '>' signs is necessary vector<vector<int> > v2d; // If you intend creating many vectors // of vectors, the following's tidier typedef vector<vector<int> > IntMatrix; IntMatrix m; // Now we'll try to create a 3 by 5 "matrix". // First, create a vector with 5 elements vector<int> v2(5, 99); // Now create a vector of 3 elements. // Each element is a copy of v2 vector<vector<int> > v2d2(3,v2); // Print out the elements for(int i=0;i<v2d2.size(); i++) { for (int j=0;j<v2d2[i].size(); j++) cout << v2d2[i][j] << " "; cout << endl; } } //output //➜ vector git:(master) ✗ ./a.out //99 99 99 99 99 //99 99 99 99 99 //99 99 99 99 99
23
46
0.590389
[ "vector" ]
5c22f636a677d660719f02c500a9b56c0e696c5e
13,432
cpp
C++
opencv-cpp/cameracalibration/src/CameraCalibration.cpp
sgjava/install-opencv
5a8fb14e93925c326563c2ccdd582f9dc503523e
[ "Unlicense" ]
72
2015-01-30T14:56:34.000Z
2021-04-07T12:24:16.000Z
opencv-cpp/cameracalibration/src/CameraCalibration.cpp
sgjava/install-opencv
5a8fb14e93925c326563c2ccdd582f9dc503523e
[ "Unlicense" ]
9
2015-03-19T13:57:08.000Z
2021-03-24T12:22:02.000Z
opencv-cpp/cameracalibration/src/CameraCalibration.cpp
sgjava/install-opencv
5a8fb14e93925c326563c2ccdd582f9dc503523e
[ "Unlicense" ]
22
2015-03-25T06:11:17.000Z
2021-07-27T11:56:34.000Z
/* * Copyright (c) Steven P. Goldsmith. All rights reserved. * * Created by Steven P. Goldsmith on November 6, 2015 * sgjava@gmail.com */ #include <glob.h> #include <iostream> #include <sys/time.h> #include <sstream> #include <vector> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; /** * Set the criteria for the cornerSubPix algorithm. */ static const TermCriteria CRITERIA = TermCriteria( TermCriteria::EPS + TermCriteria::COUNT, 30, 0.1); /** @brief Returns list of file names. @param pattern Mask to match. Return vector of sting containing list of files names matching pattern. */ vector<string> globVector(const string& pattern) { glob_t glob_result; glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result); vector<string> files; for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) { files.push_back(string(glob_result.gl_pathv[i])); } globfree(&glob_result); return files; } /** @brief Find chess board corners. @param gray Source chessboard view. It must be an 8-bit grayscale or color image. @param pattern_size Number of inner corners per a chessboard row and column. @param win_size Half of the side length of the search window. The function attempts to determine whether the input image is a view of the chessboard pattern and locate the internal chessboard corners. The function returns a non-zero value if all of the corners are found and they are placed in a certain order (row by row, left to right in every row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example, a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black squares touch each other. The detected coordinates are approximate, and to determine their positions more accurately, the function calls cornerSubPix. You also may use the function cornerSubPix with different parameters if returned coordinates are not accurate enough. */ vector<Point2f> getCorners(Mat gray, Size pattern_size, Size win_size, Size zone_size) { vector<Point2f> corners; if (findChessboardCorners(gray, pattern_size, corners)) { cornerSubPix(gray, corners, win_size, zone_size, CRITERIA); } return corners; } /** @brief Point3f corners. @param pattern_size Pattern size. */ vector<Point3f> getCorner3f(Size pattern_size) { vector<Point3f> corners3f(pattern_size.height * pattern_size.width); double squareSize = 50; int cnt = 0; for (int i = 0; i < pattern_size.height; ++i) { for (int j = 0; j < pattern_size.width; ++j, cnt++) { corners3f[cnt] = Point3f(j * squareSize, i * squareSize, 0.0); } } return corners3f; } /** @brief Calculate re-projection error. @param object_points Vector of vectors of calibration pattern points. @param rvecs Vector of rotation vectors. @param tvecs Vector of translation vectors estimated for each pattern view. @param camera_matrix 3x3 floating-point camera matrix. @param dist_coeffs Vector of distortion coefficients. @param image_points Vector of vectors of the projections of calibration pattern points. Re-projection error gives a good estimation of just how exact the found parameters are. This should be as close to zero as possible. The function computes projections of 3D points to the image plane given intrinsic and extrinsic camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of image points coordinates (as functions of all the input parameters) with respect to the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global optimization in calibrateCamera, solvePnP, and stereoCalibrate . The function itself can also be used to compute a re-projection error given the current intrinsic and extrinsic parameters. @note By setting rvec=tvec=(0,0,0) or by setting cameraMatrix to a 3x3 identity matrix, or by passing zero distortion coefficients, you can get various useful partial cases of the function. This means that you can compute the distorted coordinates for a sparse set of points or apply a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup. */ double reprojectionError(vector<vector<Point3f> > object_points, vector<Mat> rvecs, vector<Mat> tvecs, Mat camera_matrix, Mat dist_coeffs, vector<vector<Point2f> > image_points) { double total_error = 0; double total_points = 0; vector<Point2f> corners_projected; for (size_t i = 0, max = object_points.size(); i != max; ++i) { projectPoints(object_points[i], rvecs[i], tvecs[i], camera_matrix, dist_coeffs, corners_projected); double error = norm(image_points[i], corners_projected, NORM_L2); int n = object_points[i].size(); total_error += error * error; total_points += n; } return sqrt(total_error / total_points); } /** @brief Calibrate camera. @param object_points Vector of vectors of calibration pattern points. @param image_points Vector of vectors of the projections of calibration pattern points. @param images Vector of images to use in calibration. The function estimates the intrinsic camera parameters and extrinsic parameters for each of the views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object points and their corresponding 2D projections in each view must be specified. That may be achieved by using an object with a known geometry and easily detectable feature points. Such an object is called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as a calibration rig (see findChessboardCorners ). Currently, initialization of intrinsic parameters (when CV_CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also be used as long as initial cameraMatrix is provided. */ pair<Mat, Mat> calibrate(vector<vector<Point3f> > object_points, vector<vector<Point2f> > image_points, vector<Mat> images) { vector<Mat> rvecs, tvecs; Mat camera_matrix(3, 3, CV_64F); Mat dist_coeffs(8, 1, CV_64F); double rms = calibrateCamera(object_points, image_points, images[0].size(), camera_matrix, dist_coeffs, rvecs, tvecs); double error = reprojectionError(object_points, rvecs, tvecs, camera_matrix, dist_coeffs, image_points); cout << "Mean reprojection error: " << error << endl; cout << "RMS: " << rms << endl; cout << "Camera matrix: " << camera_matrix << endl; cout << "Distortion coefficients: " << dist_coeffs << endl; pair<Mat, Mat> ret_params(camera_matrix, dist_coeffs); return ret_params; } /** @brief Undistort image. @param image Image to undistort. @param camera_matrix 3x3 floating-point camera matrix. @param dist_coeffs Vector of distortion coefficients. The function computes and returns the optimal new camera matrix based on the free scaling parameter. By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original image pixels if there is valuable information in the corners alpha=1 , or get something in between. When alpha\>0 , the undistortion result is likely to have some black pixels corresponding to "virtual" pixels outside of the captured distorted image. The original camera matrix, distortion coefficients, the computed new camera matrix, and newImageSize should be passed to initUndistortRectifyMap to produce the maps for remap. */ Mat undistort(Mat image, Mat camera_matrix, Mat dist_coeffs) { Mat new_camera_mtx = getOptimalNewCameraMatrix(camera_matrix, dist_coeffs, image.size(), 0); Mat mat; undistort(image, mat, camera_matrix, dist_coeffs, new_camera_mtx); return mat; } /** @brief Undistort files matching file mask. @param in_mask File mask used to select files. @param out_dir Where undistorted images are stored.. @param camera_matrix 3x3 floating-point camera matrix. @param dist_coeffs Vector of distortion coefficients. Process all images matching in_mask and output undistorted images to out_dir. */ void undistortAll(string in_mask, string out_dir, Mat camera_matrix, Mat dist_coeffs) { // Get list of files to process. vector<string> files = globVector(in_mask); for (size_t i = 0, max = files.size(); i != max; ++i) { // Read in image unchanged Mat mat = imread(files[i], IMREAD_UNCHANGED); Mat undistort_img = undistort(mat, camera_matrix, dist_coeffs); // Get just file name from path string just_file_name = files[i].substr(files[i].find_last_of("/") + 1, files[i].length()); // File name to write to string write_file_name = out_dir + just_file_name.substr(0, just_file_name.find_last_of(".")) + "-cpp-undistort.bmp"; imwrite(write_file_name, undistort_img); } } /** @brief Get object and image points for files matching file mask. @param in_mask File mask used to select files. @param out_dir Where undistorted images are stored. @param pattern_size Number of inner corners per a chessboard row and column. Process all images matching in_mask and build object and image point vectors. */ pair<Mat, Mat> getPoints(string in_mask, string out_dir, Size pattern_size) { vector<Point3f> corners3f = getCorner3f(pattern_size); // Get list of files to process. vector<string> files = globVector(in_mask); vector<vector<Point3f> > object_points(files.size()); vector<vector<Point2f> > image_points(files.size()); vector<Mat> images(files.size()); int passed = 0; for (size_t i = 0, max = files.size(); i != max; ++i) { Mat mat = imread(files[i], IMREAD_GRAYSCALE); vector<Point2f> corners; Size win_size = Size(5, 5); Size zone_size = Size(-1, -1); corners = getCorners(mat, pattern_size, win_size, zone_size); // Process only images that pass getCorners if (!corners.empty()) { Mat vis; // Convert to color for drawing cvtColor(mat, vis, COLOR_GRAY2BGR); drawChessboardCorners(vis, pattern_size, corners, true); // Get just file name from path string just_file_name = files[i].substr( files[i].find_last_of("/") + 1, files[i].length()); // File name to write to string write_file_name = out_dir + just_file_name.substr(0, just_file_name.find_last_of(".")) + "-cpp.bmp"; imwrite(write_file_name, vis); object_points[i] = corners3f; image_points[i] = corners; images[i] = mat; passed++; } else { cout << "Chessboard not found in: " << files[i] << endl; } } cout << "Images passed findChessboardCorners: " << passed << endl; // Calibrate camera return calibrate(object_points, image_points, images); } /** @brief Save Mat to file. @param mat Mat to save. @param file_name File name to save as. */ void saveMat(Mat mat, string file_name) { FileStorage file(file_name, FileStorage::WRITE); file << "mat" << mat; file.release(); } /** @brief Load mat from file. @param file_name File name to load. */ Mat loadMat(string file_name) { FileStorage file(file_name, FileStorage::READ); Mat mat; file["mat"] >> mat; file.release(); return mat; } /** * Camera calibration. * * You need at least 10 images that pass cv2.findChessboardCorners at varying * angles and distances from the camera. You must do this for each resolution * you wish to calibrate. Camera matrix and distortion coefficients are written * to files for later use with undistort. This code is based on * http://computervisionandjava.blogspot.com/2013/10/camera-cailbration.html, * but follows Python code closely (hence the identical values returned). * * argv[1] = input file mask or will default to "../../resources/2015*.jpg" if no * args passed. * * argv[2] = output dir or will default to "../../output/" if no args passed. * * argv[3]] = cols,rows of chess board or will default to "7,5" if no args * passed. * * @author sgoldsmith * @version 1.0.0 * @since 1.0.0 */ int main(int argc, char *argv[]) { cout << CV_VERSION << endl; int return_val = 0; string in_mask; string out_dir; Size pattern_size; // Parse args if (argc == 4) { in_mask = argv[1]; out_dir = argv[2]; stringstream ss(argv[3]); vector<int> result(2); int i = 0; // Parse width and height "7,5" for example while (ss.good()) { string substr; getline(ss, substr, ','); result[i++] = atoi(substr.c_str()); } pattern_size = Size(result[0], result[1]); } else { in_mask = "../../resources/2015*.jpg"; out_dir = "../../output/"; pattern_size = Size(7, 5); } cout << "Input mask: " << in_mask << endl; cout << "Output dir: " << out_dir << endl; cout << "Pattern size: " << pattern_size << endl; timeval start_time; gettimeofday(&start_time, 0); pair<Mat, Mat> data = getPoints(in_mask, out_dir, pattern_size); undistortAll(in_mask, out_dir, data.first, data.second); // Save mats cout << "Saving calibration parameters to file" << endl; saveMat(data.first, out_dir + "camera-matrix.xml"); saveMat(data.second, out_dir + "dist-coefs.xml"); // Load mats cout << "Restoring calibration parameters from file" << endl; Mat camera_matrix =loadMat(out_dir + "camera-matrix.xml"); Mat dist_coeffs = loadMat(out_dir + "dist-coefs.xml"); cout << "Camera matrix: " << camera_matrix << endl; cout << "Distortion coefficients: " << dist_coeffs << endl; timeval end_time; gettimeofday(&end_time, 0); cout << "Elapsed time: " << (end_time.tv_sec - start_time.tv_sec) << " seconds" << endl; return return_val; }
38.487106
101
0.735036
[ "geometry", "object", "vector", "3d" ]
5c28dfa8cda4d37de0d947741635a6dfc6bfef80
16,002
cpp
C++
LPG-language-server/src/message/DocumentSymbolHandler.cpp
kuafuwang/LPG-language-server
0baf01b4b7752991b6ba45687929c241dab52537
[ "MIT" ]
2
2021-07-07T14:00:02.000Z
2021-08-05T23:14:33.000Z
LPG-language-server/src/message/DocumentSymbolHandler.cpp
kuafuwang/LPG-language-server
0baf01b4b7752991b6ba45687929c241dab52537
[ "MIT" ]
null
null
null
LPG-language-server/src/message/DocumentSymbolHandler.cpp
kuafuwang/LPG-language-server
0baf01b4b7752991b6ba45687929c241dab52537
[ "MIT" ]
null
null
null
#include "MessageHandler.h" #include "../CompilationUnit.h" #include "../parser/LPGParser.h" #include "../parser/LPGParser_top_level_ast.h" #include "../ASTUtils.h" #include <stack> #include "LPGSourcePositionLocator.h" #include "../WorkSpaceManager.h" #include "../parser/JikesPGOptions.h" using namespace LPGParser_top_level_ast; struct LPGModelVisitor :public AbstractVisitor { std::string fRHSLabel; ILexStream* lex = nullptr; std::shared_ptr<CompilationUnit>& unit; std::stack< lsDocumentSymbol*> fItemStack; void unimplementedVisitor(const std::string& s) { } LPGModelVisitor(std::shared_ptr<CompilationUnit>& u, lsDocumentSymbol* rootSymbol, ILexStream* _l) :lex(_l), unit(u) { fItemStack.push(rootSymbol); } lsDocumentSymbol* createSubItem(IAst* n) { auto parent = fItemStack.top(); if (!parent->children.has_value()) { parent->children = std::vector<lsDocumentSymbol>(); } auto& children = parent->children.value(); children.emplace_back(lsDocumentSymbol()); lsDocumentSymbol* treeNode = &children[children.size() - 1]; treeNode->kind = lsSymbolKind::Class; auto token = n->getLeftIToken(); treeNode->name = token->to_utf8_string(); auto pos = ASTUtils::toPosition(lex, token->getStartOffset()); if (pos) { treeNode->range.start = pos.value(); } pos = ASTUtils::toPosition(lex, token->getEndOffset()); if (pos) { treeNode->range.end = pos.value(); } treeNode->selectionRange = treeNode->range; return treeNode; } lsDocumentSymbol* pushSubItem(IAst* n) { auto node = createSubItem(n); fItemStack.push(node); return node; } void popSubItem() { fItemStack.pop(); } bool visit(AliasSeg* n) { auto symbol = pushSubItem(n); return true; } void endVisit(AliasSeg* n) { popSubItem(); } bool visit(AstSeg* n) { auto symbol = pushSubItem(n); return true; } void endVisit(AstSeg* n) { popSubItem(); } bool visit(DefineSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Define "; return true; } void endVisit(DefineSeg* n) { popSubItem(); } bool visit(EofSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Eof "; return true; } void endVisit(EofSeg* n) { popSubItem(); } bool visit(EolSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Eol "; return true; } void endVisit(EolSeg* n) { popSubItem(); } bool visit(ErrorSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Error "; return true; } void endVisit(ErrorSeg* n) { popSubItem(); } bool visit(ExportSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Export "; std::wstring prefix; prefix.push_back(unit->runtime_unit->getEscapeToken()); prefix.push_back('_'); for (auto& it : n->lpg_export_segment->list) { auto item = pushSubItem(it); item->kind = lsSymbolKind::Interface; auto name = it->getLeftIToken()->toString(); unit->export_macro_table.insert({ prefix + name , it }); unit->export_term.insert({ name , it }); popSubItem(); } return true; } void endVisit(ExportSeg* n) { popSubItem(); } bool visit(GlobalsSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Globals"; return true; } void endVisit(GlobalsSeg* n) { popSubItem(); } bool visit(HeadersSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Headers"; return true; } void endVisit(HeadersSeg* n) { popSubItem(); } bool visit(IdentifierSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Identifier"; return true; } void endVisit(IdentifierSeg* n) { popSubItem(); } bool visit(import_segment* n) { auto symbol = pushSubItem(n); symbol->name = "import_segment"; return false; } void endVisit(import_segment* n) { popSubItem(); } bool visit(include_segment* n) { auto symbol = pushSubItem(n); symbol->name = "include "; symbol->kind = lsSymbolKind::File; auto file_name = n->getSYMBOL()->to_utf8_string(); symbol->name += file_name; unit->dependence_info.include_files.push_back({ file_name,n }); return true; } void endVisit(include_segment* n) { popSubItem(); } bool visit(KeywordsSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Keywords "; return true; } void endVisit(KeywordsSeg* n) { popSubItem(); } bool visit(NamesSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Names "; return true; } void endVisit(NamesSeg* n) { popSubItem(); } bool visit(NoticeSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Notice "; return false; } void endVisit(NoticeSeg* n) { popSubItem(); } bool visit(PredecessorSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Predecessor "; return true; } void endVisit(PredecessorSeg* n) { popSubItem(); } bool visit(RecoverSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Recover "; return true; } void endVisit(RecoverSeg* n) { popSubItem(); } bool visit(RulesSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Rules "; return true; } void endVisit(RulesSeg* n) { popSubItem(); } bool visit(SoftKeywordsSeg* n) { auto symbol = pushSubItem(n); symbol->name = "SoftKeywords "; return true; } void endVisit(SoftKeywordsSeg* n) { popSubItem(); } bool visit(StartSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Start "; return true; } void endVisit(StartSeg* n) { popSubItem(); } bool visit(TerminalsSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Terminals "; return true; } void endVisit(TerminalsSeg* n) { popSubItem(); } bool visit(TrailersSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Trailers "; return true; } void endVisit(TrailersSeg* n) { popSubItem(); } bool visit(TypesSeg* n) { auto symbol = pushSubItem(n); symbol->name = "Types "; return true; } void endVisit(TypesSeg* n) { popSubItem(); } bool visit(defineSpec* n) { auto node = static_cast<ASTNode*>(n->getmacro_name_symbol()); auto symbol = createSubItem(node); symbol->kind = lsSymbolKind::Variable; symbol->name = node->to_utf8_string(); auto pos = ASTUtils::toPosition(lex, node->getRightIToken()->getEndOffset()); if (pos) { symbol->range.end = pos.value(); } return true; } bool visit(terminal_symbol1* n) { auto sym = createSubItem((ASTNode*)n->getMACRO_NAME()); sym->kind = lsSymbolKind::Macro; return false; } void endVisit(start_symbol0* n) { auto sym = createSubItem(n); sym->kind = lsSymbolKind::Macro; } void endVisit(start_symbol1* n) { auto sym = createSubItem(n); sym->kind = lsSymbolKind::Macro; } void endVisit(terminal* n) { auto symbol = n->getterminal_symbol(); auto alias = n->getoptTerminalAlias(); std::string label; if (alias != nullptr) { auto prod = alias->getproduces(); auto name = alias->getname(); label = nameImage(name) + " " + producesImage(prod) + " " + symbolImage(symbol); } else label = symbolImage(symbol); auto item = createSubItem(symbol); item->name.swap(label); item->kind = lsSymbolKind::String; } bool visit(nonTerm* n) { if (n->getruleList()->size() > 1) { auto item = pushSubItem(n); item->kind = lsSymbolKind::Field; } return true; } void endVisit(nonTerm* n) { if (n->getruleList()->size() > 1) popSubItem(); } bool visit(rule* n) { fRHSLabel.clear(); nonTerm* parentNonTerm = static_cast<nonTerm*>(n->getParent()->getParent()); if (parentNonTerm->getruleList()->size() == 1) { fRHSLabel.append(parentNonTerm->getruleNameWithAttributes()->getSYMBOL()->to_utf8_string()); fRHSLabel.append(" ::= "); } return true; } void endVisit(rule* n) { auto item = createSubItem(n); item->name.swap(fRHSLabel); item->kind = lsSymbolKind::Field; fRHSLabel.clear(); } void endVisit(symWithAttrs0* n) { fRHSLabel.push_back(' '); fRHSLabel.append(n->getIToken()->to_utf8_string()); } void endVisit(symWithAttrs1* n) { fRHSLabel.push_back(' '); fRHSLabel.append(n->getSYMBOL()->to_utf8_string()); } // bool visit(types_segment1 n) { // return true; // } bool visit(type_declarations* n) { pushSubItem(n); return true; } void endVisit(type_declarations* n) { popSubItem(); } std::string producesImage(ASTNode* produces) { if (dynamic_cast<produces0*>(produces) || dynamic_cast<produces1*>(produces) || dynamic_cast<produces2*>(produces) || dynamic_cast<produces3*>(produces) ) return produces->getLeftIToken()->to_utf8_string(); return "<???>"; } std::string nameImage(ASTNode* name) { if (dynamic_cast<name0*>(name) || dynamic_cast<name1*>(name) || dynamic_cast<name5*>(name)) { return name->getLeftIToken()->to_utf8_string();; } else if (dynamic_cast<name2*>(name)) return "$empty"; else if (dynamic_cast<name3*>(name)) return "$error"; else if (dynamic_cast<name4*>(name)) return "$eol"; else return "<???>"; } std::string symbolImage(ASTNode* symbol) { return symbol->getLeftIToken()->to_utf8_string(); } std::string symbolListImage(ASTNode* symbols) { auto symbolList = (SYMBOLList*)symbols; std::string buff; buff.push_back('('); for (int i = 0; i < symbolList->size(); i++) { if (i > 0) buff.push_back(','); buff.append(symbolImage(symbolList->getSYMBOLAt(i))); } buff.push_back(')'); return buff; } std::string blockImage(ASTNodeToken block) { return block.getLeftIToken()->to_utf8_string(); } }; namespace { void build_option(DependenceInfo& infos_info, std::vector<lsDocumentSymbol>& out, option_specList* list, ILexStream* lex) { int size = list->size(); for (int i = 0; i < size; ++i) { auto _option_spec = list->getoption_specAt(i); if (!_option_spec) { continue; } optionList* lpg_optionList = _option_spec->getoption_list(); if (!lpg_optionList) { continue; } for (size_t k = 0; k < lpg_optionList->list.size(); ++k) { option* _opt = lpg_optionList->getoptionAt(k); if (!_opt) continue; lsDocumentSymbol children; children.name = _opt->to_utf8_string(); auto sym = _opt->getSYMBOL(); std::stringex optName = sym->to_utf8_string(); optName.tolower(); if (OptionDescriptor::IsIncludeOption(optName)) { children.kind = lsSymbolKind::File; string fileName; auto optValue = _opt->getoption_value(); if(!optValue) continue; if (dynamic_cast<option_value0*>(optValue)) { fileName = static_cast<option_value0*>(optValue)->getSYMBOL()->to_utf8_string(); } else { fileName = optValue->to_utf8_string(); } if (optName.find("import") != std::string::npos && optName.find("terminals") != std::string::npos) { infos_info.import_terminals_files.push_back({ fileName,_opt }); } else if (optName == ("template")) { infos_info.template_files.push_back({ fileName,_opt }); } else { infos_info.filter_files.push_back({ fileName,_opt }); } } else { children.kind = lsSymbolKind::Property; } auto pos = ASTUtils::toPosition(lex, _opt->getSYMBOL()->getLeftIToken()->getStartOffset()); if (pos) { children.range.start = pos.value(); } pos = ASTUtils::toPosition(lex, _opt->getSYMBOL()->getRightIToken()->getEndOffset()); if (pos) { children.range.end = pos.value(); } children.selectionRange = children.range; out.emplace_back(children); } } } } void process_symbol(std::shared_ptr<CompilationUnit>& unit) { if (!unit->runtime_unit->root) { return; } std::vector< lsDocumentSymbol >& children = unit->document_symbols; auto lex = unit->runtime_unit->_lexer.getILexStream(); auto lpg_options_ = (option_specList*)unit->runtime_unit->root->getoptions_segment(); if (lpg_options_ && lpg_options_->list.size()) { children.push_back({}); lsDocumentSymbol& lpg_options_segment = children[children.size() - 1]; lpg_options_segment.kind = lsSymbolKind::Package; lpg_options_segment.name = "options"; auto pos = ASTUtils::toPosition(lex, lpg_options_->getLeftIToken()->getStartOffset()); if (pos) { lpg_options_segment.range.start = pos.value(); } pos = ASTUtils::toPosition(lex, lpg_options_->getRightIToken()->getEndOffset()); if (pos) { lpg_options_segment.range.end = pos.value(); } lpg_options_segment.selectionRange = lpg_options_segment.range; lpg_options_segment.children = std::vector<lsDocumentSymbol>(); build_option(unit->dependence_info, lpg_options_segment.children.value(), lpg_options_, unit->runtime_unit->_lexer.getILexStream()); } if (auto _input = unit->runtime_unit->root->getLPG_INPUT(); _input) { lsDocumentSymbol root; root.children = std::vector<lsDocumentSymbol>(); LPGModelVisitor visitor(unit, &root, lex); _input->accept(&visitor); for (auto& it : root.children.value()) { children.push_back({}); children.back().swap(it); } } }
26.80402
120
0.534683
[ "vector" ]
5c3f7c54370c199ecfe0ecb7e0eedb9814595d90
5,279
hpp
C++
include/te/basic.hpp
a1exwang/te
49732e489e84d93b26ecfd93476267c9e46bc965
[ "MIT" ]
null
null
null
include/te/basic.hpp
a1exwang/te
49732e489e84d93b26ecfd93476267c9e46bc965
[ "MIT" ]
null
null
null
include/te/basic.hpp
a1exwang/te
49732e489e84d93b26ecfd93476267c9e46bc965
[ "MIT" ]
null
null
null
#pragma once #include <cinttypes> #include <bitset> #include <vector> namespace te { constexpr uint8_t ESC = 0x1bu; static const char *CSI = "\x1b["; #pragma pack(push, 1) union Color { uint32_t u32; struct { uint8_t b; uint8_t g; uint8_t r; uint8_t a; }; }; #pragma pack(pop) constexpr Color ColorWhite = Color{0xffcccccc}; constexpr Color ColorBlack = Color{0xff000000}; constexpr Color ColorRed = Color{0xffcc0000}; constexpr Color ColorGreen = Color{0xff00cc00}; constexpr Color ColorBlue = Color{0xff0000cc}; constexpr Color ColorYellow = Color{0xff888800}; constexpr Color ColorCyan = Color{0xff008888}; constexpr Color ColorMagenta = Color{0xff880088}; constexpr Color ColorBrightWhite = Color{0xffeeeeee}; constexpr Color ColorBrightBlack = Color{0xff444444}; constexpr Color ColorBrightRed = Color{0xffee0000}; constexpr Color ColorBrightGreen = Color{0xff00ee00}; constexpr Color ColorBrightBlue = Color{0xff0000ee}; constexpr Color ColorBrightYellow = Color{0xffaaaa00}; constexpr Color ColorBrightCyan = Color{0xff00aaaa}; constexpr Color ColorBrightMagenta = Color{0xffaa00aa}; enum { CHAR_ATTR_BOLD = 0, CHAR_ATTR_FAINT, CHAR_ATTR_ITALIC, CHAR_ATTR_UNDERLINE, CHAR_ATTR_INVERT, CHAR_ATTR_CROSSED_OUT, // CSI ?0h CHAR_ATTR_CURSOR_APPLICATION_MODE, // CSI ?5h CHAR_ATTR_REVERSE_VIDEO, // CSI ?7h CHAR_ATTR_AUTO_WRAP_MODE, // CSI ?1049h CHAR_ATTR_XTERM_WINDOW_FOCUS_TRACKING, // CSI ?2004h CHAR_ATTR_XTERM_BLOCK_PASTE, CHAR_ATTR_COUNT }; struct Char { void reset() { *this = Char(); } std::string c; Color fg_color = ColorWhite; Color bg_color = ColorBlack; // TODO std::bitset<CHAR_ATTR_COUNT> attr; }; static Color ColorTable16[] = { ColorBlack, ColorRed, ColorGreen, ColorYellow, ColorBlue, ColorMagenta, ColorCyan, ColorWhite, ColorBrightBlack, ColorBrightRed, ColorBrightGreen, ColorBrightYellow, ColorBrightBlue, ColorBrightMagenta, ColorBrightCyan, ColorBrightWhite, }; // 256 colors static Color ColorTable256[] = { 0xff000000, 0xff800000, 0xff008000, 0xff808000, 0xff000080, 0xff800080, 0xff008080, 0xffc0c0c0, 0xff808080, 0xffff0000, 0xff00ff00, 0xffffff00, 0xff0000ff, 0xffff00ff, 0xff00ffff, 0xffffffff, 0xff000000, 0xff00005f, 0xff000087, 0xff0000af, 0xff0000d7, 0xff0000ff, 0xff005f00, 0xff005f5f, 0xff005f87, 0xff005faf, 0xff005fd7, 0xff005fff, 0xff008700, 0xff00875f, 0xff008787, 0xff0087af, 0xff0087d7, 0xff0087ff, 0xff00af00, 0xff00af5f, 0xff00af87, 0xff00afaf, 0xff00afd7, 0xff00afff, 0xff00d700, 0xff00d75f, 0xff00d787, 0xff00d7af, 0xff00d7d7, 0xff00d7ff, 0xff00ff00, 0xff00ff5f, 0xff00ff87, 0xff00ffaf, 0xff00ffd7, 0xff00ffff, 0xff5f0000, 0xff5f005f, 0xff5f0087, 0xff5f00af, 0xff5f00d7, 0xff5f00ff, 0xff5f5f00, 0xff5f5f5f, 0xff5f5f87, 0xff5f5faf, 0xff5f5fd7, 0xff5f5fff, 0xff5f8700, 0xff5f875f, 0xff5f8787, 0xff5f87af, 0xff5f87d7, 0xff5f87ff, 0xff5faf00, 0xff5faf5f, 0xff5faf87, 0xff5fafaf, 0xff5fafd7, 0xff5fafff, 0xff5fd700, 0xff5fd75f, 0xff5fd787, 0xff5fd7af, 0xff5fd7d7, 0xff5fd7ff, 0xff5fff00, 0xff5fff5f, 0xff5fff87, 0xff5fffaf, 0xff5fffd7, 0xff5fffff, 0xff870000, 0xff87005f, 0xff870087, 0xff8700af, 0xff8700d7, 0xff8700ff, 0xff875f00, 0xff875f5f, 0xff875f87, 0xff875faf, 0xff875fd7, 0xff875fff, 0xff878700, 0xff87875f, 0xff878787, 0xff8787af, 0xff8787d7, 0xff8787ff, 0xff87af00, 0xff87af5f, 0xff87af87, 0xff87afaf, 0xff87afd7, 0xff87afff, 0xff87d700, 0xff87d75f, 0xff87d787, 0xff87d7af, 0xff87d7d7, 0xff87d7ff, 0xff87ff00, 0xff87ff5f, 0xff87ff87, 0xff87ffaf, 0xff87ffd7, 0xff87ffff, 0xffaf0000, 0xffaf005f, 0xffaf0087, 0xffaf00af, 0xffaf00d7, 0xffaf00ff, 0xffaf5f00, 0xffaf5f5f, 0xffaf5f87, 0xffaf5faf, 0xffaf5fd7, 0xffaf5fff, 0xffaf8700, 0xffaf875f, 0xffaf8787, 0xffaf87af, 0xffaf87d7, 0xffaf87ff, 0xffafaf00, 0xffafaf5f, 0xffafaf87, 0xffafafaf, 0xffafafd7, 0xffafafff, 0xffafd700, 0xffafd75f, 0xffafd787, 0xffafd7af, 0xffafd7d7, 0xffafd7ff, 0xffafff00, 0xffafff5f, 0xffafff87, 0xffafffaf, 0xffafffd7, 0xffafffff, 0xffd70000, 0xffd7005f, 0xffd70087, 0xffd700af, 0xffd700d7, 0xffd700ff, 0xffd75f00, 0xffd75f5f, 0xffd75f87, 0xffd75faf, 0xffd75fd7, 0xffd75fff, 0xffd78700, 0xffd7875f, 0xffd78787, 0xffd787af, 0xffd787d7, 0xffd787ff, 0xffd7af00, 0xffd7af5f, 0xffd7af87, 0xffd7afaf, 0xffd7afd7, 0xffd7afff, 0xffd7d700, 0xffd7d75f, 0xffd7d787, 0xffd7d7af, 0xffd7d7d7, 0xffd7d7ff, 0xffd7ff00, 0xffd7ff5f, 0xffd7ff87, 0xffd7ffaf, 0xffd7ffd7, 0xffd7ffff, 0xffff0000, 0xffff005f, 0xffff0087, 0xffff00af, 0xffff00d7, 0xffff00ff, 0xffff5f00, 0xffff5f5f, 0xffff5f87, 0xffff5faf, 0xffff5fd7, 0xffff5fff, 0xffff8700, 0xffff875f, 0xffff8787, 0xffff87af, 0xffff87d7, 0xffff87ff, 0xffffaf00, 0xffffaf5f, 0xffffaf87, 0xffffafaf, 0xffffafd7, 0xffffafff, 0xffffd700, 0xffffd75f, 0xffffd787, 0xffffd7af, 0xffffd7d7, 0xffffd7ff, 0xffffff00, 0xffffff5f, 0xffffff87, 0xffffffaf, 0xffffffd7, 0xffffffff, 0xff080808, 0xff121212, 0xff1c1c1c, 0xff262626, 0xff303030, 0xff3a3a3a, 0xff444444, 0xff4e4e4e, 0xff585858, 0xff626262, 0xff6c6c6c, 0xff767676, 0xff808080, 0xff8a8a8a, 0xff949494, 0xff9e9e9e, 0xffa8a8a8, 0xffb2b2b2, 0xffbcbcbc, 0xffc6c6c6, 0xffd0d0d0, 0xffdadada, 0xffe4e4e4, 0xffeeeeee }; }
40.607692
111
0.776283
[ "vector" ]
5c41f8e239cf035478858688a9fd7e4b6d5bbecc
15,958
cpp
C++
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zimage_tmpl.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zimage_tmpl.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zimage_tmpl.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
#include <QtConcurrentRun> template<class T> void ZImage::setBinaryData(const T *data, T bg, int threshold) { if (threshold < 0) { int i, j; for (j = 0; j < height(); j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { uint8 value = '\0'; if (*data++ != bg) { value = '\xff'; } *line++ = value; *line++ = value; *line++ = value; *line++ = '\xff'; } } } else { int i, j; for (j = 0; j < height(); j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { if (*data > threshold) { *line++ = '\0'; *line++ = '\0'; *line++ = '\xff'; *line++ = '\xff'; ++data; } else { uint8 value = '\0'; if (*data++ != bg) { value = '\xff'; } *line++ = value; *line++ = value; *line++ = value; *line++ = '\xff'; } } } } } template<class T> void ZImage::setData(const T *data, double scale, double offset, int threshold) { if (scale == 1.0 && offset == 0.0) { if (threshold < 0) { int i, j; int w = width(); for (j = 0; j < height(); j++) { uchar *line = scanLine(j); for (i = 0; i < w; i++) { memset(line, *data++, 3); line += 3; *line++ = '\xff'; } } } else { int i, j; for (j = 0; j < height(); j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { if (*data > threshold) { *line++ = '\0'; *line++ = '\0'; *line++ = '\xff'; ++data; } else { *line++ = *data; *line++ = *data; *line++ = *data++; } *line++ = '\xff'; } } } return; } if (threshold < 0) { int i, j; for (j = 0; j < height(); j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { double value = scale * (*data++) + offset; uint8 v; if (value <= 0.0) { v = '\0'; } else if (value >= 255.0) { v = '\xff'; } else { v = (uint8) value; } memset(line, v, 3); line += 4; /* *line++ = v; *line++ = v; *line++ = v; *line++ = '\xff'; */ } } } else { int i, j; for (j = 0; j < height(); j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { if (*data > threshold) { *line++ = '\0'; *line++ = '\0'; *line++ = '\xff'; ++data; } else { double value = scale * (*data++) + offset; uint8 v; if (value <= 0.0) { v = '\0'; } else if (value >= 255.0) { v = '\xff'; } else { v = (uint8) value; } *line++ = v; *line++ = v; *line++ = v; } *line++ = '\xff'; } } } } template<class T> void ZImage::set3ChannelData(const T *data0, double scale0, double offset0, const T *data1, double scale1, double offset1, const T *data2, double scale2, double offset2, uint8_t alpha) { if (scale0 == 1.0 && offset0 == 0.0 && scale1 == 1.0 && offset1 == 0.0 && scale2 == 1.0 && offset2 == 0.0) { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { *line++ = (uint8)(*data2++); *line++ = (uint8)(*data1++); *line++ = (uint8)(*data0++); *line++ = alpha; //line++; } } } else { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { double value = scale2 * (*data2++) + offset2; uint8 v; if (value <= 0.0) { v = '\0'; } else if (value >= 255.0) { v = '\xff'; } else { v = (uint8) value; } *line++ = v; value = scale1 * (*data1++) + offset1; if (value <= 0.0) { v = '\0'; } else if (value >= 255.0) { v = '\xff'; } else { v = (uint8) value; } *line++ = v; value = scale0 * (*data0++) + offset0; if (value <= 0.0) { v = '\0'; } else if (value >= 255.0) { v = '\xff'; } else { v = (uint8) value; } *line++ = v; //*line++ = '\xff'; line++; } } } } template<class T> void ZImage::set2ChannelData(const T *data0, double scale0, double offset0, const T *data1, double scale1, double offset1, uint8_t alpha) { if (scale0 == 1.0 && offset0 == 0.0 && scale1 == 1.0 && offset1 == 0.0) { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { *line++ = '\0'; *line++ = (uint8)(*data1++); *line++ = (uint8)(*data0++); *line++ = alpha; } } } else { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { uint8 v = '\0'; *line++ = v; double value = scale1 * (*data1++) + offset1; if (value <= 0.0) { v = '\0'; } else if (value >= 255.0) { v = '\xff'; } else { v = (uint8) value; } *line++ = v; value = scale0 * (*data0++) + offset0; if (value <= 0.0) { v = '\0'; } else if (value >= 255.0) { v = '\xff'; } else { v = (uint8) value; } *line++ = v; *line++ = alpha; //line++; } } } } template<typename T> void ZImage::setData(const ZImage::DataSource<T> &source, int threshold, bool useMultithread) { if (source.color == glm::vec3(1.f,1.f,1.f)) { setData(source.data, source.scale, source.offset, threshold); return; } if (useMultithread) { int numBlock = std::min(height(), 16); int blockHeight = height() / numBlock; std::vector<QFuture<void> > res(numBlock); for (int i=0; i<numBlock; ++i) { int startLine = i * blockHeight; int endLine = (i+1) * blockHeight; if (i == numBlock - 1) endLine = height(); res[i] = QtConcurrent::run(this, &ZImage::setDataBlock<T>, source, startLine, endLine, threshold); } for (int i=0; i<numBlock; ++i) res[i].waitForFinished(); return; } const T* data = source.data; float scale = source.scale; float offset = source.offset; glm::vec3 color = glm::vec3(source.color.b, source.color.g, source.color.r); if (scale == 1.f && offset == 0.f) { if (threshold < 0) { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { glm::col3 col3 = glm::col3(color * (float)(*data++)); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = '\xff'; } } } else { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { if (*data > threshold) { *line++ = '\0'; *line++ = '\0'; *line++ = '\xff'; *line++ = '\xff'; ++data; } else { glm::col3 col3 = glm::col3(color * (float)(*data++)); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = '\xff'; } } } } return; } if (threshold < 0) { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { glm::col3 col3 = glm::col3(glm::clamp(color * (scale * (*data++) + offset), glm::vec3(0.f), glm::vec3(255.f))); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = '\xff'; } } } else { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { if (*data > threshold) { *line++ = '\0'; *line++ = '\0'; *line++ = '\xff'; *line++ = '\xff'; ++data; } else { glm::col3 col3 = glm::col3(glm::clamp(color * (scale * (*data++) + offset), glm::vec3(0.f), glm::vec3(255.f))); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = '\xff'; } } } } } template<typename T> void ZImage::setData(const std::vector<ZImage::DataSource<T> > &sources, uint8_t alpha, bool useMultithread) { if (useMultithread) { int numBlock = std::min(height(), 16); int blockHeight = height() / numBlock; std::vector<QFuture<void> > res(numBlock); for (int i=0; i<numBlock; ++i) { int startLine = i * blockHeight; int endLine = (i+1) * blockHeight; if (i == numBlock - 1) endLine = height(); res[i] = QtConcurrent::run(this, &ZImage::setDataBlockMS<T>, sources, startLine, endLine, alpha); } for (int i=0; i<numBlock; ++i) res[i].waitForFinished(); return; } std::vector<ZImage::DataSource<T> > allSources = sources; bool needScaleAndClamp = false; for (size_t i=0; i<allSources.size(); ++i) { std::swap(allSources[i].color.r, allSources[i].color.b); if (allSources[i].scale != 1.f || allSources[i].offset != 0.f) { needScaleAndClamp = true; } } if (!needScaleAndClamp) { for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { glm::col3 col3 = glm::col3(allSources[0].color * (float)(*(allSources[0].data)++)); for (size_t ch=1; ch<allSources.size(); ++ch) col3 = glm::max(col3, glm::col3(allSources[ch].color * (float)(*(allSources[ch].data)++))); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = alpha; } } return; } for (int j = 0; j < height(); j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { glm::col3 col3 = glm::col3(glm::clamp(allSources[0].color * (allSources[0].scale * (*(allSources[0].data)++) + allSources[0].offset), glm::vec3(0.f), glm::vec3(255.f))); for (size_t ch=1; ch<allSources.size(); ++ch) col3 = glm::max(col3, glm::col3(glm::clamp(allSources[ch].color * (allSources[ch].scale * (*(allSources[ch].data)++) + allSources[ch].offset), glm::vec3(0.f), glm::vec3(255.f)))); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = alpha; } } } template<typename T> void ZImage::setDataBlock(const ZImage::DataSource<T> &source, int startLine, int endLine, int threshold) { const T* data = source.data + startLine * width(); float scale = source.scale; float offset = source.offset; glm::vec3 color = glm::vec3(source.color.b, source.color.g, source.color.r); if (scale == 1.f && offset == 0.f) { if (threshold < 0) { int i, j; for (j = startLine; j < endLine; j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { glm::col3 col3 = glm::col3(color * (float)(*data++)); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = '\xff'; } } } else { int i, j; for (j = startLine; j < endLine; j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { if (*data > threshold) { *line++ = '\0'; *line++ = '\0'; *line++ = '\xff'; *line++ = '\xff'; ++data; } else { glm::col3 col3 = glm::col3(color * (float)(*data++)); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = '\xff'; } } } } return; } if (threshold < 0) { int i, j; for (j = startLine; j < endLine; j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { glm::col3 col3 = glm::col3(glm::clamp(color * (scale * (*data++) + offset), glm::vec3(0.f), glm::vec3(255.f))); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = '\xff'; } } } else { int i, j; for (j = startLine; j < endLine; j++) { uchar *line = scanLine(j); for (i = 0; i < width(); i++) { if (*data > threshold) { *line++ = '\0'; *line++ = '\0'; *line++ = '\xff'; *line++ = '\xff'; ++data; } else { glm::col3 col3 = glm::col3(glm::clamp(color * (scale * (*data++) + offset), glm::vec3(0.f), glm::vec3(255.f))); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = '\xff'; } } } } } template<typename T> void ZImage::setDataBlockMS(const std::vector<ZImage::DataSource<T> > &sources, int startLine, int endLine, uint8_t alpha) { std::vector<ZImage::DataSource<T> > allSources = sources; bool needScaleAndClamp = false; for (size_t i=0; i<allSources.size(); ++i) { allSources[i].data += startLine * width(); std::swap(allSources[i].color.r, allSources[i].color.b); if (allSources[i].scale != 1.f || allSources[i].offset != 0.f) { needScaleAndClamp = true; } } if (!needScaleAndClamp) { for (int j = startLine; j < endLine; j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { glm::col3 col3 = glm::col3(allSources[0].color * (float)(*(allSources[0].data)++)); for (size_t ch=1; ch<allSources.size(); ++ch) col3 = glm::max(col3, glm::col3(allSources[ch].color * (float)(*(allSources[ch].data)++))); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = alpha; } } return; } for (int j = startLine; j < endLine; j++) { uchar *line = scanLine(j); for (int i = 0; i < width(); i++) { glm::col3 col3 = glm::col3(glm::clamp(allSources[0].color * (allSources[0].scale * (*(allSources[0].data)++) + allSources[0].offset), glm::vec3(0.f), glm::vec3(255.f))); for (size_t ch=1; ch<allSources.size(); ++ch) col3 = glm::max(col3, glm::col3(glm::clamp(allSources[ch].color * (allSources[ch].scale * (*(allSources[ch].data)++) + allSources[ch].offset), glm::vec3(0.f), glm::vec3(255.f)))); *line++ = col3[0]; *line++ = col3[1]; *line++ = col3[2]; *line++ = alpha; } } }
28.496429
116
0.407695
[ "vector" ]
5c459521e0b66ad2c81b2071e1aa932a73b2b952
1,083
cpp
C++
Atcoder/90Problems/003.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
Atcoder/90Problems/003.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
null
null
null
Atcoder/90Problems/003.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const int TMX = 1 << 18; const long long llINF = 1e18+10; const long long mod = 1e9+7; const long long hashmod = 100003; const int MAXN = 100000; const int MAXM = 1000000; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef pair <ll,ll> pl; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int n,d[100005]; vec v[100005]; void dfs(int x,int pr) { for(int i : v[x]) { if(i == pr) continue; d[i] = d[x]+1; dfs(i,x); } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; for(int i = 1;i < n;i++) { int x,y; cin >> x >> y; v[x].pb(y), v[y].pb(x); } dfs(1,-1); int mx = 1; for(int i = 1;i <= n;i++) { if(d[mx] < d[i]) mx = i; } d[mx] = 0; dfs(mx,-1); mx = 1; for(int i = 1;i <= n;i++) { if(d[mx] < d[i]) mx = i; } cout << d[mx]+1; }
19.690909
46
0.597415
[ "vector" ]
5c523d60edb075a293ccb0c6e787fe320883bbaa
776
cpp
C++
leetcode/l0416.cpp
Victrid/Atlas
da25d50424790e571f29b66fc815245c1093798c
[ "MIT" ]
1
2020-01-19T16:00:07.000Z
2020-01-19T16:00:07.000Z
leetcode/l0416.cpp
Victrid/Atlas
da25d50424790e571f29b66fc815245c1093798c
[ "MIT" ]
null
null
null
leetcode/l0416.cpp
Victrid/Atlas
da25d50424790e571f29b66fc815245c1093798c
[ "MIT" ]
null
null
null
#include "lc.hpp" //fast and neat class Solution { public: bool canPartition(vector<int>& nums) { auto it = nums.begin(); int sum = 0; for (; it < nums.end(); it++) sum += *it; if (sum & 1) return false; //建立一个一维bool数组 bool* boolarray = new bool[sum + 1](); sum >>= 1; for (it = nums.begin(); it < nums.end(); it++) { //原本为true对应的和加新增值置true for (int j = sum; j >= 0; j--) if (boolarray[j]) boolarray[j + *it] = 1; //自己置true boolarray[*it] = 1; //判断目标和 if (boolarray[sum]) return true; } //目标和格子仍然为false,我们返回false。 return false; } };
26.758621
56
0.429124
[ "vector" ]
5c56d2c17ddc4c5c9efa8b438dacdcd0a1b3a6f7
21,181
cpp
C++
src/env.cpp
GerHobbelt/lmdb-store
3d2ec6adb43e478faad708a27a3354a69669046d
[ "MIT" ]
null
null
null
src/env.cpp
GerHobbelt/lmdb-store
3d2ec6adb43e478faad708a27a3354a69669046d
[ "MIT" ]
null
null
null
src/env.cpp
GerHobbelt/lmdb-store
3d2ec6adb43e478faad708a27a3354a69669046d
[ "MIT" ]
null
null
null
#include "lmdb-js.h" using namespace Napi; #define IGNORE_NOTFOUND (1) env_tracking_t* EnvWrap::envTracking = EnvWrap::initTracking(); env_tracking_t* EnvWrap::initTracking() { env_tracking_t* tracking = new env_tracking_t; tracking->envsLock = new pthread_mutex_t; pthread_mutex_init(tracking->envsLock, nullptr); return tracking; } EnvWrap::EnvWrap(const CallbackInfo& info) : ObjectWrap<EnvWrap>(info) { int rc; rc = mdb_env_create(&(this->env)); if (rc != 0) { mdb_env_close(this->env); throwLmdbError(info.Env(), rc); return; } this->currentWriteTxn = nullptr; this->currentReadTxn = nullptr; this->writeTxn = nullptr; this->writeWorker = nullptr; this->readTxnRenewed = false; this->writingLock = new pthread_mutex_t; this->writingCond = new pthread_cond_t; info.This().As<Object>().Set("address", Number::New(info.Env(), (size_t) this)); pthread_mutex_init(this->writingLock, nullptr); pthread_cond_init(this->writingCond, nullptr); } EnvWrap::~EnvWrap() { // Close if not closed already closeEnv(); pthread_mutex_destroy(this->writingLock); pthread_cond_destroy(this->writingCond); } void EnvWrap::cleanupStrayTxns() { if (this->currentWriteTxn) { mdb_txn_abort(this->currentWriteTxn->txn); this->currentWriteTxn->removeFromEnvWrap(); } /* while (this->workers.size()) { // enable this if we do need to do worker cleanup AsyncWorker *worker = *this->workers.begin(); fprintf(stderr, "Deleting running worker\n"); delete worker; }*/ while (this->readTxns.size()) { TxnWrap *tw = *this->readTxns.begin(); mdb_txn_abort(tw->txn); tw->removeFromEnvWrap(); } } class SyncWorker : public AsyncWorker { public: SyncWorker(EnvWrap* env, const Function& callback) : AsyncWorker(callback), env(env) { //env->workers.push_back(this); } /*~SyncWorker() { for (auto workerRef = env->workers.begin(); workerRef != env->workers.end(); ) { if (this == *workerRef) { env->workers.erase(workerRef); } } }*/ void OnOK() { napi_value result; // we use direct napi call here because node-addon-api interface with throw a fatal error if a worker thread is terminating napi_call_function(Env(), Env().Undefined(), Callback().Value(), 0, {}, &result); } void Execute() { int rc = mdb_env_sync(env->env, 1); if (rc != 0) { SetError(mdb_strerror(rc)); } } private: EnvWrap* env; }; class CopyWorker : public AsyncWorker { public: CopyWorker(MDB_env* env, std::string inPath, int flags, const Function& callback) : AsyncWorker(callback), env(env), path(inPath), flags(flags) { } ~CopyWorker() { //free(path); } void Execute() { int rc = mdb_env_copy2(env, path.c_str(), flags); if (rc != 0) { fprintf(stderr, "Error on copy code: %u\n", rc); SetError("Error on copy"); } } private: MDB_env* env; std::string path; int flags; }; MDB_txn* EnvWrap::getReadTxn() { MDB_txn* txn = writeTxn ? writeTxn->txn : nullptr; if (txn) return txn; txn = currentReadTxn; if (readTxnRenewed) return txn; if (txn) mdb_txn_renew(txn); else { fprintf(stderr, "No current read transaction available"); return nullptr; } readTxnRenewed = true; return txn; } #ifdef MDB_RPAGE_CACHE static int encfunc(const MDB_val* src, MDB_val* dst, const MDB_val* key, int encdec) { chacha8(src->mv_data, src->mv_size, (uint8_t*) key[0].mv_data, (uint8_t*) key[1].mv_data, (char*)dst->mv_data); return 0; } #endif void cleanup(void* data) { ((EnvWrap*) data)->closeEnv(); } Napi::Value EnvWrap::open(const CallbackInfo& info) { int rc; // Get the wrapper if (!this->env) { return throwError(info.Env(), "The environment is already closed."); } Object options = info[0].As<Object>(); int flags = info[1].As<Number>(); int jsFlags = info[2].As<Number>(); Compression* compression = nullptr; Napi::Value compressionOption = options.Get("compression"); if (compressionOption.IsObject()) { napi_unwrap(info.Env(), compressionOption, (void**)&compression); this->compression = compression; } void* keyBuffer; Napi::Value keyBytesValue = options.Get("keyBytes"); if (!keyBytesValue.IsTypedArray()) fprintf(stderr, "Invalid key buffer\n"); size_t keyBufferLength; napi_get_typedarray_info(info.Env(), keyBytesValue, nullptr, &keyBufferLength, &keyBuffer, nullptr, nullptr); setFlagFromValue(&jsFlags, SEPARATE_FLUSHED, "separateFlushed", false, options); String path = options.Get("path").As<String>(); std::string pathString = path.Utf8Value(); /*int pathLength = path.Length(); if (bytes != pathLength) fprintf(stderr, "Bytes do not match %u %u", bytes, pathLength); if (pathBytes[bytes]) fprintf(stderr, "String is not null-terminated");*/ // Parse the maxDbs option int maxDbs = 12; Napi::Value option = options.Get("maxDbs"); if (option.IsNumber()) maxDbs = option.As<Number>(); mdb_size_t mapSize = 0; // Parse the mapSize option option = options.Get("mapSize"); if (option.IsNumber()) mapSize = option.As<Number>().Int64Value(); int pageSize = 4096; // Parse the mapSize option option = options.Get("pageSize"); if (option.IsNumber()) pageSize = option.As<Number>(); int maxReaders = 126; // Parse the mapSize option option = options.Get("maxReaders"); if (option.IsNumber()) maxReaders = option.As<Number>(); Napi::Value encryptionKey = options.Get("encryptionKey"); std::string encryptKey; if (!encryptionKey.IsUndefined()) { encryptKey = encryptionKey.As<String>().Utf8Value(); if (encryptKey.length() != 32) { return throwError(info.Env(), "Encryption key must be 32 bytes long"); } #ifndef MDB_RPAGE_CACHE return throwError(info.Env(), "Encryption not supported with data format version 1"); #endif } rc = this->openEnv(flags, jsFlags, (const char*)pathString.c_str(), (char*) keyBuffer, compression, maxDbs, maxReaders, mapSize, pageSize, encryptKey.empty() ? nullptr : (char*)encryptKey.c_str()); //delete[] pathBytes; if (rc < 0) return throwLmdbError(info.Env(), rc); napi_add_env_cleanup_hook(info.Env(), cleanup, this); return info.Env().Undefined(); } int EnvWrap::openEnv(int flags, int jsFlags, const char* path, char* keyBuffer, Compression* compression, int maxDbs, int maxReaders, mdb_size_t mapSize, int pageSize, char* encryptionKey) { pthread_mutex_lock(envTracking->envsLock); this->keyBuffer = keyBuffer; this->compression = compression; this->jsFlags = jsFlags; MDB_env* env = this->env; for (auto envPath = envTracking->envs.begin(); envPath != envTracking->envs.end();) { char* existingPath = envPath->path; if (!strcmp(existingPath, path)) { envPath->count++; mdb_env_close(env); this->env = envPath->env; pthread_mutex_unlock(envTracking->envsLock); return 0; } ++envPath; } int rc; rc = mdb_env_set_maxdbs(env, maxDbs); if (rc) goto fail; rc = mdb_env_set_maxreaders(env, maxReaders); if (rc) goto fail; rc = mdb_env_set_mapsize(env, mapSize); if (rc) goto fail; #ifdef MDB_RPAGE_CACHE rc = mdb_env_set_pagesize(env, pageSize); if (rc) goto fail; #endif if ((size_t) encryptionKey > 100) { MDB_val enckey; enckey.mv_data = encryptionKey; enckey.mv_size = 32; #ifdef MDB_RPAGE_CACHE rc = mdb_env_set_encrypt(this->env, encfunc, &enckey, 0); #else rc = -1; #endif if (rc != 0) goto fail; } if (flags & MDB_OVERLAPPINGSYNC) { flags |= MDB_PREVSNAPSHOT; } if (flags & MDB_NOLOCK) { fprintf(stderr, "You chose to use MDB_NOLOCK which is not officially supported by node-lmdb. You have been warned!\n"); } // Set MDB_NOTLS to enable multiple read-only transactions on the same thread (in this case, the nodejs main thread) flags |= MDB_NOTLS; // TODO: make file attributes configurable // *String::Utf8Value(Isolate::GetCurrent(), path) rc = mdb_env_open(env, path, flags, 0664); mdb_env_get_flags(env, (unsigned int*) &flags); if (rc != 0) { mdb_env_close(env); goto fail; } SharedEnv envPath; envPath.path = strdup(path); envPath.env = env; envPath.count = 1; envPath.deleteOnClose = jsFlags & DELETE_ON_CLOSE; envTracking->envs.push_back(envPath); pthread_mutex_unlock(envTracking->envsLock); return 0; fail: pthread_mutex_unlock(envTracking->envsLock); this->env = nullptr; return rc; } Napi::Value EnvWrap::getMaxKeySize(const CallbackInfo& info) { return Number::New(info.Env(), mdb_env_get_maxkeysize(this->env)); } NAPI_FUNCTION(getEnvFlags) { ARGS(1) EnvWrap* ew; GET_INT64_ARG(ew, 0); unsigned int envFlags; mdb_env_get_flags(ew->env, &envFlags); RETURN_INT64(envFlags); } NAPI_FUNCTION(setJSFlags) { ARGS(2) EnvWrap* ew; GET_INT64_ARG(ew, 0); int64_t jsFlags; GET_INT64_ARG(jsFlags, 1); ew->jsFlags = jsFlags; RETURN_UNDEFINED; } #ifdef _WIN32 // TODO: I think we should switch to DeleteFileW (but have to convert to UTF16) #define unlink DeleteFileA #else #include <unistd.h> #endif void SharedEnv::finish(bool close) { unsigned int envFlags; // This is primarily useful for detecting termination of threads and sync'ing on their termination mdb_env_get_flags(env, &envFlags); if (envFlags & MDB_OVERLAPPINGSYNC) { mdb_env_sync(env, 1); } if (close) { mdb_env_close(env); if (deleteOnClose) { unlink(path); //unlink(strcat(envPath->path, "-lock")); } } } NAPI_FUNCTION(EnvWrap::onExit) { // close all the environments pthread_mutex_lock(envTracking->envsLock); for (auto envPath : envTracking->envs) { envPath.finish(false); } pthread_mutex_unlock(envTracking->envsLock); napi_value returnValue; RETURN_UNDEFINED; } NAPI_FUNCTION(getEnvsPointer) { napi_value returnValue; RETURN_INT64((int64_t) EnvWrap::envTracking); } NAPI_FUNCTION(setEnvsPointer) { // If another version of lmdb-js is running, switch to using its list of envs ARGS(1) env_tracking_t* adoptedTracking; GET_INT64_ARG(adoptedTracking, 0); // copy any existing ones over to the central one adoptedTracking->envs.assign(EnvWrap::envTracking->envs.begin(), EnvWrap::envTracking->envs.end()); EnvWrap::envTracking = adoptedTracking; RETURN_UNDEFINED; } void EnvWrap::closeEnv() { if (!env) return; cleanupStrayTxns(); pthread_mutex_lock(envTracking->envsLock); for (auto envPath = envTracking->envs.begin(); envPath != envTracking->envs.end(); ) { if (envPath->env == env) { envPath->count--; if (envPath->count <= 0) { // last thread using it, we can really close it now envPath->finish(true); envTracking->envs.erase(envPath); } break; } ++envPath; } pthread_mutex_unlock(envTracking->envsLock); env = nullptr; } Napi::Value EnvWrap::close(const CallbackInfo& info) { if (!this->env) { return throwError(info.Env(), "The environment is already closed."); } napi_remove_env_cleanup_hook(info.Env(), cleanup, this); this->closeEnv(); return info.Env().Undefined(); } Napi::Value EnvWrap::stat(const CallbackInfo& info) { if (!this->env) { return throwError(info.Env(), "The environment is already closed."); } int rc; MDB_stat stat; rc = mdb_env_stat(this->env, &stat); if (rc != 0) { return throwLmdbError(info.Env(), rc); } Object stats = Object::New(info.Env()); stats.Set("pageSize", Number::New(info.Env(), stat.ms_psize)); stats.Set("treeDepth", Number::New(info.Env(), stat.ms_depth)); stats.Set("treeBranchPageCount", Number::New(info.Env(), stat.ms_branch_pages)); stats.Set("treeLeafPageCount", Number::New(info.Env(), stat.ms_leaf_pages)); stats.Set("entryCount", Number::New(info.Env(), stat.ms_entries)); stats.Set("overflowPages", Number::New(info.Env(), stat.ms_overflow_pages)); return stats; } Napi::Value EnvWrap::freeStat(const CallbackInfo& info) { if (!this->env) { return throwError(info.Env(),"The environment is already closed."); } int rc; MDB_stat stat; TxnWrap *txn; napi_unwrap(info.Env(), info[0], (void**)&txn); rc = mdb_stat(txn->txn, 0, &stat); if (rc != 0) { return throwLmdbError(info.Env(), rc); } Object stats = Object::New(info.Env()); stats.Set("pageSize", Number::New(info.Env(), stat.ms_psize)); stats.Set("treeDepth", Number::New(info.Env(), stat.ms_depth)); stats.Set("treeBranchPageCount", Number::New(info.Env(), stat.ms_branch_pages)); stats.Set("treeLeafPageCount", Number::New(info.Env(), stat.ms_leaf_pages)); stats.Set("entryCount", Number::New(info.Env(), stat.ms_entries)); stats.Set("overflowPages", Number::New(info.Env(), stat.ms_overflow_pages)); return stats; } Napi::Value EnvWrap::info(const CallbackInfo& info) { if (!this->env) { return throwError(info.Env(),"The environment is already closed."); } int rc; MDB_envinfo envinfo; rc = mdb_env_info(this->env, &envinfo); if (rc != 0) { return throwLmdbError(info.Env(), rc); } Object stats = Object::New(info.Env()); stats.Set("mapSize", Number::New(info.Env(), envinfo.me_mapsize)); stats.Set("lastPageNumber", Number::New(info.Env(), envinfo.me_last_pgno)); stats.Set("lastTxnId", Number::New(info.Env(), envinfo.me_last_txnid)); stats.Set("maxReaders", Number::New(info.Env(), envinfo.me_maxreaders)); stats.Set("numReaders", Number::New(info.Env(), envinfo.me_numreaders)); return stats; } Napi::Value EnvWrap::readerCheck(const CallbackInfo& info) { if (!this->env) { return throwError(info.Env(), "The environment is already closed."); } int rc, dead; rc = mdb_reader_check(this->env, &dead); if (rc != 0) { return throwLmdbError(info.Env(), rc); } return Number::New(info.Env(), dead); } Array readerStrings; MDB_msg_func* printReaders = ([](const char* message, void* env) -> int { readerStrings.Set(readerStrings.Length(), String::New(*(Env*)env, message)); return 0; }); Napi::Value EnvWrap::readerList(const CallbackInfo& info) { if (!this->env) { return throwError(info.Env(), "The environment is already closed."); } readerStrings = Array::New(info.Env()); int rc; Napi::Env env = info.Env(); rc = mdb_reader_list(this->env, printReaders, &env); if (rc != 0) { return throwLmdbError(info.Env(), rc); } return readerStrings; } Napi::Value EnvWrap::copy(const CallbackInfo& info) { if (!this->env) { return throwError(info.Env(), "The environment is already closed."); } // Check that the correct number/type of arguments was given. if (!info[0].IsString()) { return throwError(info.Env(), "Call env.copy(path, compact?, callback) with a file path."); } if (!info[info.Length() - 1].IsFunction()) { return throwError(info.Env(), "Call env.copy(path, compact?, callback) with a file path."); } int flags = 0; if (info.Length() > 1 && info[1].IsBoolean() && info[1].ToBoolean()) { flags = MDB_CP_COMPACT; } CopyWorker* worker = new CopyWorker( this->env, info[0].As<String>().Utf8Value(), flags, info[info.Length() > 2 ? 2 : 1].As<Function>() ); worker->Queue(); return info.Env().Undefined(); } Napi::Value EnvWrap::beginTxn(const CallbackInfo& info) { int flags = info[0].As<Number>(); if (!(flags & MDB_RDONLY)) { MDB_env *env = this->env; unsigned int envFlags; mdb_env_get_flags(env, &envFlags); MDB_txn *txn; if (this->writeTxn) txn = this->writeTxn->txn; else if (this->writeWorker) { // try to acquire the txn from the current batch txn = this->writeWorker->AcquireTxn(&flags); } else { pthread_mutex_lock(this->writingLock); txn = nullptr; } if (txn) { if (flags & TXN_ABORTABLE) { if (envFlags & MDB_WRITEMAP) flags &= ~TXN_ABORTABLE; else { // child txn mdb_txn_begin(env, txn, flags & 0xf0000, &txn); TxnTracked* childTxn = new TxnTracked(txn, flags); childTxn->parent = this->writeTxn; this->writeTxn = childTxn; return info.Env().Undefined(); } } } else { mdb_txn_begin(env, nullptr, flags & 0xf0000, &txn); flags |= TXN_ABORTABLE; } this->writeTxn = new TxnTracked(txn, flags); return info.Env().Undefined(); } if (info.Length() > 1) { fprintf(stderr, "Invalid number of arguments"); } else { fprintf(stderr, "Invalid number of arguments"); } return info.Env().Undefined(); } Napi::Value EnvWrap::commitTxn(const CallbackInfo& info) { TxnTracked *currentTxn = this->writeTxn; //fprintf(stderr, "commitTxn %p\n", currentTxn); int rc = 0; if (currentTxn->flags & TXN_ABORTABLE) { //fprintf(stderr, "txn_commit\n"); rc = mdb_txn_commit(currentTxn->txn); } this->writeTxn = currentTxn->parent; if (!this->writeTxn) { //fprintf(stderr, "unlock txn\n"); if (this->writeWorker) this->writeWorker->UnlockTxn(); else pthread_mutex_unlock(this->writingLock); } delete currentTxn; if (rc) throwLmdbError(info.Env(), rc); return info.Env().Undefined(); } Napi::Value EnvWrap::abortTxn(const CallbackInfo& info) { TxnTracked *currentTxn = this->writeTxn; if (currentTxn->flags & TXN_ABORTABLE) { mdb_txn_abort(currentTxn->txn); } else { throwError(info.Env(), "Can not abort this transaction"); } this->writeTxn = currentTxn->parent; if (!this->writeTxn) { if (this->writeWorker) this->writeWorker->UnlockTxn(); else pthread_mutex_unlock(this->writingLock); } delete currentTxn; return info.Env().Undefined(); } /*Napi::Value EnvWrap::openDbi(const CallbackInfo& info) { const unsigned argc = 5; Local<Value> argv[argc] = { info.This(), info[0], info[1], info[2], info[3] }; Nan::MaybeLocal<Object> maybeInstance = Nan::NewInstance(Nan::New(*dbiCtor), argc, argv); // Check if database could be opened if ((maybeInstance.IsEmpty())) { // The maybeInstance is empty because the dbiCtor called throwError. // No need to call that here again, the user will get the error thrown there. return; } Local<Object> instance = maybeInstance.ToLocalChecked(); DbiWrap *dw = Nan::ObjectWrap::Unwrap<DbiWrap>(instance); if (dw->dbi == (MDB_dbi) 0xffffffff) info.GetReturnValue().Set(Nan::Undefined()); else info.GetReturnValue().Set(instance); }*/ Napi::Value EnvWrap::sync(const CallbackInfo& info) { if (!this->env) { return throwError(info.Env(), "The environment is already closed."); } if (info.Length() > 0) { SyncWorker* worker = new SyncWorker(this, info[0].As<Function>()); worker->Queue(); } else { int rc = mdb_env_sync(this->env, 1); if (rc != 0) { return throwLmdbError(info.Env(), rc); } } return info.Env().Undefined(); } Napi::Value EnvWrap::resetCurrentReadTxn(const CallbackInfo& info) { mdb_txn_reset(this->currentReadTxn); this->readTxnRenewed = false; return info.Env().Undefined(); } void EnvWrap::setupExports(Napi::Env env, Object exports) { // EnvWrap: Prepare constructor template Function EnvClass = ObjectWrap<EnvWrap>::DefineClass(env, "Env", { EnvWrap::InstanceMethod("open", &EnvWrap::open), EnvWrap::InstanceMethod("getMaxKeySize", &EnvWrap::getMaxKeySize), EnvWrap::InstanceMethod("close", &EnvWrap::close), EnvWrap::InstanceMethod("beginTxn", &EnvWrap::beginTxn), EnvWrap::InstanceMethod("commitTxn", &EnvWrap::commitTxn), EnvWrap::InstanceMethod("abortTxn", &EnvWrap::abortTxn), EnvWrap::InstanceMethod("sync", &EnvWrap::sync), EnvWrap::InstanceMethod("startWriting", &EnvWrap::startWriting), EnvWrap::InstanceMethod("stat", &EnvWrap::stat), EnvWrap::InstanceMethod("freeStat", &EnvWrap::freeStat), EnvWrap::InstanceMethod("info", &EnvWrap::info), EnvWrap::InstanceMethod("readerCheck", &EnvWrap::readerCheck), EnvWrap::InstanceMethod("readerList", &EnvWrap::readerList), EnvWrap::InstanceMethod("copy", &EnvWrap::copy), //EnvWrap::InstanceMethod("detachBuffer", &EnvWrap::detachBuffer), EnvWrap::InstanceMethod("resetCurrentReadTxn", &EnvWrap::resetCurrentReadTxn), }); EXPORT_NAPI_FUNCTION("compress", compress); EXPORT_NAPI_FUNCTION("write", write); EXPORT_NAPI_FUNCTION("onExit", onExit); EXPORT_NAPI_FUNCTION("getEnvsPointer", getEnvsPointer); EXPORT_NAPI_FUNCTION("setEnvsPointer", setEnvsPointer); EXPORT_NAPI_FUNCTION("getEnvFlags", getEnvFlags); EXPORT_NAPI_FUNCTION("setJSFlags", setJSFlags); //envTpl->InstanceTemplate()->SetInternalFieldCount(1); exports.Set("Env", EnvClass); } // This file contains code from the node-lmdb project // Copyright (c) 2013-2017 Timur Kristóf // Copyright (c) 2021 Kristopher Tate // Licensed to you under the terms of the MIT license // // 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.
30.608382
198
0.703083
[ "object" ]
5c588ee1d45a2fde54fd87e69cbff2f103a6ea79
28,480
cpp
C++
geoAutorift/geogrid/src/geogrid.cpp
NieYi/autoRIFT
d442f4e5c96c4f480106c934c3afdebd607c6cb5
[ "Apache-2.0" ]
1
2020-04-26T14:36:22.000Z
2020-04-26T14:36:22.000Z
geoAutorift/geogrid/src/geogrid.cpp
NieYi/autoRIFT
d442f4e5c96c4f480106c934c3afdebd607c6cb5
[ "Apache-2.0" ]
null
null
null
geoAutorift/geogrid/src/geogrid.cpp
NieYi/autoRIFT
d442f4e5c96c4f480106c934c3afdebd607c6cb5
[ "Apache-2.0" ]
null
null
null
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright 2019 California Institute of Technology. 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. * * United States Government Sponsorship acknowledged. This software is subject to * U.S. export control laws and regulations and has been classified as 'EAR99 NLR' * (No [Export] License Required except when exporting to an embargoed country, * end user, or in support of a prohibited end use). By downloading this software, * the user agrees to comply with all applicable U.S. export laws and regulations. * The user has the responsibility to obtain export licenses, or other export * authority as may be required before exporting this software to any 'EAR99' * embargoed foreign country or citizen of those countries. * * Authors: Piyush Agram, Yang Lei *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "geogrid.h" #include <gdal.h> #include <gdal_priv.h> #include <iostream> #include <complex> #include <cmath> extern "C" { #include "linalg3.h" #include "geometry.h" } void geoGrid::geogrid() { //Some constants double deg2rad = M_PI/180.0; //For now print inputs that were obtained std::cout << "\nRadar parameters: \n"; std::cout << "Range: " << startingRange << " " << dr << "\n"; std::cout << "Azimuth: " << sensingStart << " " << prf << "\n"; std::cout << "Dimensions: " << nPixels << " " << nLines << "\n"; std::cout << "\nMap inputs: \n"; std::cout << "EPSG: " << epsgcode << "\n"; std::cout << "Repeat Time: " << dt << "\n"; std::cout << "XLimits: " << xmin << " " << xmax << "\n"; std::cout << "YLimits: " << ymin << " " << ymax << "\n"; std::cout << "Extent in km: " << (xmax - xmin)/1000. << " " << (ymax - ymin)/1000. << "\n"; std::cout << "DEM: " << demname << "\n"; std::cout << "Velocities: " << vxname << " " << vyname << "\n"; std::cout << "Slopes: " << dhdxname << " " << dhdyname << "\n"; std::cout << "\nOutputs: \n"; std::cout << "Window locations: " << pixlinename << "\n"; std::cout << "Window offsets: " << offsetname << "\n"; std::cout << "Window rdr_off2vel_x vector: " << ro2vx_name << "\n"; std::cout << "Window rdr_off2vel_y vector: " << ro2vy_name << "\n"; std::cout << "\nStarting processing .... \n"; //Startup GDAL GDALAllRegister(); //DEM related information GDALDataset* demDS = NULL; GDALDataset* sxDS = NULL; GDALDataset* syDS = NULL; GDALDataset* vxDS = NULL; GDALDataset* vyDS = NULL; double geoTrans[6]; demDS = reinterpret_cast<GDALDataset *>(GDALOpenShared(demname.c_str(), GA_ReadOnly)); if (vxname != "") { sxDS = reinterpret_cast<GDALDataset *>(GDALOpenShared(dhdxname.c_str(), GA_ReadOnly)); syDS = reinterpret_cast<GDALDataset *>(GDALOpenShared(dhdyname.c_str(), GA_ReadOnly)); vxDS = reinterpret_cast<GDALDataset *>(GDALOpenShared(vxname.c_str(), GA_ReadOnly)); vyDS = reinterpret_cast<GDALDataset *>(GDALOpenShared(vyname.c_str(), GA_ReadOnly)); } if (demDS == NULL) { std::cout << "Error opening DEM file { " << demname << " }\n"; std::cout << "Exiting with error code .... (101) \n"; GDALDestroyDriverManager(); exit(101); } if (vxname != "") { if (sxDS == NULL) { std::cout << "Error opening x-direction slope file { " << dhdxname << " }\n"; std::cout << "Exiting with error code .... (101) \n"; GDALDestroyDriverManager(); exit(101); } if (syDS == NULL) { std::cout << "Error opening y-direction slope file { " << dhdyname << " }\n"; std::cout << "Exiting with error code .... (101) \n"; GDALDestroyDriverManager(); exit(101); } if (vxDS == NULL) { std::cout << "Error opening x-direction velocity file { " << vxname << " }\n"; std::cout << "Exiting with error code .... (101) \n"; GDALDestroyDriverManager(); exit(101); } if (vyDS == NULL) { std::cout << "Error opening y-direction velocity file { " << vyname << " }\n"; std::cout << "Exiting with error code .... (101) \n"; GDALDestroyDriverManager(); exit(101); } } demDS->GetGeoTransform(geoTrans); int demXSize = demDS->GetRasterXSize(); int demYSize = demDS->GetRasterYSize(); //Get offsets and size to read from DEM int lOff = std::max( std::floor((ymax - geoTrans[3])/geoTrans[5]), 0.); int lCount = std::min( std::ceil((ymin - geoTrans[3])/geoTrans[5]), demYSize-1.) - lOff; int pOff = std::max( std::floor((xmin - geoTrans[0])/geoTrans[1]), 0.); int pCount = std::min( std::ceil((xmax - geoTrans[0])/geoTrans[1]), demXSize-1.) - pOff; std::cout << "Xlimits : " << geoTrans[0] + pOff * geoTrans[1] << " " << geoTrans[0] + (pOff + pCount) * geoTrans[1] << "\n"; std::cout << "Ylimits : " << geoTrans[3] + (lOff + lCount) * geoTrans[5] << " " << geoTrans[3] + lOff * geoTrans[5] << "\n"; std::cout << "Dimensions of geogrid: " << pCount << " x " << lCount << "\n\n"; //Create GDAL Transformers OGRSpatialReference demSRS(nullptr); if (demSRS.importFromEPSG(epsgcode) != 0) { std::cout << "Could not create OGR spatial reference for EPSG code: " << epsgcode << "\n"; GDALClose(demDS); GDALDestroyDriverManager(); exit(102); } OGRSpatialReference llhSRS(nullptr); if (llhSRS.importFromEPSG(4326) != 0) { std::cout << "Could not create OGR spatil reference for EPSG code: 4326 \n"; GDALClose(demDS); GDALDestroyDriverManager(); exit(103); } OGRCoordinateTransformation *fwdTrans = OGRCreateCoordinateTransformation( &demSRS, &llhSRS); OGRCoordinateTransformation *invTrans = OGRCreateCoordinateTransformation( &llhSRS, &demSRS); //WGS84 ellipsoid only cEllipsoid wgs84; wgs84.a = 6378137.0; wgs84.e2 = 0.0066943799901; //Initial guess for solution double tmid = sensingStart + 0.5 * nLines / prf; double satxmid[3]; double satvmid[3]; if (interpolateWGS84Orbit(orbit, tmid, satxmid, satvmid) != 0) { std::cout << "Error with orbit interpolation for setup. \n"; GDALClose(demDS); GDALDestroyDriverManager(); exit(104); } // std::cout << satxmid[0] << " " << satxmid[1] << " " << satxmid[2] << "\n"; std::vector<double> demLine(pCount); std::vector<double> sxLine(pCount); std::vector<double> syLine(pCount); std::vector<double> vxLine(pCount); std::vector<double> vyLine(pCount); GInt32 raster1[pCount]; GInt32 raster2[pCount]; GInt32 raster11[pCount]; GInt32 raster22[pCount]; double raster1a[pCount]; double raster1b[pCount]; // double raster1c[pCount]; double raster2a[pCount]; double raster2b[pCount]; // double raster2c[pCount]; double nodata; double nodata_out; if (vxname != "") { int* pbSuccess = NULL; nodata = vxDS->GetRasterBand(1)->GetNoDataValue(pbSuccess); } nodata_out = -2000000000; const char *pszFormat = "GTiff"; char **papszOptions = NULL; std::string str = ""; double adfGeoTransform[6] = { xmin, (xmax-xmin)/pCount, 0, ymax, 0, (ymin-ymax)/lCount }; OGRSpatialReference oSRS; char *pszSRS_WKT = NULL; demSRS.exportToWkt( &pszSRS_WKT ); GDALDriver *poDriver; poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if( poDriver == NULL ) exit(107); GDALDataset *poDstDS; str = pixlinename; const char * pszDstFilename = str.c_str(); poDstDS = poDriver->Create( pszDstFilename, pCount, lCount, 2, GDT_Int32, papszOptions ); poDstDS->SetGeoTransform( adfGeoTransform ); poDstDS->SetProjection( pszSRS_WKT ); // CPLFree( pszSRS_WKT ); GDALRasterBand *poBand1; GDALRasterBand *poBand2; poBand1 = poDstDS->GetRasterBand(1); poBand2 = poDstDS->GetRasterBand(2); poBand1->SetNoDataValue(nodata_out); poBand2->SetNoDataValue(nodata_out); GDALDriver *poDriverOff; poDriverOff = GetGDALDriverManager()->GetDriverByName(pszFormat); if( poDriverOff == NULL ) exit(107); GDALDataset *poDstDSOff; str = offsetname; const char * pszDstFilenameOff = str.c_str(); poDstDSOff = poDriverOff->Create( pszDstFilenameOff, pCount, lCount, 2, GDT_Int32, papszOptions ); poDstDSOff->SetGeoTransform( adfGeoTransform ); poDstDSOff->SetProjection( pszSRS_WKT ); // CPLFree( pszSRS_WKT ); GDALRasterBand *poBand1Off; GDALRasterBand *poBand2Off; poBand1Off = poDstDSOff->GetRasterBand(1); poBand2Off = poDstDSOff->GetRasterBand(2); poBand1Off->SetNoDataValue(nodata_out); poBand2Off->SetNoDataValue(nodata_out); GDALDriver *poDriverRO2VX; poDriverRO2VX = GetGDALDriverManager()->GetDriverByName(pszFormat); if( poDriverRO2VX == NULL ) exit(107); GDALDataset *poDstDSRO2VX; str = ro2vx_name; const char * pszDstFilenameRO2VX = str.c_str(); poDstDSRO2VX = poDriverRO2VX->Create( pszDstFilenameRO2VX, pCount, lCount, 2, GDT_Float64, papszOptions ); poDstDSRO2VX->SetGeoTransform( adfGeoTransform ); poDstDSRO2VX->SetProjection( pszSRS_WKT ); // CPLFree( pszSRS_WKT ); GDALRasterBand *poBand1RO2VX; GDALRasterBand *poBand2RO2VX; // GDALRasterBand *poBand3Los; poBand1RO2VX = poDstDSRO2VX->GetRasterBand(1); poBand2RO2VX = poDstDSRO2VX->GetRasterBand(2); // poBand3Los = poDstDSLos->GetRasterBand(3); poBand1RO2VX->SetNoDataValue(nodata_out); poBand2RO2VX->SetNoDataValue(nodata_out); // poBand3Los->SetNoDataValue(nodata_out); GDALDriver *poDriverRO2VY; poDriverRO2VY = GetGDALDriverManager()->GetDriverByName(pszFormat); if( poDriverRO2VY == NULL ) exit(107); GDALDataset *poDstDSRO2VY; str = ro2vy_name; const char * pszDstFilenameRO2VY = str.c_str(); poDstDSRO2VY = poDriverRO2VY->Create( pszDstFilenameRO2VY, pCount, lCount, 2, GDT_Float64, papszOptions ); poDstDSRO2VY->SetGeoTransform( adfGeoTransform ); poDstDSRO2VY->SetProjection( pszSRS_WKT ); CPLFree( pszSRS_WKT ); GDALRasterBand *poBand1RO2VY; GDALRasterBand *poBand2RO2VY; // GDALRasterBand *poBand3Alt; poBand1RO2VY = poDstDSRO2VY->GetRasterBand(1); poBand2RO2VY = poDstDSRO2VY->GetRasterBand(2); // poBand3Alt = poDstDSAlt->GetRasterBand(3); poBand1RO2VY->SetNoDataValue(nodata_out); poBand2RO2VY->SetNoDataValue(nodata_out); // poBand3Alt->SetNoDataValue(nodata_out); for (int ii=0; ii<lCount; ii++) { double y = geoTrans[3] + (lOff+ii+0.5) * geoTrans[5]; int status = demDS->GetRasterBand(1)->RasterIO(GF_Read, pOff, lOff+ii, pCount, 1, (void*) (demLine.data()), pCount, 1, GDT_Float64, sizeof(double), sizeof(double)*pCount, NULL); if (status != 0) { std::cout << "Error read line " << lOff + ii << " from DEM file: " << demname << "\n"; GDALClose(demDS); GDALDestroyDriverManager(); exit(105); } if (vxname != "") { status = sxDS->GetRasterBand(1)->RasterIO(GF_Read, pOff, lOff+ii, pCount, 1, (void*) (sxLine.data()), pCount, 1, GDT_Float64, sizeof(double), sizeof(double)*pCount, NULL); if (status != 0) { std::cout << "Error read line " << lOff + ii << " from x-direction slope file: " << dhdxname << "\n"; GDALClose(sxDS); GDALDestroyDriverManager(); exit(105); } status = syDS->GetRasterBand(1)->RasterIO(GF_Read, pOff, lOff+ii, pCount, 1, (void*) (syLine.data()), pCount, 1, GDT_Float64, sizeof(double), sizeof(double)*pCount, NULL); if (status != 0) { std::cout << "Error read line " << lOff + ii << " from y-direction slope file: " << dhdyname << "\n"; GDALClose(syDS); GDALDestroyDriverManager(); exit(105); } status = vxDS->GetRasterBand(1)->RasterIO(GF_Read, pOff, lOff+ii, pCount, 1, (void*) (vxLine.data()), pCount, 1, GDT_Float64, sizeof(double), sizeof(double)*pCount, NULL); if (status != 0) { std::cout << "Error read line " << lOff + ii << " from x-direction velocity file: " << vxname << "\n"; GDALClose(vxDS); GDALDestroyDriverManager(); exit(105); } status = vyDS->GetRasterBand(1)->RasterIO(GF_Read, pOff, lOff+ii, pCount, 1, (void*) (vyLine.data()), pCount, 1, GDT_Float64, sizeof(double), sizeof(double)*pCount, NULL); if (status != 0) { std::cout << "Error read line " << lOff + ii << " from y-direction velocity file: " << vyname << "\n"; GDALClose(vyDS); GDALDestroyDriverManager(); exit(105); } } int rgind; int azind; for (int jj=0; jj<pCount; jj++) { double xyz[3]; double llh[3]; double targllh0[3]; double llhi[3]; double drpos[3]; double slp[3]; double vel[3]; //Setup ENU with DEM llh[0] = geoTrans[0] + (jj+pOff+0.5)*geoTrans[1]; llh[1] = y; llh[2] = demLine[jj]; for(int pp=0; pp<3; pp++) { targllh0[pp] = llh[pp]; } if (vxname != "") { slp[0] = sxLine[jj]; slp[1] = syLine[jj]; slp[2] = -1.0; vel[0] = vxLine[jj]; vel[1] = vyLine[jj]; } //Convert from DEM coordinates to LLH inplace fwdTrans->Transform(1, llh, llh+1, llh+2); //Bringing it into ISCE llhi[0] = deg2rad * llh[1]; llhi[1] = deg2rad * llh[0]; llhi[2] = llh[2]; //Convert to ECEF latlon_C(&wgs84, xyz, llhi, LLH_2_XYZ); // if ((ii == (lCount+1)/2)&(jj == pCount/2)){ // std::cout << xyz[0] << " " << xyz[1] << " " << xyz[2] << "\n"; // } //Start the geo2rdr algorithm double satx[3]; double satv[3]; double tprev; double tline = tmid; double rngpix; double los[3]; double alt[3]; double normal[3]; double dopfact; double height; double vhat[3], that[3], chat[3], nhat[3], delta[3], targVec[3], targXYZ[3], diffvec[3], temp[3], satvc[3], altc[3]; double vmag; double major, minor; double satDist; double alpha, beta, gamma; double radius, hgt, zsch; double a, b, costheta, sintheta; double rdiff; for(int kk=0; kk<3; kk++) { satx[kk] = satxmid[kk]; } for(int kk=0; kk<3; kk++) { satv[kk] = satvmid[kk]; } //Iterations for (int kk=0; kk<51;kk++) { tprev = tline; for(int pp=0; pp<3; pp++) { drpos[pp] = xyz[pp] - satx[pp]; } rngpix = norm_C(drpos); double fn = dot_C(drpos, satv); double fnprime = -dot_C(satv, satv); tline = tline - fn/fnprime; if (interpolateWGS84Orbit(orbit, tline, satx, satv) != 0) { std::cout << "Error with orbit interpolation. \n"; GDALClose(demDS); GDALDestroyDriverManager(); exit(106); } } // if ((ii==600)&&(jj==600)) // { // std::cout << "\n" << lOff+ii << " " << pOff+jj << " " << demLine[jj] << "\n"; // } rgind = std::round((rngpix - startingRange) / dr) + 1.; azind = std::round((tline - sensingStart) * prf) + 1.; //*********************Slant-range vector unitvec_C(drpos, los); for(int pp=0; pp<3; pp++) { llh[pp] = xyz[pp] + los[pp] * dr; } latlon_C(&wgs84, llh, llhi, XYZ_2_LLH); //Bringing it from ISCE into LLH llh[0] = llhi[1] / deg2rad; llh[1] = llhi[0] / deg2rad; llh[2] = llhi[2]; //Convert from LLH inplace to DEM coordinates invTrans->Transform(1, llh, llh+1, llh+2); for(int pp=0; pp<3; pp++) { drpos[pp] = llh[pp] - targllh0[pp]; } unitvec_C(drpos, los); //*********************Along-track vector tline = tline + 1/prf; if (interpolateWGS84Orbit(orbit, tline, satx, satv) != 0) { std::cout << "Error with orbit interpolation. \n"; GDALClose(demDS); GDALDestroyDriverManager(); exit(106); } //run the topo algorithm for new tline dopfact = 0.0; height = demLine[jj]; unitvec_C(satv, vhat); vmag = norm_C(satv); //Convert position and velocity to local tangent plane major = wgs84.a; minor = major * std::sqrt(1 - wgs84.e2); //Setup ortho normal system right below satellite satDist = norm_C(satx); temp[0] = (satx[0] / major); temp[1] = (satx[1] / major); temp[2] = (satx[2] / minor); alpha = 1 / norm_C(temp); radius = alpha * satDist; hgt = (1.0 - alpha) * satDist; //Setup TCN basis - Geocentric unitvec_C(satx, nhat); for(int pp=0; pp<3; pp++) { nhat[pp] = -nhat[pp]; } cross_C(nhat,satv,temp); unitvec_C(temp, chat); cross_C(chat,nhat,temp); unitvec_C(temp, that); //Solve the range doppler eqns iteratively //Initial guess zsch = height; for (int kk=0; kk<10;kk++) { a = satDist; b = (radius + zsch); costheta = 0.5 * (a / rngpix + rngpix / a - (b / a) * (b / rngpix)); sintheta = std::sqrt(1-costheta*costheta); gamma = rngpix * costheta; alpha = dopfact - gamma * dot_C(nhat,vhat) / dot_C(vhat,that); beta = -lookSide * std::sqrt(rngpix * rngpix * sintheta * sintheta - alpha * alpha); for(int pp=0; pp<3; pp++) { delta[pp] = alpha * that[pp] + beta * chat[pp] + gamma * nhat[pp]; } for(int pp=0; pp<3; pp++) { targVec[pp] = satx[pp] + delta[pp]; } latlon_C(&wgs84, targVec, llhi, XYZ_2_LLH); llhi[2] = height; latlon_C(&wgs84, targXYZ, llhi, LLH_2_XYZ); zsch = norm_C(targXYZ) - radius; for(int pp=0; pp<3; pp++) { diffvec[pp] = satx[pp] - targXYZ[pp]; } rdiff = rngpix - norm_C(diffvec); } //Bringing it from ISCE into LLH llh[0] = llhi[1] / deg2rad; llh[1] = llhi[0] / deg2rad; llh[2] = llhi[2]; //Convert from LLH inplace to DEM coordinates invTrans->Transform(1, llh, llh+1, llh+2); for(int pp=0; pp<3; pp++) { alt[pp] = llh[pp] - targllh0[pp]; } unitvec_C(alt, temp); if (vxname != "") { //*********************Local normal vector unitvec_C(slp, normal); for(int pp=0; pp<3; pp++) { normal[pp] = -normal[pp]; } vel[2] = -(vel[0]*normal[0]+vel[1]*normal[1])/normal[2]; } if ((rgind > nPixels)|(rgind < 1)|(azind > nLines)|(azind < 1)) { raster1[jj] = nodata_out; raster2[jj] = nodata_out; raster11[jj] = nodata_out; raster22[jj] = nodata_out; raster1a[jj] = nodata_out; raster1b[jj] = nodata_out; // raster1c[jj] = nodata_out; raster2a[jj] = nodata_out; raster2b[jj] = nodata_out; // raster2c[jj] = nodata_out; } else { raster1[jj] = rgind; raster2[jj] = azind; if ((vxname != "")&(vel[0] != nodata)) { raster11[jj] = std::round(dot_C(vel,los)*dt/dr/365.0/24.0/3600.0*1); raster22[jj] = std::round(dot_C(vel,temp)*dt/norm_C(alt)/365.0/24.0/3600.0*1); } else { raster11[jj] = 0.; raster22[jj] = 0.; } raster1a[jj] = normal[2]/(dt/dr/365.0/24.0/3600.0)*(normal[2]*temp[1]-normal[1]*temp[2])/((normal[2]*los[0]-normal[0]*los[2])*(normal[2]*temp[1]-normal[1]*temp[2])-(normal[2]*temp[0]-normal[0]*temp[2])*(normal[2]*los[1]-normal[1]*los[2])); raster1b[jj] = -normal[2]/(dt/norm_C(alt)/365.0/24.0/3600.0)*(normal[2]*los[1]-normal[1]*los[2])/((normal[2]*los[0]-normal[0]*los[2])*(normal[2]*temp[1]-normal[1]*temp[2])-(normal[2]*temp[0]-normal[0]*temp[2])*(normal[2]*los[1]-normal[1]*los[2])); raster2a[jj] = -normal[2]/(dt/dr/365.0/24.0/3600.0)*(normal[2]*temp[0]-normal[0]*temp[2])/((normal[2]*los[0]-normal[0]*los[2])*(normal[2]*temp[1]-normal[1]*temp[2])-(normal[2]*temp[0]-normal[0]*temp[2])*(normal[2]*los[1]-normal[1]*los[2])); raster2b[jj] = normal[2]/(dt/norm_C(alt)/365.0/24.0/3600.0)*(normal[2]*los[0]-normal[0]*los[2])/((normal[2]*los[0]-normal[0]*los[2])*(normal[2]*temp[1]-normal[1]*temp[2])-(normal[2]*temp[0]-normal[0]*temp[2])*(normal[2]*los[1]-normal[1]*los[2])); // raster1a[jj] = los[0]*dt/dr/365.0/24.0/3600.0; // raster1b[jj] = los[1]*dt/dr/365.0/24.0/3600.0; // raster1c[jj] = los[2]*dt/dr/365.0/24.0/3600.0; // raster2a[jj] = temp[0]*dt/norm_C(alt)/365.0/24.0/3600.0; // raster2b[jj] = temp[1]*dt/norm_C(alt)/365.0/24.0/3600.0; // raster2c[jj] = temp[2]*dt/norm_C(alt)/365.0/24.0/3600.0; } // std::cout << ii << " " << jj << "\n"; // std::cout << rgind << " " << azind << "\n"; // std::cout << raster1[jj][ii] << " " << raster2[jj][ii] << "\n"; // std::cout << raster1[ii][jj] << "\n"; } poBand1->RasterIO( GF_Write, 0, ii, pCount, 1, raster1, pCount, 1, GDT_Int32, 0, 0 ); poBand2->RasterIO( GF_Write, 0, ii, pCount, 1, raster2, pCount, 1, GDT_Int32, 0, 0 ); poBand1Off->RasterIO( GF_Write, 0, ii, pCount, 1, raster11, pCount, 1, GDT_Int32, 0, 0 ); poBand2Off->RasterIO( GF_Write, 0, ii, pCount, 1, raster22, pCount, 1, GDT_Int32, 0, 0 ); poBand1RO2VX->RasterIO( GF_Write, 0, ii, pCount, 1, raster1a, pCount, 1, GDT_Float64, 0, 0 ); poBand2RO2VX->RasterIO( GF_Write, 0, ii, pCount, 1, raster1b, pCount, 1, GDT_Float64, 0, 0 ); // poBand3Los->RasterIO( GF_Write, 0, ii, pCount, 1, // raster1c, pCount, 1, GDT_Float64, 0, 0 ); poBand1RO2VY->RasterIO( GF_Write, 0, ii, pCount, 1, raster2a, pCount, 1, GDT_Float64, 0, 0 ); poBand2RO2VY->RasterIO( GF_Write, 0, ii, pCount, 1, raster2b, pCount, 1, GDT_Float64, 0, 0 ); // poBand3Alt->RasterIO( GF_Write, 0, ii, pCount, 1, // raster2c, pCount, 1, GDT_Float64, 0, 0 ); } /* Once we're done, close properly the dataset */ GDALClose( (GDALDatasetH) poDstDS ); /* Once we're done, close properly the dataset */ GDALClose( (GDALDatasetH) poDstDSOff ); /* Once we're done, close properly the dataset */ GDALClose( (GDALDatasetH) poDstDSRO2VX ); /* Once we're done, close properly the dataset */ GDALClose( (GDALDatasetH) poDstDSRO2VY ); GDALClose(demDS); if (vxname != "") { GDALClose(sxDS); GDALClose(syDS); GDALClose(vxDS); GDALClose(vyDS); } GDALDestroyDriverManager(); } void geoGrid::computeBbox(double *wesn) { std::cout << "\nEstimated bounding box: \n" << "West: " << wesn[0] << "\n" << "East: " << wesn[1] << "\n" << "South: " << wesn[2] << "\n" << "North: " << wesn[3] << "\n"; }
36.559692
263
0.478827
[ "geometry", "vector", "transform" ]
5c5b21c85cda4cae62c22e7facaa5509e6f922ad
17,113
cc
C++
elec/ReactionManager.cc
DavidPoliakoff/cardioid
b1699c618966b304848f41e027dfc5c013b7a42b
[ "MIT-0", "MIT" ]
null
null
null
elec/ReactionManager.cc
DavidPoliakoff/cardioid
b1699c618966b304848f41e027dfc5c013b7a42b
[ "MIT-0", "MIT" ]
null
null
null
elec/ReactionManager.cc
DavidPoliakoff/cardioid
b1699c618966b304848f41e027dfc5c013b7a42b
[ "MIT-0", "MIT" ]
null
null
null
#include <set> #include <algorithm> #include "ReactionManager.hh" #include "Reaction.hh" #include "object_cc.hh" #include "units.h" #include "reactionFactory.hh" #include "slow_fix.hh" using namespace std; ///pass through routines. void ReactionManager::calc(double dt, ro_mgarray_ptr<double> Vm, ro_mgarray_ptr<double> iStim, wo_mgarray_ptr<double> dVm) { for (int ii=0; ii<reactions_.size(); ++ii) { reactions_[ii]->calc(dt, Vm.slice(extents_[ii],extents_[ii+1]), iStim.slice(extents_[ii],extents_[ii+1]), dVm.slice(extents_[ii],extents_[ii+1])); } } void ReactionManager::updateNonGate(double dt, ro_mgarray_ptr<double> Vm, wo_mgarray_ptr<double> dVR) { for (int ii=0; ii<reactions_.size(); ++ii) { reactions_[ii]->updateNonGate(dt, Vm.slice(extents_[ii], extents_[ii+1]), dVR.slice(extents_[ii], extents_[ii+1])); } } void ReactionManager::updateGate(double dt, ro_mgarray_ptr<double> Vm) { for (int ii=0; ii<reactions_.size(); ++ii) { reactions_[ii]->updateGate(dt, Vm.slice(extents_[ii], extents_[ii+1])); } } /** Populates the Vm array with some sensible default initial * membrane voltage. Vm will be the parallel to the local cells in * the anatomy that was used to create the concrete reaction class. */ void ReactionManager::initializeMembraneState(wo_mgarray_ptr<double> Vm) { for (int ii=0; ii<reactions_.size(); ++ii) { ::initializeMembraneState(reactions_[ii], objectNameFromRidx_[ii], Vm.slice(extents_[ii],extents_[ii+1])); } } void ReactionManager::addReaction(const std::string& rxnObjectName) { objectNameFromRidx_.push_back(rxnObjectName); } class SortByRidxThenAnatomyThenGid { public: const map<int, int>& ridxFromTag_; SortByRidxThenAnatomyThenGid(map<int, int>& ridxFromTag) : ridxFromTag_(ridxFromTag) {} bool operator()(const AnatomyCell& a, const AnatomyCell& b) { if (ridxFromTag_.find(a.cellType_) != ridxFromTag_.find(b.cellType_)) { if (ridxFromTag_.find(a.cellType_) == ridxFromTag_.end()) { return false; } else if (ridxFromTag_.find(b.cellType_) == ridxFromTag_.end()) { return true; } else { return ridxFromTag_.find(a.cellType_)->second < ridxFromTag_.find(b.cellType_)->second; } } else if (a.cellType_ != b.cellType_) { return a.cellType_ < b.cellType_; } else if (a.gid_ != b.gid_) { return a.gid_ < b.gid_; } return false; } }; void ReactionManager::create(const double dt, Anatomy& anatomy, const ThreadTeam &group) { //construct an array of all the objects int numReactions=objectNameFromRidx_.size(); vector<OBJECT*> objects(numReactions); for (int ii=0; ii<numReactions; ++ii) { objects[ii] = objectFind(objectNameFromRidx_[ii], "REACTION"); } //get all the method types int numTypes; { set<string> methodTypeSet; for (int ii=0; ii<numReactions; ++ii) { string method; objectGet(objects[ii], "method", method, ""); assert(method != ""); methodTypeSet.insert(method); } numTypes = methodTypeSet.size(); methodNameFromType_.resize(numTypes); copy(methodTypeSet.begin(), methodTypeSet.end(), methodNameFromType_.begin()); } typeFromRidx_.resize(numReactions); { vector<int> reactionReordering(numReactions); { int cursor=0; for (int itype=0; itype<numTypes; ++itype) { for (int ireaction=0; ireaction<numReactions; ++ireaction) //bottleneck when #reactions large { string method; objectGet(objects[ireaction], "method", method, ""); if (method == methodNameFromType_[itype]) { /* note, we use cursor instead of ireaction here because we're about to reorder the object arrays. This ensures that the typeFromRidx array corresponds to the same things as what the objects[] array and objectNameFromRidx_ arrays point to. If we used ireaction instead, we would have to permute the arrays below, and we don't want to do that. */ typeFromRidx_[cursor] = itype; reactionReordering[ireaction] = cursor++; } } } assert(cursor == numReactions); } vector<string> nameCopy(numReactions); vector<OBJECT*> objectCopy(numReactions); for (int ireaction=0; ireaction<numReactions; ++ireaction) { objectCopy[reactionReordering[ireaction]] = objects[ireaction]; nameCopy[reactionReordering[ireaction]] = objectNameFromRidx_[ireaction]; } objects = objectCopy; objectNameFromRidx_ = nameCopy; } //now all the reactions are sorted by their type //here are the invariants. for (int ireaction=0; ireaction<numReactions; ++ireaction) { assert(objectNameFromRidx_[ireaction] == objects[ireaction]->name); string method; objectGet(objects[ireaction], "method", method, ""); assert(method == methodNameFromType_[typeFromRidx_[ireaction]]); } //check that all the reaction objects we're using have cellTypes defined and that cellTypes are numbers. { bool foundCellTypeProblem=false; for (int ireaction=0; ireaction<numReactions; ++ireaction) { vector<string> cellTypesText; objectGet(objects[ireaction], "cellTypes", cellTypesText); if (cellTypesText.empty()) { printf("cellTypes not found for %s. cellTypes now required on all REACTION objects\n", objectNameFromRidx_[ireaction].c_str()); foundCellTypeProblem=true; } for (int itag=0; itag<cellTypesText.size(); ++itag) { for (int cursor=0; cursor<cellTypesText[itag].size(); ++cursor) { unsigned char thisChar = cellTypesText[itag][cursor]; if (!('0' <= thisChar && thisChar <= '9')) { printf("Expected a number, found %s instead for cellTypes attribute on object %s\n" "If you're converting an old object.data file, use cellTypeName instead.\n" "Notice the singular. You'll need diffent reaction objects for each type.\n", cellTypesText[itag].c_str(), objectNameFromRidx_[ireaction].c_str()); foundCellTypeProblem=true; } } } } assert(!foundCellTypeProblem); } //find all the anatomy tags that have been set as reaction models map<int, int> ridxFromCellType; for (int ireaction=0; ireaction<numReactions; ++ireaction) { vector<int> anatomyCellTypes; objectGet(objects[ireaction], "cellTypes", anatomyCellTypes); for (int itag=0; itag<anatomyCellTypes.size(); ++itag) { if (ridxFromCellType.find(anatomyCellTypes[itag]) != ridxFromCellType.end()) { assert(0 && "Duplicate cellTypes within the reaction models"); } ridxFromCellType[anatomyCellTypes[itag]] = ireaction; allCellTypes_.insert(anatomyCellTypes[itag]); } } //go through the anatomy looking for cell types with no reaction vector<AnatomyCell>& cellArray(anatomy.cellArray()); { set<int> missingReactions; for (int icell=0; icell<anatomy.nLocal(); icell++) { if (allCellTypes_.find(cellArray[icell].cellType_) == allCellTypes_.end()) { missingReactions.insert(cellArray[icell].cellType_); } } for (set<int>::iterator iter=missingReactions.begin(); iter != missingReactions.end(); ++iter) { printf("Found cell type %d, which isn't claimed by any reaction model.\n", *iter); } assert(missingReactions.empty()); } //sort the anatomy in the correct order. { SortByRidxThenAnatomyThenGid cmpFunc(ridxFromCellType); sort(cellArray.begin(),cellArray.begin()+anatomy.nLocal(), cmpFunc); } //count how many of each we have. vector<int> countFromRidx(numReactions); for (int ireaction=0; ireaction<numReactions; ++ireaction) { countFromRidx[ireaction] = 0; } for (int icell=0; icell<anatomy.nLocal(); ++icell) { const AnatomyCell& cell(cellArray[icell]); if (ridxFromCellType.find(cell.cellType_) != ridxFromCellType.end()) { countFromRidx[ridxFromCellType[cell.cellType_]]++; } } //create the reaction objects reactions_.resize(numReactions); extents_.resize(numReactions+1); extents_[0] = 0; for (int ireaction=0; ireaction<numReactions; ++ireaction) { int localSize = countFromRidx[ireaction]; reactions_[ireaction] = reactionFactory(objectNameFromRidx_[ireaction], dt, localSize, group); extents_[ireaction+1] = extents_[ireaction]+localSize; int bufferSize = convertActualSizeToBufferSize(localSize); } //Ok, now we've created the reaction objects. Now we need to //figure out the state variables will map. //First, collect all the info about the state variables. vector<vector<string> > subUnitsFromType(numTypes); vector<vector<string> > subVarnamesFromType(numTypes); vector<vector<int> > subHandlesFromType(numTypes); for (int itype=0; itype<numTypes; ++itype) { //find a reaction object for this type. Reaction* thisReaction=NULL; for (int ireaction=0; ireaction<numReactions; ++ireaction) { if (typeFromRidx_[ireaction] == itype) { thisReaction = reactions_[ireaction]; break; } } assert(thisReaction != NULL); //query the state variable information. thisReaction->getCheckpointInfo(subVarnamesFromType[itype], subUnitsFromType[itype]); subHandlesFromType[itype] = thisReaction->getVarHandle(subVarnamesFromType[itype]); } //find all the subVarnames with more than one baseType set<string> subVarnamesWithMultipleBases; { map<string, string> baseUnitFromSubVarname; for (int itype=0; itype<numTypes; ++itype) { const vector<string>& subVarnames(subVarnamesFromType[itype]); for (int isubVarname=0; isubVarname<subVarnames.size(); ++isubVarname) { const string& thisSubVarname(subVarnames[isubVarname]); const string& thisSubUnit(subUnitsFromType[itype][isubVarname]); //does this name has a subtype assigned to it? if (baseUnitFromSubVarname.find(thisSubVarname) == baseUnitFromSubVarname.end()) { //if a type hasn't been identified yet for this guy, add it here. baseUnitFromSubVarname[thisSubVarname] = thisSubUnit; } else { //otherwise, if the units don't match this guy has multiple bases. if (units_check(baseUnitFromSubVarname[thisSubVarname].c_str(), thisSubUnit.c_str())) { subVarnamesWithMultipleBases.insert(thisSubVarname); } } } } } //set up the rename structures //if a subvar has multiple bases, rename it everywhere. Otherwise, pass it through. //collect up all the unique names and the bases. //sets unitFromHandle_ //sets handleFromVarname_ //sets subHandleInfoFromTypeAndHandle_ subHandleInfoFromTypeAndHandle_.resize(numTypes); for (int itype=0; itype<numTypes; ++itype) { for (int isubVarname=0; isubVarname<subVarnamesFromType[itype].size(); ++isubVarname) { const string& thisSubVarname(subVarnamesFromType[itype][isubVarname]); const string& thisSubUnit(subUnitsFromType[itype][isubVarname]); const int& thisSubHandle(subHandlesFromType[itype][isubVarname]); string newName = thisSubVarname; if (subVarnamesWithMultipleBases.find(thisSubVarname) != subVarnamesWithMultipleBases.end()) { newName = methodNameFromType_[itype]+"."+newName; } int thisHandle; if (handleFromVarname_.find(newName) == handleFromVarname_.end()) { thisHandle = handleFromVarname_.size(); handleFromVarname_[newName] = thisHandle; unitFromHandle_.push_back(thisSubUnit); } else { thisHandle = handleFromVarname_[newName]; } assert(thisHandle == handleFromVarname_[newName]); assert(handleFromVarname_.size() == unitFromHandle_.size()); assert(units_check(thisSubUnit.c_str(),unitFromHandle_[thisHandle].c_str()) == 0); subHandleInfoFromTypeAndHandle_[itype][thisHandle].first = thisSubHandle; subHandleInfoFromTypeAndHandle_[itype][thisHandle].second = units_convert(1,unitFromHandle_[thisHandle].c_str(),thisSubUnit.c_str()); } } } std::string ReactionManager::stateDescription() const { assert(methodNameFromType_.size() >= 1); string retval = methodNameFromType_[0]; for (int itype=1; itype<methodNameFromType_.size(); ++itype) { retval += "+"; retval += methodNameFromType_[itype]; } return retval; } /** Functions needed for checkpoint/restart */ void ReactionManager::getCheckpointInfo(std::vector<std::string>& fieldNames, std::vector<std::string>& fieldUnits) const { fieldNames.clear(); fieldNames.reserve(handleFromVarname_.size()); for(map<string,int>::const_iterator iter=handleFromVarname_.begin(); iter != handleFromVarname_.end(); ++iter) { fieldNames.push_back(iter->first); } for (int ii=0; ii<fieldNames.size(); ++ii) { fieldUnits.push_back(getUnit(fieldNames[ii])); } } int ReactionManager::getVarHandle(const std::string& varName) const { if (handleFromVarname_.find(varName) == handleFromVarname_.end()) { return -1; } else { return handleFromVarname_.find(varName)->second; } } vector<int> ReactionManager::getVarHandle(const vector<string>& varName) const { vector<int> handle; for (unsigned ii=0; ii<varName.size(); ++ii) handle.push_back(getVarHandle(varName[ii])); return handle; } void ReactionManager::setValue(int iCell, int varHandle, double value) { int ridx = getRidxFromCell(iCell); int subHandle; double myUnitFromTheirUnit; if (subUsesHandle(ridx, varHandle, subHandle, myUnitFromTheirUnit)) { int subCell = iCell-extents_[ridx]; reactions_[ridx]->setValue(subCell, subHandle, value/myUnitFromTheirUnit); } } double ReactionManager::getValue(int iCell, int varHandle) const { int ridx = getRidxFromCell(iCell); int subHandle; double myUnitFromTheirUnit; if (subUsesHandle(ridx, varHandle, subHandle, myUnitFromTheirUnit)) { int subCell = iCell-extents_[ridx]; return myUnitFromTheirUnit*reactions_[ridx]->getValue(subCell, subHandle); } else { return numeric_limits<double>::quiet_NaN(); } } void ReactionManager::getValue(int iCell, const vector<int>& handle, vector<double>& value) const { for (unsigned ii=0; ii<handle.size(); ++ii) value[ii] = getValue(iCell, handle[ii]); } const std::string ReactionManager::getUnit(const std::string& varName) const { return unitFromHandle_[getVarHandle(varName)]; } vector<int> ReactionManager::allCellTypes() const { vector<int> retVal(allCellTypes_.size()); copy(allCellTypes_.begin(), allCellTypes_.end(), retVal.begin()); return retVal; } int ReactionManager::getRidxFromCell(const int iCell) const { //binary search to find the proper Ridx. int begin=0; int end=extents_.size(); while (begin+1 < end) { int mid=(begin+end)/2; if (extents_[mid] == iCell) { return mid; } else if (extents_[mid] < iCell) { begin=mid; } else { end=mid; } } return begin; } bool ReactionManager::subUsesHandle(const int ridx, const int handle, int& subHandle, double& myUnitFromTheirUnit) const { const map<int, pair<int, double> >& subHandleInfoFromHandle(subHandleInfoFromTypeAndHandle_[typeFromRidx_[ridx]]); if (subHandleInfoFromHandle.find(handle) == subHandleInfoFromHandle.end()) { return false; } subHandle = subHandleInfoFromHandle.find(handle)->second.first; myUnitFromTheirUnit = subHandleInfoFromHandle.find(handle)->second.second; return true; }
34.363454
142
0.629229
[ "object", "vector", "model" ]