text
stringlengths
54
60.6k
<commit_before>345480e1-2e4f-11e5-b653-28cfe91dbc4b<commit_msg>345df9cf-2e4f-11e5-92e1-28cfe91dbc4b<commit_after>345df9cf-2e4f-11e5-92e1-28cfe91dbc4b<|endoftext|>
<commit_before>a8b346fa-2d3f-11e5-b64f-c82a142b6f9b<commit_msg>a9093dcf-2d3f-11e5-a34f-c82a142b6f9b<commit_after>a9093dcf-2d3f-11e5-a34f-c82a142b6f9b<|endoftext|>
<commit_before>cc0de594-2e4e-11e5-937a-28cfe91dbc4b<commit_msg>cc14e3fa-2e4e-11e5-ba4c-28cfe91dbc4b<commit_after>cc14e3fa-2e4e-11e5-ba4c-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> int main (int argc, char* args[]) { std::cout << "top level main" << std::endl; return 0; } <commit_msg>take xml file path as command line parameter<commit_after>#include <iostream> int main () { std::cout << "top level main" << std::endl; return 0; } <|endoftext|>
<commit_before><commit_msg>`yli::audio::AudioMaster` constructor: initialize `audio_spec` fields.<commit_after><|endoftext|>
<commit_before>37d7eb7a-ad5d-11e7-b4fa-ac87a332f658<commit_msg>Nope, didn't work, now it does<commit_after>3864a92b-ad5d-11e7-9fc1-ac87a332f658<|endoftext|>
<commit_before>2484b391-2748-11e6-9987-e0f84713e7b8<commit_msg>Nope, didn't work, now it does<commit_after>248e781e-2748-11e6-80dc-e0f84713e7b8<|endoftext|>
<commit_before>db9fedca-585a-11e5-9ac0-6c40088e03e4<commit_msg>dba88d54-585a-11e5-8415-6c40088e03e4<commit_after>dba88d54-585a-11e5-8415-6c40088e03e4<|endoftext|>
<commit_before>f41a9562-585a-11e5-be15-6c40088e03e4<commit_msg>f421d37e-585a-11e5-824f-6c40088e03e4<commit_after>f421d37e-585a-11e5-824f-6c40088e03e4<|endoftext|>
<commit_before>b35024bd-2e4f-11e5-92bb-28cfe91dbc4b<commit_msg>b356ec91-2e4f-11e5-8771-28cfe91dbc4b<commit_after>b356ec91-2e4f-11e5-8771-28cfe91dbc4b<|endoftext|>
<commit_before>#include <QtGui/QApplication> #include "mainwindow.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <stdio.h> #include <iostream> #include <vector> #include "geom/chessgen.h" using namespace cv; using namespace std; using namespace fr; int main(int, char**) { VideoCapture cap(0); // open the default camera if(!cap.isOpened()) // check if we succeeded return -1; cap.set(CV_CAP_PROP_FRAME_WIDTH,640); cap.set(CV_CAP_PROP_FRAME_HEIGHT,480); Mat edges; Size size(7,7); int counter = 10; vector<Point2f> corners; bool found; vector<Point3f> chess = fr::ChessGen::getBoard(size,1,false); /* for(unsigned int i=0;i<chess.size();i++){ cout << chess[i].x << "," << chess[i].y << endl; }*/ vector<vector<Point3f> > objectPoints; vector<vector<Point2f> > imagePoints; Mat camera = Mat::eye(3,3,CV_64F); camera.at<double>(0,2) = 640/2; camera.at<double>(1,2) = 480/2; Mat distortion = Mat::zeros(8, 1, CV_64F); vector<Mat > rvecs; vector<Mat > tvecs; namedWindow("edges",1); for(;;) { Mat frame; cap >> frame; // get a new frame from camera cvtColor(frame, edges, CV_BGR2GRAY); found = findChessboardCorners(edges,size,corners); /* found = findCirclesGrid(edges,size,corners ,CALIB_CB_ASYMMETRIC_GRID );//*/ if(found) frame.convertTo(edges,-1,0.2); drawChessboardCorners(edges,size,corners,found); imshow("edges", edges); if(found){ //if(waitKey(200)>=0){ waitKey(300); objectPoints.push_back(chess); imagePoints.push_back(corners); if(--counter<= 0) break; //} } else waitKey(30); } double rpe = calibrateCamera(objectPoints,imagePoints,Size(800,600),camera,distortion,rvecs,tvecs,CV_CALIB_FIX_ASPECT_RATIO); if(found) imwrite("/home/ryan/chessboard.png",edges); cout << camera << endl; cout << rpe << endl; return 0; } <commit_msg>quick modifications for testing<commit_after>#include <QtGui/QApplication> #include "mainwindow.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <stdio.h> #include <iostream> #include <vector> #include "geom/chessgen.h" using namespace cv; using namespace std; using namespace fr; int main(int, char**) { VideoCapture cap(1); // open the default camera if(!cap.isOpened()) // check if we succeeded return -1; cap.set(CV_CAP_PROP_FRAME_WIDTH,640); cap.set(CV_CAP_PROP_FRAME_HEIGHT,480); Mat edges; Size size(12,9); int counter = 10; vector<Point2f> corners; bool found; vector<Point3f> chess = fr::ChessGen::getBoard(size,1,false); /* for(unsigned int i=0;i<chess.size();i++){ cout << chess[i].x << "," << chess[i].y << endl; }*/ vector<vector<Point3f> > objectPoints; vector<vector<Point2f> > imagePoints; Mat camera = Mat::eye(3,3,CV_64F); camera.at<double>(0,2) = 640/2; camera.at<double>(1,2) = 480/2; Mat distortion = Mat::zeros(8, 1, CV_64F); vector<Mat > rvecs; vector<Mat > tvecs; namedWindow("edges",1); for(;;) { Mat frame; cap >> frame; // get a new frame from camera cvtColor(frame, edges, CV_BGR2GRAY); found = findChessboardCorners(edges,size,corners); /* found = findCirclesGrid(edges,size,corners ,CALIB_CB_ASYMMETRIC_GRID );//*/ if(found) frame.convertTo(edges,-1,0.2); drawChessboardCorners(edges,size,corners,found); imshow("edges", edges); /*if(found){ //if(waitKey(200)>=0){ waitKey(300); objectPoints.push_back(chess); imagePoints.push_back(corners); if(--counter<= 0) break; //} } else waitKey(30);*/ if(waitKey(30)>1) break; } //double rpe = calibrateCamera(objectPoints,imagePoints,Size(800,600),camera,distortion,rvecs,tvecs,CV_CALIB_FIX_ASPECT_RATIO); if(found) imwrite("/home/ryan/chessboard.png",edges); //cout << camera << endl; //cout << rpe << endl; return 0; } <|endoftext|>
<commit_before>83000e87-2d15-11e5-af21-0401358ea401<commit_msg>83000e88-2d15-11e5-af21-0401358ea401<commit_after>83000e88-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>9647c6d4-4b02-11e5-bd5b-28cfe9171a43<commit_msg>almost working<commit_after>9654a55e-4b02-11e5-a803-28cfe9171a43<|endoftext|>
<commit_before>9e5b6ceb-327f-11e5-92b0-9cf387a8033e<commit_msg>9e615359-327f-11e5-9934-9cf387a8033e<commit_after>9e615359-327f-11e5-9934-9cf387a8033e<|endoftext|>
<commit_before>6a0b36e6-2e3a-11e5-9225-c03896053bdd<commit_msg>6a1b184a-2e3a-11e5-a1d5-c03896053bdd<commit_after>6a1b184a-2e3a-11e5-a1d5-c03896053bdd<|endoftext|>
<commit_before>c3b37502-327f-11e5-b12c-9cf387a8033e<commit_msg>c3b99107-327f-11e5-9def-9cf387a8033e<commit_after>c3b99107-327f-11e5-9def-9cf387a8033e<|endoftext|>
<commit_before>6f411e2e-2e4f-11e5-bdca-28cfe91dbc4b<commit_msg>6f4814de-2e4f-11e5-8287-28cfe91dbc4b<commit_after>6f4814de-2e4f-11e5-8287-28cfe91dbc4b<|endoftext|>
<commit_before>a345addc-2e4f-11e5-8d0e-28cfe91dbc4b<commit_msg>a34d6b94-2e4f-11e5-8978-28cfe91dbc4b<commit_after>a34d6b94-2e4f-11e5-8978-28cfe91dbc4b<|endoftext|>
<commit_before>c35bd5a3-ad5c-11e7-bc6d-ac87a332f658<commit_msg>That didn't fix it<commit_after>c4079dcf-ad5c-11e7-8663-ac87a332f658<|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <string> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <math.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <sys/stat.h> #include <vector> using namespace std; int info_RF(char* dirName); int info_D(char* dirName); int info_CS(char* dirName); int info_BS(char* dirName); int info_S(char* dirName); int info_SL(char* dirName); int info_R(char* dirName); int info_W(char* dirName); int info_X(char* dirName); int main() { char *word[50]; char buf[500] = "\0"; int i, k=0; cin.getline(buf, 500); word[k] = strtok(buf, " "); while (word[k++] != NULL) { word[k] = strtok(NULL, " "); } char checking_first = *word[0]; /* pid_t pid; pid = fork(); if(pid == 0) { if(k<=3 && word[0] != "exit"){ string cmd("./src./single_command.sh "); cmd += word[0]; cmd += " "; cmd += word[1]; system(cmd.c_str()); perror("invalid input"); } //run for single_command.sh else if(checking_first == '#'){ string cmd("./src./comment_command.sh "); system(cmd.c_str()); //run for comment_command.sh perror("invalid input"); } else if(word[0] == "exit"){ string cmd("./src./exit.sh "); cmd += word[0]; system(cmd.c_str()); perror("invalid input"); } //run for exit.sh else { int initial = 0; int hold_number = 0; int hold_other_number = 0; int ret[20]; int v[20]; while(initial <= k){ string cmd("./src./multi_command.sh "); if(word[initial] == "|"|| word[initial] == "&" || word[initial][strlen(word[initial]-1)] == ';'){ if(hold_number < initial){ while(hold_number <initial){ cmd += word[hold_number]; hold_number++; } ret[hold_other_number] = system(cmd.c_str()); v[hold_other_number] = WEXITSTATUS(ret[hold_other_number]); } } initial++; } } int status = 0; waitpid(pid, status, WNOHANG); if(status != 1){ perror("fail to close child process"); } } else if(pid == -1){ cout<<"fork error!"<<endl; } else{ cout<<"Should not be in parents"<<endl; } */ //top of part is for homework 01 which does not working so i made it as comment cout<<"program is passing through get cin"<<endl; if(checking_first == '[' || word[0] =="test"){ cout<<"program is passing through checking_first == [ or test "<<endl; checking_first = *word[1]; if(checking_first == '-'){ cout<<"program is passing through '-' "<<endl; //All functions need that file exist vector<char *> dirlist; dirlist.push_back(word[2]); if(word[1] == "-a" || word[1] == "-e"){ //True if <file> exist cout<<"file exist"<<endl; } else if(word[1] == "-f"){//True if <file> exist and is regular file if(info_RF(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-d"){//True if <file> exist and is a directory if(info_D(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-c"){//True if <file> exist and is character special file if(info_CS(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-b"){//True if <file> exist and is block special file if(info_BS(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-p"){//True if <file> exist and is named pipe // need to } else if(word[1] == "-S"){//True if <file> exist and is socket file if(info_S(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-L" || word[1] =="-h"){//True if <file> exist and is symbolic link if(info_SL(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-g"){//True if <file> exist and is sgid bit set // need to } else if(word[1] == "-u"){//True if <file> exist and is suid bit set // need to } else if(word[1] == "-r"){//True if <file> exist and is readable if(info_R(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-w"){//True if <file> exist and is writeable if(info_W(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-x"){//True if <file> exist and is excutable if(info_X(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-s"){//True if <file> exist and size of file is bigger than 0 (not empty) //need to } else if(word[1] == "-t"){//True if file descriptor <fd> is open and refers to a terminal //need to } } checking_first = *word[2]; if(checking_first == '-'){ // there is two files to compare if(word[2] == "-nt"){// True if <file1> is newer than <file2> } else if(word[2] == "-ot"){// True if <file1> is older than <file2> } else if(word[2] == "-ef"){// True if <file1> and <file2> refer to the same device and inode numbers. } } } return 0; } int info_RF(char* dirName){//regular file struct stat sb; if((sb.st_mode & S_IFREG)){ return 1; } return 0; } int info_D(char* dirName){ struct stat sb; if((sb.st_mode & S_IFDIR)){ return 1; } return 0; } int info_CS(char * dirName){ struct stat sb; if((sb.st_mode & S_IFCHR)){ return 1; } return 0; } int info_BS(char * dirName){ struct stat sb; if((sb.st_mode & S_IFBLK)){ return 1; } return 0; } int info_S(char * dirName){ struct stat sb; if((sb.st_mode & S_IFSOCK)){ return 1; } return 0; } int info_SL(char * dirName){ struct stat sb; if((sb.st_mode & S_IFLNK)){ return 1; } return 0; } int info_R(char * dirName){//read struct stat sb; if((sb.st_mode & S_IRUSR)){ return 1; } return 0; } int info_W(char * dirName){ struct stat sb; if((sb.st_mode & S_IWUSR)){ return 1; } return 0; } int info_X(char * dirName){ struct stat sb; if((sb.st_mode & S_IXUSR)){ return 1; } return 0; }<commit_msg>201511201818<commit_after>#include <iostream> #include <cstring> #include <string> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <math.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <sys/stat.h> #include <vector> using namespace std; int info_RF(char* dirName); int info_D(char* dirName); int info_CS(char* dirName); int info_BS(char* dirName); int info_S(char* dirName); int info_SL(char* dirName); int info_R(char* dirName); int info_W(char* dirName); int info_X(char* dirName); int main() { char *word[50]; char buf[500] = "\0"; int i, k=0; cin.getline(buf, 500); word[k] = strtok(buf, " "); while (word[k++] != NULL) { word[k] = strtok(NULL, " "); } char checking_first = word[0]; /* pid_t pid; pid = fork(); if(pid == 0) { if(k<=3 && word[0] != "exit"){ string cmd("./src./single_command.sh "); cmd += word[0]; cmd += " "; cmd += word[1]; system(cmd.c_str()); perror("invalid input"); } //run for single_command.sh else if(checking_first == '#'){ string cmd("./src./comment_command.sh "); system(cmd.c_str()); //run for comment_command.sh perror("invalid input"); } else if(word[0] == "exit"){ string cmd("./src./exit.sh "); cmd += word[0]; system(cmd.c_str()); perror("invalid input"); } //run for exit.sh else { int initial = 0; int hold_number = 0; int hold_other_number = 0; int ret[20]; int v[20]; while(initial <= k){ string cmd("./src./multi_command.sh "); if(word[initial] == "|"|| word[initial] == "&" || word[initial][strlen(word[initial]-1)] == ';'){ if(hold_number < initial){ while(hold_number <initial){ cmd += word[hold_number]; hold_number++; } ret[hold_other_number] = system(cmd.c_str()); v[hold_other_number] = WEXITSTATUS(ret[hold_other_number]); } } initial++; } } int status = 0; waitpid(pid, status, WNOHANG); if(status != 1){ perror("fail to close child process"); } } else if(pid == -1){ cout<<"fork error!"<<endl; } else{ cout<<"Should not be in parents"<<endl; } */ //top of part is for homework 01 which does not working so i made it as comment cout<<"program is passing through get cin"<<endl; if(checking_first == '[' || word[0] =="test"){ cout<<"program is passing through checking_first == [ or test "<<endl; checking_first = word[1]; if(checking_first == '-'){ cout<<"program is passing through '-' "<<endl; //All functions need that file exist vector<char *> dirlist; dirlist.push_back(word[2]); if(word[1] == "-a" || word[1] == "-e"){ //True if <file> exist cout<<"file exist"<<endl; } else if(word[1] == "-f"){//True if <file> exist and is regular file if(info_RF(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-d"){//True if <file> exist and is a directory if(info_D(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-c"){//True if <file> exist and is character special file if(info_CS(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-b"){//True if <file> exist and is block special file if(info_BS(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-p"){//True if <file> exist and is named pipe // need to } else if(word[1] == "-S"){//True if <file> exist and is socket file if(info_S(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-L" || word[1] =="-h"){//True if <file> exist and is symbolic link if(info_SL(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-g"){//True if <file> exist and is sgid bit set // need to } else if(word[1] == "-u"){//True if <file> exist and is suid bit set // need to } else if(word[1] == "-r"){//True if <file> exist and is readable if(info_R(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-w"){//True if <file> exist and is writeable if(info_W(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-x"){//True if <file> exist and is excutable if(info_X(dirlist.front()) == 1){ cout<<"file exist"<<endl; } else cout<<"file does not exist"<<endl; } else if(word[1] == "-s"){//True if <file> exist and size of file is bigger than 0 (not empty) //need to } else if(word[1] == "-t"){//True if file descriptor <fd> is open and refers to a terminal //need to } } checking_first = *word[2]; if(checking_first == '-'){ // there is two files to compare if(word[2] == "-nt"){// True if <file1> is newer than <file2> } else if(word[2] == "-ot"){// True if <file1> is older than <file2> } else if(word[2] == "-ef"){// True if <file1> and <file2> refer to the same device and inode numbers. } } } return 0; } int info_RF(char* dirName){//regular file struct stat sb; if((sb.st_mode & S_IFREG)){ return 1; } return 0; } int info_D(char* dirName){ struct stat sb; if((sb.st_mode & S_IFDIR)){ return 1; } return 0; } int info_CS(char * dirName){ struct stat sb; if((sb.st_mode & S_IFCHR)){ return 1; } return 0; } int info_BS(char * dirName){ struct stat sb; if((sb.st_mode & S_IFBLK)){ return 1; } return 0; } int info_S(char * dirName){ struct stat sb; if((sb.st_mode & S_IFSOCK)){ return 1; } return 0; } int info_SL(char * dirName){ struct stat sb; if((sb.st_mode & S_IFLNK)){ return 1; } return 0; } int info_R(char * dirName){//read struct stat sb; if((sb.st_mode & S_IRUSR)){ return 1; } return 0; } int info_W(char * dirName){ struct stat sb; if((sb.st_mode & S_IWUSR)){ return 1; } return 0; } int info_X(char * dirName){ struct stat sb; if((sb.st_mode & S_IXUSR)){ return 1; } return 0; }<|endoftext|>
<commit_before>d5fbd7ec-35ca-11e5-833d-6c40088e03e4<commit_msg>d604760c-35ca-11e5-8bf1-6c40088e03e4<commit_after>d604760c-35ca-11e5-8bf1-6c40088e03e4<|endoftext|>
<commit_before>42304594-5216-11e5-adf0-6c40088e03e4<commit_msg>423a7534-5216-11e5-81ea-6c40088e03e4<commit_after>423a7534-5216-11e5-81ea-6c40088e03e4<|endoftext|>
<commit_before><commit_msg>Also check for libvorbisfile.dll and libvorbisidec.dll in Windows<commit_after><|endoftext|>
<commit_before>/* ============================================================================== FontAwesome.cpp Created: 13 Jul 2014 12:45:27pm Author: Daniel Lindenfelser ============================================================================== */ #include "FontAwesome.h" Typeface::Ptr FontAwesome_ptr = Typeface::createSystemTypefaceFor( FontAwesomeData::fontawesomewebfont_ttf, FontAwesomeData::fontawesomewebfont_ttfSize); Font FontAwesome() { Font fontAwesomeFont(FontAwesome_ptr); return fontAwesomeFont; } Font getFontAwesome(float height) { Font fontAwesomeFont = FontAwesome(); fontAwesomeFont.setHeight(height); return fontAwesomeFont; } void DrawIcon(Graphics &g, int x, int y, float height, String icon) { g.setFont(getFontAwesome(height)); g.drawText(icon, (int)x, (int)y, (int)height, (int)height, Justification::centred, true); } <commit_msg>dirty fix Linux Font loading<commit_after>/* ============================================================================== FontAwesome.cpp Created: 13 Jul 2014 12:45:27pm Author: Daniel Lindenfelser ============================================================================== */ #include "FontAwesome.h" #if JUCE_LINUX Font getFontAwesome(float height) { Font fontAwesomeFont("FontAwesome", height, Font::plain); return fontAwesomeFont; } #else Typeface::Ptr FontAwesome_ptr = Typeface::createSystemTypefaceFor( FontAwesomeData::fontawesomewebfont_ttf, FontAwesomeData::fontawesomewebfont_ttfSize); Font FontAwesome() { Font fontAwesomeFont(FontAwesome_ptr); return fontAwesomeFont; } Font getFontAwesome(float height) { Font fontAwesomeFont = FontAwesome(); fontAwesomeFont.setHeight(height); return fontAwesomeFont; } #endif void DrawIcon(Graphics &g, int x, int y, float height, String icon) { g.setFont(getFontAwesome(height)); g.drawText(icon, (int)x, (int)y, (int)height, (int)height, Justification::centred, true); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDiffusionImagingAppWorkbenchAdvisor.h" #include "internal/QmitkDiffusionApplicationPlugin.h" #include <berryPlatform.h> #include <berryIPreferencesService.h> #include <berryWorkbenchPreferenceConstants.h> #include <QmitkExtWorkbenchWindowAdvisor.h> #include <QApplication> #include <QPoint> #include <QRect> #include <QDesktopWidget> const QString QmitkDiffusionImagingAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.diffusionimagingapp.perspectives.welcome"; void QmitkDiffusionImagingAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkDiffusionImagingAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { QList<QString> perspExcludeList; perspExcludeList.push_back( "org.blueberry.uitest.util.EmptyPerspective" ); perspExcludeList.push_back( "org.blueberry.uitest.util.EmptyPerspective2" ); perspExcludeList.push_back("org.blueberry.perspectives.help"); QList<QString> viewExcludeList; viewExcludeList.push_back( "org.mitk.views.controlvisualizationpropertiesview" ); QRect rec = QApplication::desktop()->screenGeometry(); configurer->SetInitialSize(QPoint(rec.width(),rec.height())); QmitkExtWorkbenchWindowAdvisor* advisor = new QmitkExtWorkbenchWindowAdvisor(this, configurer); advisor->ShowViewMenuItem(true); advisor->ShowNewWindowMenuItem(true); advisor->ShowClosePerspectiveMenuItem(true); advisor->SetPerspectiveExcludeList(perspExcludeList); advisor->SetViewExcludeList(viewExcludeList); advisor->ShowViewToolbar(false); advisor->ShowPerspectiveToolbar(true); advisor->ShowVersionInfo(true); advisor->ShowMitkVersionInfo(true); advisor->ShowMemoryIndicator(false); advisor->SetProductName("MITK Diffusion"); advisor->SetWindowIcon(":/org.mitk.gui.qt.diffusionimagingapp/app-icon.png"); return advisor; } QString QmitkDiffusionImagingAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return WELCOME_PERSPECTIVE_ID; } <commit_msg>intro is opened after display now<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkDiffusionImagingAppWorkbenchAdvisor.h" #include "internal/QmitkDiffusionApplicationPlugin.h" #include <berryPlatform.h> #include <berryIPreferencesService.h> #include <berryWorkbenchPreferenceConstants.h> #include <QmitkExtWorkbenchWindowAdvisor.h> #include <QApplication> #include <QPoint> #include <QRect> #include <QDesktopWidget> const QString QmitkDiffusionImagingAppWorkbenchAdvisor::WELCOME_PERSPECTIVE_ID = "org.mitk.diffusionimagingapp.perspectives.welcome"; class QmitkDiffusionImagingAppWorkbenchWindowAdvisor : public QmitkExtWorkbenchWindowAdvisor { public: QmitkDiffusionImagingAppWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer) : QmitkExtWorkbenchWindowAdvisor(wbAdvisor, configurer) { } void PostWindowOpen() { QmitkExtWorkbenchWindowAdvisor::PostWindowOpen(); berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); configurer->GetWindow()->GetWorkbench()->GetIntroManager()->ShowIntro(configurer->GetWindow(), false); } }; void QmitkDiffusionImagingAppWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); configurer->SetSaveAndRestore(true); } berry::WorkbenchWindowAdvisor* QmitkDiffusionImagingAppWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { QList<QString> perspExcludeList; perspExcludeList.push_back( "org.blueberry.uitest.util.EmptyPerspective" ); perspExcludeList.push_back( "org.blueberry.uitest.util.EmptyPerspective2" ); perspExcludeList.push_back("org.blueberry.perspectives.help"); QList<QString> viewExcludeList; viewExcludeList.push_back( "org.mitk.views.controlvisualizationpropertiesview" ); QRect rec = QApplication::desktop()->screenGeometry(); configurer->SetInitialSize(QPoint(rec.width(),rec.height())); QmitkDiffusionImagingAppWorkbenchWindowAdvisor* advisor = new QmitkDiffusionImagingAppWorkbenchWindowAdvisor(this, configurer); advisor->ShowViewMenuItem(true); advisor->ShowNewWindowMenuItem(true); advisor->ShowClosePerspectiveMenuItem(true); advisor->SetPerspectiveExcludeList(perspExcludeList); advisor->SetViewExcludeList(viewExcludeList); advisor->ShowViewToolbar(false); advisor->ShowPerspectiveToolbar(true); advisor->ShowVersionInfo(true); advisor->ShowMitkVersionInfo(true); advisor->ShowMemoryIndicator(false); advisor->SetProductName("MITK Diffusion"); advisor->SetWindowIcon(":/org.mitk.gui.qt.diffusionimagingapp/app-icon.png"); return advisor; } QString QmitkDiffusionImagingAppWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return WELCOME_PERSPECTIVE_ID; } <|endoftext|>
<commit_before>#ifndef CLASS_PCI_NIC_HPP #define CLASS_PCI_NIC_HPP #include <class_pci_device.hpp> #include <stdio.h> // The nic knows about the IP stack #include <net/class_ethernet.hpp> #include <net/class_arp.hpp> #include <net/class_ip4.hpp> #include <net/class_ip6.hpp> /* class mac_t{ unsigned char[6]; const char* _str; public: const char* c_str(){ } }*/ class E1000{ public: const char* name(){ return "E1000 Driver"; }; }; class RTL8139; /** A public interface for Network cards @todo(Alfred): We should probably inherit something here, but I still don't know what the common denominators are between a Nic and other devices, except that they should have a "name". When do we ever need/want to treat all devices similarly? I don't want to introduce vtables/polymorphism unless I know it's really useful. */ template<class DRIVER_T> class Nic{ public: /** Get a readable name. @todo Replace the dummy with something useful.*/ //const char* name(); /** @note If we add this while there's a specialization, this overrides. */ inline const char* name() { return driver.name(); }; /** The actual mac address. */ inline const mac_t& mac() { return driver.mac(); }; /** Mac address string. */ inline const char* mac_str() { return driver.mac_str(); }; /** Event types */ enum event_t {EthData, TCPConnection, TCPData, UDPConnection, UDPData, HttpRequest}; /** Attach event handlers to Nic-events. @todo Decide between delegates and function pointers*/ void on(event_t ev, void(*callback)()); private: Ethernet _eth; Arp _arp; IP4 _ip4; IP6 _ip6; DRIVER_T driver; /** Constructor. Just a wrapper around the driver constructor. @note The Dev-class is a friend and will call this */ Nic(PCI_Device* d): _eth(), _arp(_eth),_ip4(_eth),_ip6(_eth), driver(d,_eth) {}; friend class Dev; }; //Driver instead? And delegate everything to it with a delegate? /** class Virtio_Nic : public Nic /{ }; **/ #endif //Class Nic <commit_msg>Cleanup<commit_after>#ifndef CLASS_PCI_NIC_HPP #define CLASS_PCI_NIC_HPP #include <class_pci_device.hpp> #include <stdio.h> // The nic knows about the IP stack #include <net/class_ethernet.hpp> #include <net/class_arp.hpp> #include <net/class_ip4.hpp> #include <net/class_ip6.hpp> /** Future drivers may start out like so, */ class E1000{ public: const char* name(){ return "E1000 Driver"; } //...whatever the Nic class implicitly needs }; /** Or so, etc. They'll have to provide anything the Nic class calls from them. @note{ There's no virtual interface, we'll need to call every function from he Nic class in order to make sure all members exist } */ class RTL8139; /** A public interface for Network cards We're using compile-time polymorphism for now, so the "inheritance" requirements for a driver is implicily given by how it's used below, rather than explicitly by proper inheritance. */ template<class DRIVER_T> class Nic{ public: /** Get a readable name. @todo Replace the dummy with something useful.*/ //const char* name(); /** @note If we add this while there's a specialization, this overrides. */ inline const char* name() { return driver.name(); }; /** The actual mac address. */ inline const mac_t& mac() { return driver.mac(); }; /** Mac address string. */ inline const char* mac_str() { return driver.mac_str(); }; /** Event types */ enum event_t {EthData, TCPConnection, TCPData, UDPConnection, UDPData, HttpRequest}; /** Attach event handlers to Nic-events. @todo Decide between delegates and function pointers*/ void on(event_t ev, void(*callback)()); private: /** An IP stack (a skeleton for now). @todo We might consider adding the stack from the outside to save some overhead for services who only wants a few layers. (I.e. a bridge might not need the whole stack) */ Ethernet _eth; Arp _arp; IP4 _ip4; IP6 _ip6; DRIVER_T driver; /** Constructor. Just a wrapper around the driver constructor. @note The Dev-class is a friend and will call this */ Nic(PCI_Device* d): // Hook up the IP stack _eth(), _arp(_eth),_ip4(_eth),_ip6(_eth), // Add PCI and ethernet layer to the driver driver(d,_eth) {}; friend class Dev; }; #endif //Class Nic <|endoftext|>
<commit_before>#include <Network/cUDPServerManager.h> #include <Network/cUDPManager.h> #include <Network/cDeliverManager.h> #include <Network/cEventManager.h> #include <Network/cRequestManager.h> #include <Network/cResponseManager.h> #include <cinder/app/App.h> #include <limits> #include <Node/action.hpp> #include <Utility/MessageBox.h> #include <Network/IpHost.h> namespace Network { cUDPServerManager::cUDPServerManager( ) { closeAccepter( ); mRoot = Node::node::create( ); mRoot->set_schedule_update( ); } void cUDPServerManager::close( ) { mRoot.reset( ); mSocket.close( ); closeAccepter( ); } void cUDPServerManager::open( ) { mRoot = Node::node::create( ); mRoot->set_schedule_update( ); mSocket.open( 25565 ); openAccepter( ); } void cUDPServerManager::closeAccepter( ) { mIsAccept = false; mIdCount = 0; mConnections.clear( ); } void cUDPServerManager::openAccepter( ) { mIsAccept = true; } void cUDPServerManager::update( float delta ) { updateRecv( ); updateSend( ); mRoot->entry_update( delta ); } ubyte1 cUDPServerManager::getPlayerId( cNetworkHandle const & handle ) { auto itr = mConnections.find( handle ); if ( itr != mConnections.end( ) ) { return itr->second.id; } else { throw std::runtime_error( "Networkhandle nothing" ); } } void cUDPServerManager::updateSend( ) { // M̂΃obt@[ođB for ( auto& client : mConnections ) { auto& handle = client.first; auto& buf = client.second.buffer; // CAuȃf[^l߂܂B auto reliableData = client.second.reliableManager.update( ); std::copy( reliableData.begin(), reliableData.end(), std::back_inserter( buf ) ); // ]ĂpPbg𑗂܂B if ( !buf.empty( ) ) { mSocket.write( handle, buf.size( ), buf.data( ) ); buf.clear( ); buf.shrink_to_fit( ); } } } void cUDPServerManager::updateRecv( ) { // M̂΃obt@[oăpPbg̕ʂsB while ( !mSocket.emptyChunk( ) ) { auto chunk = mSocket.popChunk( ); if ( cUDPManager::getInstance( )->isConnectPacket( chunk ) || ( mConnections.find( chunk.networkHandle ) != mConnections.end( ) ) ) { cUDPManager::getInstance( )->onReceive( chunk ); } else { // RlNVmȂ܂ܑMĂꍇB } } connection( ); ping( ); } void cUDPServerManager::sendDataBufferAdd( cNetworkHandle const & networkHandle, cPacketBuffer const & packetBuffer, bool reliable ) { auto itr = mConnections.find( networkHandle ); if ( itr == mConnections.end( ) ) return; auto& buf = itr->second.buffer; // pPbg傫Ȃ肻ȂɑĂ܂܂B if ( 1024 < buf.size( ) ) { mSocket.write( networkHandle, buf.size( ), buf.data( ) ); buf.clear( ); buf.shrink_to_fit( ); } ubyte2 const& byte = packetBuffer.transferredBytes; cBuffer const& buffer = packetBuffer.buffer; if ( reliable ) { std::vector<char> buf; buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); itr->second.reliableManager.append( std::move( buf ) ); } else { buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); } } void cUDPServerManager::connection( ) { while ( auto p = cRequestManager::getInstance( )->getReqConnect( ) ) { if ( !mIsAccept ) continue; cinder::app::console( ) << p->mNetworkHandle.ipAddress << ":" << p->mNetworkHandle.port << ""; cinder::app::console( ) << "cUDPServerManager: " << "connecting..." << (int)mIdCount << std::endl; auto itr = mConnections.insert( std::make_pair( p->mNetworkHandle, std::move( cConnectionInfo( mIdCount ) ) ) ); if ( itr.second ) { cinder::app::console( ) << p->mNetworkHandle.ipAddress << ":" << p->mNetworkHandle.port << ""; cinder::app::console( ) << "cUDPServerManager: " << "connect success!! " << (int)mIdCount << std::endl; mIdCount += 1; send( p->mNetworkHandle, new Packet::Response::cResConnect( ), false ); // pingR[`𑖂点B using namespace Node::Action; auto act = repeat_forever::create( sequence::create( delay::create( 1.5F ), call_func::create( [ networkHandle = p->mNetworkHandle, this ] { send( networkHandle, new Packet::Event::cEvePing( ) ); cinder::app::console( ) << "cUDPServerManager: " << "ping to " << (int)getPlayerId( networkHandle ) << std::endl; } ) ) ); act->set_tag( itr.first->second.id ); mRoot->run_action( act ); } else { cinder::app::console( ) << p->mNetworkHandle.ipAddress << ":" << p->mNetworkHandle.port << ""; cinder::app::console( ) << "cUDPServerManager: " << "connect faild " << (int)mIdCount << std::endl; } } } void cUDPServerManager::ping( ) { while ( auto p = cDeliverManager::getInstance( )->getDliPing( ) ) { auto itr = mConnections.find( p->mNetworkHandle ); if ( itr != mConnections.end( ) ) { itr->second.closeSecond = cinder::app::getElapsedSeconds( ) + PING_HOLD_SECOND; } } for ( auto itr = mConnections.begin( ); itr != mConnections.end( ); ) { // [J̏ꍇ̓JEg_E܂B if ( itr->first.ipAddress != Network::getLocalIpAddressHost( ) ) { if ( itr->second.closeSecond < cinder::app::getElapsedSeconds( ) ) { cinder::app::console( ) << itr->first.ipAddress << ":" << itr->first.port << ""; cinder::app::console( ) << "cUDPServerManager: " << "disconnect" << itr->second.id << std::endl; mRoot->remove_action_by_tag( itr->second.id ); mConnections.erase( itr++ ); continue; } } ++itr; } } }<commit_msg>リコネクト出来るようにしました。<commit_after>#include <Network/cUDPServerManager.h> #include <Network/cUDPManager.h> #include <Network/cDeliverManager.h> #include <Network/cEventManager.h> #include <Network/cRequestManager.h> #include <Network/cResponseManager.h> #include <cinder/app/App.h> #include <limits> #include <Node/action.hpp> #include <Utility/MessageBox.h> #include <Network/IpHost.h> namespace Network { cUDPServerManager::cUDPServerManager( ) { closeAccepter( ); mRoot = Node::node::create( ); mRoot->set_schedule_update( ); } void cUDPServerManager::close( ) { mRoot.reset( ); mSocket.close( ); closeAccepter( ); } void cUDPServerManager::open( ) { mRoot = Node::node::create( ); mRoot->set_schedule_update( ); mSocket.open( 25565 ); openAccepter( ); } void cUDPServerManager::closeAccepter( ) { mIsAccept = false; mIdCount = 0; mConnections.clear( ); } void cUDPServerManager::openAccepter( ) { mIsAccept = true; } void cUDPServerManager::update( float delta ) { updateRecv( ); updateSend( ); mRoot->entry_update( delta ); } ubyte1 cUDPServerManager::getPlayerId( cNetworkHandle const & handle ) { auto itr = mConnections.find( handle ); if ( itr != mConnections.end( ) ) { return itr->second.id; } else { throw std::runtime_error( "Networkhandle nothing" ); } } void cUDPServerManager::updateSend( ) { // M̂΃obt@[ođB for ( auto& client : mConnections ) { auto& handle = client.first; auto& buf = client.second.buffer; // CAuȃf[^l߂܂B auto reliableData = client.second.reliableManager.update( ); std::copy( reliableData.begin(), reliableData.end(), std::back_inserter( buf ) ); // ]ĂpPbg𑗂܂B if ( !buf.empty( ) ) { mSocket.write( handle, buf.size( ), buf.data( ) ); buf.clear( ); buf.shrink_to_fit( ); } } } void cUDPServerManager::updateRecv( ) { // M̂΃obt@[oăpPbg̕ʂsB while ( !mSocket.emptyChunk( ) ) { auto chunk = mSocket.popChunk( ); if ( cUDPManager::getInstance( )->isConnectPacket( chunk ) || ( mConnections.find( chunk.networkHandle ) != mConnections.end( ) ) ) { cUDPManager::getInstance( )->onReceive( chunk ); } else { // RlNVmȂ܂ܑMĂꍇB } } connection( ); ping( ); } void cUDPServerManager::sendDataBufferAdd( cNetworkHandle const & networkHandle, cPacketBuffer const & packetBuffer, bool reliable ) { auto itr = mConnections.find( networkHandle ); if ( itr == mConnections.end( ) ) return; auto& buf = itr->second.buffer; // pPbg傫Ȃ肻ȂɑĂ܂܂B if ( 1024 < buf.size( ) ) { mSocket.write( networkHandle, buf.size( ), buf.data( ) ); buf.clear( ); buf.shrink_to_fit( ); } ubyte2 const& byte = packetBuffer.transferredBytes; cBuffer const& buffer = packetBuffer.buffer; if ( reliable ) { std::vector<char> buf; buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); itr->second.reliableManager.append( std::move( buf ) ); } else { buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); } } void cUDPServerManager::connection( ) { while ( auto p = cRequestManager::getInstance( )->getReqConnect( ) ) { if ( !mIsAccept ) continue; cinder::app::console( ) << p->mNetworkHandle.ipAddress << ":" << p->mNetworkHandle.port << ""; cinder::app::console( ) << "cUDPServerManager: " << "connecting..." << (int)mIdCount << std::endl; auto itr = mConnections.insert( std::make_pair( p->mNetworkHandle, std::move( cConnectionInfo( mIdCount ) ) ) ); if ( itr.second ) { cinder::app::console( ) << p->mNetworkHandle.ipAddress << ":" << p->mNetworkHandle.port << ""; cinder::app::console( ) << "cUDPServerManager: " << "connect success!! " << (int)mIdCount << std::endl; mIdCount += 1; send( p->mNetworkHandle, new Packet::Response::cResConnect( ), false ); // pingR[`𑖂点B using namespace Node::Action; auto act = repeat_forever::create( sequence::create( delay::create( 1.5F ), call_func::create( [ networkHandle = p->mNetworkHandle, this ] { send( networkHandle, new Packet::Event::cEvePing( ) ); cinder::app::console( ) << "cUDPServerManager: " << "ping to " << (int)getPlayerId( networkHandle ) << std::endl; } ) ) ); act->set_tag( itr.first->second.id ); mRoot->run_action( act ); } else { // ĂѐڑĂꍇB cinder::app::console( ) << p->mNetworkHandle.ipAddress << ":" << p->mNetworkHandle.port << ""; cinder::app::console( ) << "cUDPServerManager: " << "reconnect success!! " << (int)mIdCount << std::endl; send( p->mNetworkHandle, new Packet::Response::cResConnect( ), false ); // pingR[`𑖂点B mRoot->remove_action_by_tag( itr.first->second.id ); using namespace Node::Action; auto act = repeat_forever::create( sequence::create( delay::create( 1.5F ), call_func::create( [networkHandle = p->mNetworkHandle, this] { send( networkHandle, new Packet::Event::cEvePing( ) ); cinder::app::console( ) << "cUDPServerManager: " << "ping to " << (int)getPlayerId( networkHandle ) << std::endl; } ) ) ); act->set_tag( itr.first->second.id ); mRoot->run_action( act ); } } } void cUDPServerManager::ping( ) { while ( auto p = cDeliverManager::getInstance( )->getDliPing( ) ) { auto itr = mConnections.find( p->mNetworkHandle ); if ( itr != mConnections.end( ) ) { itr->second.closeSecond = cinder::app::getElapsedSeconds( ) + PING_HOLD_SECOND; } } for ( auto itr = mConnections.begin( ); itr != mConnections.end( ); ) { // [J̏ꍇ̓JEg_E܂B if ( itr->first.ipAddress != Network::getLocalIpAddressHost( ) ) { if ( itr->second.closeSecond < cinder::app::getElapsedSeconds( ) ) { cinder::app::console( ) << itr->first.ipAddress << ":" << itr->first.port << ""; cinder::app::console( ) << "cUDPServerManager: " << "disconnect" << itr->second.id << std::endl; mRoot->remove_action_by_tag( itr->second.id ); mConnections.erase( itr++ ); continue; } } ++itr; } } }<|endoftext|>
<commit_before>/** * @file checksum.cc * @author Tomasz Lichon * @copyright (C) 2016 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "checksum.h" #include "messages.pb.h" #include <sstream> namespace one { namespace messages { namespace fuse { Checksum::Checksum(std::unique_ptr<ProtocolServerMessage> serverMessage) { if (!serverMessage->fuse_response().has_checksum()) throw std::system_error{std::make_error_code(std::errc::protocol_error), "checksum field missing"}; auto &message = *serverMessage->mutable_fuse_response()->mutable_checksum(); message.mutable_value()->swap(m_value); } const std::string &Checksum::value() const { return m_value; } std::string Checksum::toString() const { std::stringstream ss; ss << "type: 'Checksum', value: '" << m_value; return ss.str(); } } // namespace fuse } // namespace messages } // namespace one <commit_msg>VFS-2197 Fail with proper error when sync has failed.<commit_after>/** * @file checksum.cc * @author Tomasz Lichon * @copyright (C) 2016 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "checksum.h" #include "messages.pb.h" #include "messages/status.h" #include <sstream> namespace one { namespace messages { namespace fuse { Checksum::Checksum(std::unique_ptr<ProtocolServerMessage> serverMessage) { Status{*serverMessage->mutable_fuse_response()->mutable_status()} .throwOnError(); if (!serverMessage->fuse_response().has_checksum()) throw std::system_error{std::make_error_code(std::errc::protocol_error), "checksum field missing"}; auto &message = *serverMessage->mutable_fuse_response()->mutable_checksum(); message.mutable_value()->swap(m_value); } const std::string &Checksum::value() const { return m_value; } std::string Checksum::toString() const { std::stringstream ss; ss << "type: 'Checksum', value: '" << m_value; return ss.str(); } } // namespace fuse } // namespace messages } // namespace one <|endoftext|>
<commit_before><commit_msg>Invoke the right method (invokeDefault) if a plugin calls NPN_InvokeDefault on its own object.<commit_after><|endoftext|>
<commit_before><commit_msg>Disable tests while I investigate<commit_after><|endoftext|>
<commit_before>#pragma once #include "Karabiner-VirtualHIDDevice/dist/include/karabiner_virtual_hid_device_methods.hpp" #include "iokit_utility.hpp" #include <IOKit/IOKitLib.h> #include <IOKit/hidsystem/IOHIDShared.h> #include <nod/nod.hpp> #include <pqrs/osx/iokit_service_monitor.hpp> #include <pqrs/osx/kern_return.hpp> namespace krbn { class virtual_hid_device_client final : public pqrs::dispatcher::extra::dispatcher_client { public: nod::signal<void(void)> client_connected; nod::signal<void(void)> client_disconnected; nod::signal<void(void)> virtual_hid_keyboard_ready; virtual_hid_device_client(const virtual_hid_device_client&) = delete; virtual_hid_device_client(void) : dispatcher_client(), service_(IO_OBJECT_NULL), connect_(IO_OBJECT_NULL), connected_(false), virtual_hid_keyboard_ready_check_timer_(*this), virtual_hid_keyboard_ready_(false) { } virtual ~virtual_hid_device_client(void) { detach_from_dispatcher([this] { close_connection(); service_monitor_ = nullptr; }); } void async_connect(void) { enqueue_to_dispatcher([this] { if (auto matching_dictionary = IOServiceNameMatching(pqrs::karabiner_virtual_hid_device::get_virtual_hid_root_name())) { service_monitor_ = std::make_unique<pqrs::osx::iokit_service_monitor>(weak_dispatcher_, matching_dictionary); service_monitor_->service_matched.connect([this](auto&& registry_entry_id, auto&& service_ptr) { close_connection(); // Use the last matched service. open_connection(*service_ptr); }); service_monitor_->service_terminated.connect([this](auto&& registry_entry_id) { close_connection(); // Use the next service service_monitor_->async_invoke_service_matched(); }); service_monitor_->async_start(); logger::get_logger()->info("virtual_hid_device_client is started."); CFRelease(matching_dictionary); } }); } void async_close(void) { enqueue_to_dispatcher([this] { close_connection(); }); } bool is_connected(void) const { return connected_; } bool is_virtual_hid_keyboard_ready(void) const { return virtual_hid_keyboard_ready_; } void async_initialize_virtual_hid_keyboard(const pqrs::karabiner_virtual_hid_device::properties::keyboard_initialization& properties) { enqueue_to_dispatcher([this, properties] { if (virtual_hid_keyboard_ready_ && virtual_hid_keyboard_properties_ == properties) { return; } virtual_hid_keyboard_properties_ = properties; virtual_hid_keyboard_ready_ = false; logger::get_logger()->info("initialize_virtual_hid_keyboard"); logger::get_logger()->info(" country_code:{0}", static_cast<uint32_t>(virtual_hid_keyboard_properties_.country_code)); if (!connect_) { logger::get_logger()->warn("connect_ is IO_OBJECT_NULL"); return; } bool result = pqrs::karabiner_virtual_hid_device_methods::initialize_virtual_hid_keyboard(connect_, virtual_hid_keyboard_properties_); if (result == kIOReturnSuccess) { virtual_hid_keyboard_ready_check_timer_.start( [this] { if (!connect_) { virtual_hid_keyboard_ready_check_timer_.stop(); return; } bool ready = false; if (pqrs::karabiner_virtual_hid_device_methods::is_virtual_hid_keyboard_ready(connect_, ready) == kIOReturnSuccess) { if (ready) { virtual_hid_keyboard_ready_check_timer_.stop(); virtual_hid_keyboard_ready_ = true; enqueue_to_dispatcher([this] { virtual_hid_keyboard_ready(); }); } } }, std::chrono::milliseconds(1000)); } }); } void async_terminate_virtual_hid_keyboard(void) { enqueue_to_dispatcher([this] { virtual_hid_keyboard_ready_check_timer_.stop(); virtual_hid_keyboard_ready_ = false; if (connect_) { pqrs::karabiner_virtual_hid_device_methods::terminate_virtual_hid_keyboard(connect_); } }); } void async_post_keyboard_input_report(const pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::keyboard_input& report) { enqueue_to_dispatcher([this, report] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::post_keyboard_input_report(connect_, report); } }); } void async_post_keyboard_input_report(const pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::consumer_input& report) { enqueue_to_dispatcher([this, report] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::post_keyboard_input_report(connect_, report); } }); } void async_post_keyboard_input_report(const pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::apple_vendor_top_case_input& report) { enqueue_to_dispatcher([this, report] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::post_keyboard_input_report(connect_, report); } }); } void async_post_keyboard_input_report(const pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::apple_vendor_keyboard_input& report) { enqueue_to_dispatcher([this, report] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::post_keyboard_input_report(connect_, report); } }); } void async_reset_virtual_hid_keyboard(void) { enqueue_to_dispatcher([this] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::reset_virtual_hid_keyboard(connect_); } }); } void async_initialize_virtual_hid_pointing(void) { enqueue_to_dispatcher([this] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::initialize_virtual_hid_pointing(connect_); } }); } void async_terminate_virtual_hid_pointing(void) { enqueue_to_dispatcher([this] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::terminate_virtual_hid_pointing(connect_); } }); } void async_post_pointing_input_report(const pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::pointing_input& report) { enqueue_to_dispatcher([this, report] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::post_pointing_input_report(connect_, report); } }); } void async_reset_virtual_hid_pointing(void) { enqueue_to_dispatcher([this] { if (connect_) { pqrs::karabiner_virtual_hid_device_methods::reset_virtual_hid_pointing(connect_); } }); } private: // This method is executed in the dispatcher thread. void open_connection(io_service_t s) { service_ = s; IOObjectRetain(service_); pqrs::osx::kern_return r = IOServiceOpen(service_, mach_task_self(), kIOHIDServerConnectType, &connect_); if (r) { logger::get_logger()->info("virtual_hid_device_client is opened."); connected_ = true; enqueue_to_dispatcher([this] { client_connected(); }); } else { logger::get_logger()->error("virtual_hid_device_client::open_connection is failed: {0}", r.to_string()); connect_ = IO_OBJECT_NULL; } } // This method is executed in the dispatcher thread. void close_connection(void) { if (connect_) { pqrs::osx::kern_return r = IOServiceClose(connect_); if (!r) { logger::get_logger()->error("virtual_hid_device_client::close_connection error: {0}", r.to_string()); } connect_ = IO_OBJECT_NULL; connected_ = false; enqueue_to_dispatcher([this] { client_disconnected(); }); logger::get_logger()->info("virtual_hid_device_client is closed."); } if (service_) { IOObjectRelease(service_); service_ = IO_OBJECT_NULL; } virtual_hid_keyboard_ready_check_timer_.stop(); virtual_hid_keyboard_ready_ = false; } std::unique_ptr<pqrs::osx::iokit_service_monitor> service_monitor_; io_service_t service_; io_connect_t connect_; std::atomic<bool> connected_; pqrs::dispatcher::extra::timer virtual_hid_keyboard_ready_check_timer_; std::atomic<bool> virtual_hid_keyboard_ready_; pqrs::karabiner_virtual_hid_device::properties::keyboard_initialization virtual_hid_keyboard_properties_; }; } // namespace krbn <commit_msg>Remove virtual_hid_device_client<commit_after><|endoftext|>
<commit_before>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere (disa@jhu.edu) * * This file is part of k-par-means * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <limits> #include <numa.h> #include "signal.h" #include "io.hpp" #include "kmeans.hpp" #include "kmeans_coordinator.hpp" #include "kmeans_task_coordinator.hpp" #include "util.hpp" static void print_usage(); int main(int argc, char* argv[]) { if (argc < 5) { print_usage(); exit(EXIT_FAILURE); } int opt; std::string datafn = std::string(argv[1]); size_t nrow = atol(argv[2]); size_t ncol = atol(argv[3]); unsigned k = atol(argv[4]); std::string dist_type = "eucl"; std::string centersfn = ""; size_t max_iters=std::numeric_limits<size_t>::max(); std::string init = "kmeanspp"; unsigned nthread = kpmbase::get_num_omp_threads(); int num_opts = 0; double tolerance = -1; bool use_min_tri = false; bool pthread = false; unsigned nnodes = numa_num_task_nodes(); std::string outdir = ""; // Increase by 3 -- getopt ignores argv[0] argv += 3; argc -= 3; signal(SIGINT, kpmbase::int_handler); while ((opt = getopt(argc, argv, "l:i:t:T:d:C:mpN:o:")) != -1) { num_opts++; switch (opt) { case 'l': tolerance = atof(optarg); num_opts++; break; case 'i': max_iters = atol(optarg); num_opts++; break; case 't': init = optarg; num_opts++; break; case 'T': nthread = atoi(optarg); num_opts++; break; case 'd': dist_type = std::string(optarg); num_opts++; break; case 'C': centersfn = std::string(optarg); BOOST_ASSERT_MSG(kpmbase::is_file_exist(centersfn.c_str()), "Centers file name doesn't exit!"); init = "none"; // Ignore whatever you pass in num_opts++; break; case 'm': use_min_tri = true; num_opts++; break; case 'p': pthread = true; num_opts++; break; case 'N': nnodes = atoi(optarg); num_opts++; break; case 'o': outdir = std::string(optarg); num_opts++; break; default: print_usage(); } } if (outdir.empty()) fprintf(stderr, "\n\n**[WARNING]**: No output dir specified with '-o' " " flag means no output will be saved!\n\n"); BOOST_ASSERT_MSG(!(init=="none" && centersfn.empty()), "Centers file name doesn't exit!"); if (kpmbase::filesize(datafn.c_str()) != (sizeof(double)*nrow*ncol)) throw kpmbase::io_exception("File size does not match input size."); double* p_centers = NULL; kpmbase::kmeans_t ret; if (kpmbase::is_file_exist(centersfn.c_str())) { p_centers = new double [k*ncol]; kpmbase::bin_io<double> br2(centersfn, k, ncol); br2.read(p_centers); printf("Read centers!\n"); } else printf("No centers to read ..\n"); if (pthread) { if (use_min_tri) { kpmprune::kmeans_task_coordinator::ptr kc = kpmprune::kmeans_task_coordinator::create( datafn, nrow, ncol, k, max_iters, nnodes, nthread, p_centers, init, tolerance, dist_type); ret = kc->run_kmeans(); } else { kpmeans::kmeans_coordinator::ptr kc = kpmeans::kmeans_coordinator::create(datafn, nrow, ncol, k, max_iters, nnodes, nthread, p_centers, init, tolerance, dist_type); ret = kc->run_kmeans(); } } else { kpmbase::bin_io<double> br(datafn, nrow, ncol); double* p_data = new double [nrow*ncol]; br.read(p_data); printf("Read data!\n"); unsigned* p_clust_asgns = new unsigned [nrow]; size_t* p_clust_asgn_cnt = new size_t [k]; if (NULL == p_centers) // We have no preallocated centers p_centers = new double [k*ncol]; if (use_min_tri) { ret = kpmeans::omp::compute_min_kmeans(p_data, p_centers, p_clust_asgns, p_clust_asgn_cnt, nrow, ncol, k, max_iters, nthread, init, tolerance, dist_type); } else { ret = kpmeans::omp::compute_kmeans(p_data, p_centers, p_clust_asgns, p_clust_asgn_cnt, nrow, ncol, k, max_iters, nthread, init, tolerance, dist_type); } delete [] p_clust_asgns; delete [] p_clust_asgn_cnt; delete [] p_data; } if (!outdir.empty()) { printf("\nWriting output to '%s'\n", outdir.c_str()); ret.write(outdir); } if (p_centers) delete [] p_centers; return EXIT_SUCCESS; } void print_usage() { fprintf(stderr, "kpmeans data-file num-rows num-cols k [alg-options]\n"); fprintf(stderr, "-t type: type of initialization for kmeans" " ['random', 'forgy', 'kmeanspp', 'none']\n"); fprintf(stderr, "-T num_thread: The number of threads to run\n"); fprintf(stderr, "-i iters: maximum number of iterations\n"); fprintf(stderr, "-C File with initial clusters in same format as data\n"); fprintf(stderr, "-l tolerance for convergence (1E-6)\n"); fprintf(stderr, "-d Distance metric [eucl,cos]\n"); fprintf(stderr, "-m Use the minimal triangle inequality (~Elkan's alg)\n"); fprintf(stderr, "-p Use p-threads for ||ization rather than OMP\n"); fprintf(stderr, "-N No. of numa nodes you want to use\n"); fprintf(stderr, "-o Write output to an output directory of this name\n"); exit(EXIT_FAILURE); } <commit_msg>knori: made pthreads + prune default. Commit closes #21<commit_after>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere (disa@jhu.edu) * * This file is part of k-par-means * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <limits> #include <numa.h> #include "signal.h" #include "io.hpp" #include "kmeans.hpp" #include "kmeans_coordinator.hpp" #include "kmeans_task_coordinator.hpp" #include "util.hpp" static void print_usage(); int main(int argc, char* argv[]) { if (argc < 5) { print_usage(); exit(EXIT_FAILURE); } int opt; std::string datafn = std::string(argv[1]); size_t nrow = atol(argv[2]); size_t ncol = atol(argv[3]); unsigned k = atol(argv[4]); std::string dist_type = "eucl"; std::string centersfn = ""; size_t max_iters=std::numeric_limits<size_t>::max(); std::string init = "kmeanspp"; unsigned nthread = kpmbase::get_num_omp_threads(); int num_opts = 0; double tolerance = -1; bool no_prune = false; bool omp = false; unsigned nnodes = numa_num_task_nodes(); std::string outdir = ""; // Increase by 3 -- getopt ignores argv[0] argv += 3; argc -= 3; signal(SIGINT, kpmbase::int_handler); while ((opt = getopt(argc, argv, "l:i:t:T:d:C:PON:o:")) != -1) { num_opts++; switch (opt) { case 'l': tolerance = atof(optarg); num_opts++; break; case 'i': max_iters = atol(optarg); num_opts++; break; case 't': init = optarg; num_opts++; break; case 'T': nthread = atoi(optarg); num_opts++; break; case 'd': dist_type = std::string(optarg); num_opts++; break; case 'C': centersfn = std::string(optarg); BOOST_ASSERT_MSG(kpmbase::is_file_exist(centersfn.c_str()), "Centers file name doesn't exit!"); init = "none"; // Ignore whatever you pass in num_opts++; break; case 'P': no_prune = true; num_opts++; break; case 'O': omp = true; num_opts++; break; case 'N': nnodes = atoi(optarg); num_opts++; break; case 'o': outdir = std::string(optarg); num_opts++; break; default: print_usage(); } } if (outdir.empty()) fprintf(stderr, "\n\n**[WARNING]**: No output dir specified with '-o' " " flag means no output will be saved!\n\n"); BOOST_ASSERT_MSG(!(init=="none" && centersfn.empty()), "Centers file name doesn't exit!"); if (kpmbase::filesize(datafn.c_str()) != (sizeof(double)*nrow*ncol)) throw kpmbase::io_exception("File size does not match input size."); double* p_centers = NULL; kpmbase::kmeans_t ret; if (kpmbase::is_file_exist(centersfn.c_str())) { p_centers = new double [k*ncol]; kpmbase::bin_io<double> br2(centersfn, k, ncol); br2.read(p_centers); printf("Read centers!\n"); } else printf("No centers to read ..\n"); if (omp) { kpmbase::bin_io<double> br(datafn, nrow, ncol); double* p_data = new double [nrow*ncol]; br.read(p_data); printf("Read data!\n"); unsigned* p_clust_asgns = new unsigned [nrow]; size_t* p_clust_asgn_cnt = new size_t [k]; if (NULL == p_centers) // We have no preallocated centers p_centers = new double [k*ncol]; if (no_prune) { ret = kpmeans::omp::compute_kmeans(p_data, p_centers, p_clust_asgns, p_clust_asgn_cnt, nrow, ncol, k, max_iters, nthread, init, tolerance, dist_type); } else { ret = kpmeans::omp::compute_min_kmeans(p_data, p_centers, p_clust_asgns, p_clust_asgn_cnt, nrow, ncol, k, max_iters, nthread, init, tolerance, dist_type); } delete [] p_clust_asgns; delete [] p_clust_asgn_cnt; delete [] p_data; } else { if (no_prune) { kpmeans::kmeans_coordinator::ptr kc = kpmeans::kmeans_coordinator::create(datafn, nrow, ncol, k, max_iters, nnodes, nthread, p_centers, init, tolerance, dist_type); ret = kc->run_kmeans(); } else { kpmprune::kmeans_task_coordinator::ptr kc = kpmprune::kmeans_task_coordinator::create( datafn, nrow, ncol, k, max_iters, nnodes, nthread, p_centers, init, tolerance, dist_type); ret = kc->run_kmeans(); } } if (!outdir.empty()) { printf("\nWriting output to '%s'\n", outdir.c_str()); ret.write(outdir); } if (p_centers) delete [] p_centers; return EXIT_SUCCESS; } void print_usage() { fprintf(stderr, "kpmeans data-file num-rows num-cols k [alg-options]\n"); fprintf(stderr, "-t type: type of initialization for kmeans" " ['random', 'forgy', 'kmeanspp', 'none']\n"); fprintf(stderr, "-T num_thread: The number of threads to run\n"); fprintf(stderr, "-i iters: maximum number of iterations\n"); fprintf(stderr, "-C File with initial clusters in same format as data\n"); fprintf(stderr, "-l tolerance for convergence (1E-6)\n"); fprintf(stderr, "-d Distance metric [eucl,cos]\n"); fprintf(stderr, "-P DO NOT use the minimal triangle inequality (~Elkan's alg)\n"); fprintf(stderr, "-O Use OpenMP for ||ization rather than fast pthreads\n"); fprintf(stderr, "-N No. of numa nodes you want to use\n"); fprintf(stderr, "-o Write output to an output directory of this name\n"); exit(EXIT_FAILURE); } <|endoftext|>
<commit_before>//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This diagnostic client prints out their diagnostic messages. // //===----------------------------------------------------------------------===// #include "TextDiagnosticPrinter.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Lexer.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Streams.h" #include <string> using namespace clang; static llvm::cl::opt<bool> NoShowColumn("fno-show-column", llvm::cl::desc("Do not include column number on diagnostics")); static llvm::cl::opt<bool> NoCaretDiagnostics("fno-caret-diagnostics", llvm::cl::desc("Do not include source line and caret with" " diagnostics")); void TextDiagnosticPrinter:: PrintIncludeStack(FullSourceLoc Pos) { if (Pos.isInvalid()) return; Pos = Pos.getLogicalLoc(); // Print out the other include frames first. PrintIncludeStack(Pos.getIncludeLoc()); unsigned LineNo = Pos.getLineNumber(); llvm::cerr << "In file included from " << Pos.getSourceName() << ":" << LineNo << ":\n"; } /// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s) /// any characters in LineNo that intersect the SourceRange. void TextDiagnosticPrinter::HighlightRange(const SourceRange &R, SourceManager& SourceMgr, unsigned LineNo, unsigned FileID, std::string &CaratLine, const std::string &SourceLine) { assert(CaratLine.size() == SourceLine.size() && "Expect a correspondence between source and carat line!"); if (!R.isValid()) return; SourceLocation LogicalStart = SourceMgr.getLogicalLoc(R.getBegin()); unsigned StartLineNo = SourceMgr.getLineNumber(LogicalStart); if (StartLineNo > LineNo || LogicalStart.getFileID() != FileID) return; // No intersection. SourceLocation LogicalEnd = SourceMgr.getLogicalLoc(R.getEnd()); unsigned EndLineNo = SourceMgr.getLineNumber(LogicalEnd); if (EndLineNo < LineNo || LogicalStart.getFileID() != FileID) return; // No intersection. // Compute the column number of the start. unsigned StartColNo = 0; if (StartLineNo == LineNo) { StartColNo = SourceMgr.getLogicalColumnNumber(R.getBegin()); if (StartColNo) --StartColNo; // Zero base the col #. } // Pick the first non-whitespace column. while (StartColNo < SourceLine.size() && (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t')) ++StartColNo; // Compute the column number of the end. unsigned EndColNo = CaratLine.size(); if (EndLineNo == LineNo) { EndColNo = SourceMgr.getLogicalColumnNumber(R.getEnd()); if (EndColNo) { --EndColNo; // Zero base the col #. // Add in the length of the token, so that we cover multi-char tokens. EndColNo += Lexer::MeasureTokenLength(R.getEnd(), SourceMgr); } else { EndColNo = CaratLine.size(); } } // Pick the last non-whitespace column. while (EndColNo-1 && (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t')) --EndColNo; // Fill the range with ~'s. assert(StartColNo <= EndColNo && "Invalid range!"); for (unsigned i = StartColNo; i != EndColNo; ++i) CaratLine[i] = '~'; } void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic &Diags, Diagnostic::Level Level, FullSourceLoc Pos, diag::kind ID, const std::string *Strs, unsigned NumStrs, const SourceRange *Ranges, unsigned NumRanges) { unsigned LineNo = 0, ColNo = 0; unsigned FileID = 0; const char *LineStart = 0, *LineEnd = 0; if (Pos.isValid()) { FullSourceLoc LPos = Pos.getLogicalLoc(); LineNo = LPos.getLineNumber(); FileID = LPos.getLocation().getFileID(); // First, if this diagnostic is not in the main file, print out the // "included from" lines. if (LastWarningLoc != LPos.getIncludeLoc()) { LastWarningLoc = LPos.getIncludeLoc(); PrintIncludeStack(LastWarningLoc); } // Compute the column number. Rewind from the current position to the start // of the line. ColNo = LPos.getColumnNumber(); const char *TokLogicalPtr = LPos.getCharacterData(); LineStart = TokLogicalPtr-ColNo+1; // Column # is 1-based // Compute the line end. Scan forward from the error position to the end of // the line. const llvm::MemoryBuffer *Buffer = LPos.getBuffer(); const char *BufEnd = Buffer->getBufferEnd(); LineEnd = TokLogicalPtr; while (LineEnd != BufEnd && *LineEnd != '\n' && *LineEnd != '\r') ++LineEnd; llvm::cerr << Buffer->getBufferIdentifier() << ":" << LineNo << ":"; if (ColNo && !NoShowColumn) llvm::cerr << ColNo << ":"; llvm::cerr << " "; } switch (Level) { default: assert(0 && "Unknown diagnostic type!"); case Diagnostic::Note: llvm::cerr << "note: "; break; case Diagnostic::Warning: llvm::cerr << "warning: "; break; case Diagnostic::Error: llvm::cerr << "error: "; break; case Diagnostic::Fatal: llvm::cerr << "fatal error: "; break; break; } llvm::cerr << FormatDiagnostic(Diags, Level, ID, Strs, NumStrs) << "\n"; if (!NoCaretDiagnostics && Pos.isValid() && ((LastLoc != Pos) && !Ranges)) { // Cache the LastLoc, it allows us to omit duplicate source/caret spewage. LastLoc = Pos; // Get the line of the source file. std::string SourceLine(LineStart, LineEnd); // Create a line for the carat that is filled with spaces that is the same // length as the line of source code. std::string CaratLine(LineEnd-LineStart, ' '); // Highlight all of the characters covered by Ranges with ~ characters. for (unsigned i = 0; i != NumRanges; ++i) HighlightRange(Ranges[i], Pos.getManager(), LineNo, FileID, CaratLine, SourceLine); // Next, insert the carat itself. if (ColNo-1 < CaratLine.size()) CaratLine[ColNo-1] = '^'; else CaratLine.push_back('^'); // Scan the source line, looking for tabs. If we find any, manually expand // them to 8 characters and update the CaratLine to match. for (unsigned i = 0; i != SourceLine.size(); ++i) { if (SourceLine[i] != '\t') continue; // Replace this tab with at least one space. SourceLine[i] = ' '; // Compute the number of spaces we need to insert. unsigned NumSpaces = ((i+8)&~7) - (i+1); assert(NumSpaces < 8 && "Invalid computation of space amt"); // Insert spaces into the SourceLine. SourceLine.insert(i+1, NumSpaces, ' '); // Insert spaces or ~'s into CaratLine. CaratLine.insert(i+1, NumSpaces, CaratLine[i] == '~' ? '~' : ' '); } // Finally, remove any blank spaces from the end of CaratLine. while (CaratLine[CaratLine.size()-1] == ' ') CaratLine.erase(CaratLine.end()-1); // Emit what we have computed. llvm::cerr << SourceLine << "\n"; llvm::cerr << CaratLine << "\n"; } } <commit_msg><commit_after>//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This diagnostic client prints out their diagnostic messages. // //===----------------------------------------------------------------------===// #include "TextDiagnosticPrinter.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Lexer.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Streams.h" #include <string> using namespace clang; static llvm::cl::opt<bool> NoShowColumn("fno-show-column", llvm::cl::desc("Do not include column number on diagnostics")); static llvm::cl::opt<bool> NoCaretDiagnostics("fno-caret-diagnostics", llvm::cl::desc("Do not include source line and caret with" " diagnostics")); void TextDiagnosticPrinter:: PrintIncludeStack(FullSourceLoc Pos) { if (Pos.isInvalid()) return; Pos = Pos.getLogicalLoc(); // Print out the other include frames first. PrintIncludeStack(Pos.getIncludeLoc()); unsigned LineNo = Pos.getLineNumber(); llvm::cerr << "In file included from " << Pos.getSourceName() << ":" << LineNo << ":\n"; } /// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s) /// any characters in LineNo that intersect the SourceRange. void TextDiagnosticPrinter::HighlightRange(const SourceRange &R, SourceManager& SourceMgr, unsigned LineNo, unsigned FileID, std::string &CaratLine, const std::string &SourceLine) { assert(CaratLine.size() == SourceLine.size() && "Expect a correspondence between source and carat line!"); if (!R.isValid()) return; SourceLocation LogicalStart = SourceMgr.getLogicalLoc(R.getBegin()); unsigned StartLineNo = SourceMgr.getLineNumber(LogicalStart); if (StartLineNo > LineNo || LogicalStart.getFileID() != FileID) return; // No intersection. SourceLocation LogicalEnd = SourceMgr.getLogicalLoc(R.getEnd()); unsigned EndLineNo = SourceMgr.getLineNumber(LogicalEnd); if (EndLineNo < LineNo || LogicalStart.getFileID() != FileID) return; // No intersection. // Compute the column number of the start. unsigned StartColNo = 0; if (StartLineNo == LineNo) { StartColNo = SourceMgr.getLogicalColumnNumber(R.getBegin()); if (StartColNo) --StartColNo; // Zero base the col #. } // Pick the first non-whitespace column. while (StartColNo < SourceLine.size() && (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t')) ++StartColNo; // Compute the column number of the end. unsigned EndColNo = CaratLine.size(); if (EndLineNo == LineNo) { EndColNo = SourceMgr.getLogicalColumnNumber(R.getEnd()); if (EndColNo) { --EndColNo; // Zero base the col #. // Add in the length of the token, so that we cover multi-char tokens. EndColNo += Lexer::MeasureTokenLength(R.getEnd(), SourceMgr); } else { EndColNo = CaratLine.size(); } } // Pick the last non-whitespace column. while (EndColNo-1 && (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t')) --EndColNo; // Fill the range with ~'s. assert(StartColNo <= EndColNo && "Invalid range!"); for (unsigned i = StartColNo; i != EndColNo; ++i) CaratLine[i] = '~'; } void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic &Diags, Diagnostic::Level Level, FullSourceLoc Pos, diag::kind ID, const std::string *Strs, unsigned NumStrs, const SourceRange *Ranges, unsigned NumRanges) { unsigned LineNo = 0, ColNo = 0; unsigned FileID = 0; const char *LineStart = 0, *LineEnd = 0; if (Pos.isValid()) { FullSourceLoc LPos = Pos.getLogicalLoc(); LineNo = LPos.getLineNumber(); FileID = LPos.getLocation().getFileID(); // First, if this diagnostic is not in the main file, print out the // "included from" lines. if (LastWarningLoc != LPos.getIncludeLoc()) { LastWarningLoc = LPos.getIncludeLoc(); PrintIncludeStack(LastWarningLoc); } // Compute the column number. Rewind from the current position to the start // of the line. ColNo = LPos.getColumnNumber(); const char *TokLogicalPtr = LPos.getCharacterData(); LineStart = TokLogicalPtr-ColNo+1; // Column # is 1-based // Compute the line end. Scan forward from the error position to the end of // the line. const llvm::MemoryBuffer *Buffer = LPos.getBuffer(); const char *BufEnd = Buffer->getBufferEnd(); LineEnd = TokLogicalPtr; while (LineEnd != BufEnd && *LineEnd != '\n' && *LineEnd != '\r') ++LineEnd; llvm::cerr << Buffer->getBufferIdentifier() << ":" << LineNo << ":"; if (ColNo && !NoShowColumn) llvm::cerr << ColNo << ":"; llvm::cerr << " "; } switch (Level) { default: assert(0 && "Unknown diagnostic type!"); case Diagnostic::Note: llvm::cerr << "note: "; break; case Diagnostic::Warning: llvm::cerr << "warning: "; break; case Diagnostic::Error: llvm::cerr << "error: "; break; case Diagnostic::Fatal: llvm::cerr << "fatal error: "; break; break; } llvm::cerr << FormatDiagnostic(Diags, Level, ID, Strs, NumStrs) << "\n"; if (!NoCaretDiagnostics && Pos.isValid() && ((LastLoc != Pos) || Ranges)) { // Cache the LastLoc, it allows us to omit duplicate source/caret spewage. LastLoc = Pos; // Get the line of the source file. std::string SourceLine(LineStart, LineEnd); // Create a line for the carat that is filled with spaces that is the same // length as the line of source code. std::string CaratLine(LineEnd-LineStart, ' '); // Highlight all of the characters covered by Ranges with ~ characters. for (unsigned i = 0; i != NumRanges; ++i) HighlightRange(Ranges[i], Pos.getManager(), LineNo, FileID, CaratLine, SourceLine); // Next, insert the carat itself. if (ColNo-1 < CaratLine.size()) CaratLine[ColNo-1] = '^'; else CaratLine.push_back('^'); // Scan the source line, looking for tabs. If we find any, manually expand // them to 8 characters and update the CaratLine to match. for (unsigned i = 0; i != SourceLine.size(); ++i) { if (SourceLine[i] != '\t') continue; // Replace this tab with at least one space. SourceLine[i] = ' '; // Compute the number of spaces we need to insert. unsigned NumSpaces = ((i+8)&~7) - (i+1); assert(NumSpaces < 8 && "Invalid computation of space amt"); // Insert spaces into the SourceLine. SourceLine.insert(i+1, NumSpaces, ' '); // Insert spaces or ~'s into CaratLine. CaratLine.insert(i+1, NumSpaces, CaratLine[i] == '~' ? '~' : ' '); } // Finally, remove any blank spaces from the end of CaratLine. while (CaratLine[CaratLine.size()-1] == ' ') CaratLine.erase(CaratLine.end()-1); // Emit what we have computed. llvm::cerr << SourceLine << "\n"; llvm::cerr << CaratLine << "\n"; } } <|endoftext|>
<commit_before><commit_msg>put alignments in the right place<commit_after><|endoftext|>
<commit_before>/* * This file is part of Wireless Display Software for Linux OS * * Copyright (C) 2014 Intel Corporation. * * Contact: Jussi Laako <jussi.laako@linux.intel.com> * * 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 */ #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include <algorithm> #include <memory> #include <unistd.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include "mirac-network.hpp" #define MIRAC_MAX_NAMELEN 255 MiracNetwork::MiracNetwork () { Init(); } MiracNetwork::MiracNetwork (int conn_handle) { Init(); handle = conn_handle; } MiracNetwork::~MiracNetwork () { Close(); } void MiracNetwork::Init () { long ps; handle = -1; ps = sysconf(_SC_PAGESIZE); page_size = (ps <= 0) ? 4096 : static_cast<size_t> (ps); conn_ares = NULL; } void MiracNetwork::Close () { if (handle >= 0) close(handle); handle = -1; if (conn_ares) { freeaddrinfo(reinterpret_cast<struct addrinfo *> (conn_ares)); conn_ares = NULL; } } void MiracNetwork::Bind (const char *address, const char *service) { int ec; int reuse = 1; struct addrinfo *addr_res = NULL; struct addrinfo *bind_addr; struct addrinfo addr_hint; Close(); memset(&addr_hint, 0x00, sizeof(addr_hint)); addr_hint.ai_flags = AI_PASSIVE; ec = getaddrinfo(address, service, &addr_hint, &addr_res); if (ec) throw MiracException(gai_strerror(ec), __FUNCTION__); bind_addr = addr_res; while (bind_addr) { /* note, the SOCK_NONBLOCK is specific to Linux 2.6.27+, * on other platforms use either fcntl() or ioctl(h, FIONBIO, 1) */ handle = socket(addr_res->ai_family, addr_res->ai_socktype | SOCK_NONBLOCK, addr_res->ai_protocol); if (handle < 0) throw MiracException(errno, "socket()", __FUNCTION__); if (setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) throw MiracException(errno, "setsockopt()", __FUNCTION__); if (bind(handle, bind_addr->ai_addr, bind_addr->ai_addrlen) == 0) break; else if (!bind_addr->ai_next) throw MiracException(errno, "bind()", __FUNCTION__); close(handle); bind_addr = bind_addr->ai_next; } freeaddrinfo(addr_res); if (listen(handle, 1)) throw MiracException(errno, "listen()", __FUNCTION__); } MiracNetwork * MiracNetwork::Accept () { int ch; int nonblock = 1; ch = accept(handle, NULL, NULL); if (ch < 0) throw MiracException(errno, "accept()", __FUNCTION__); if (ioctl(ch, FIONBIO, &nonblock)) throw MiracException(errno, "ioctl(FIONBIO)", __FUNCTION__); return new MiracNetwork(ch); } bool MiracNetwork::Connect (const char *address, const char *service) { int ec = 0; if (address && service) { Close(); struct addrinfo addr_hint; memset(&addr_hint, 0x00, sizeof(addr_hint)); addr_hint.ai_socktype = SOCK_STREAM; ec = getaddrinfo(address, service, &addr_hint, reinterpret_cast<struct addrinfo **> (&conn_ares)); if (ec) throw MiracException(gai_strerror(ec), __FUNCTION__); conn_aptr = conn_ares; } else { socklen_t optlen = sizeof(ec); if (getsockopt(handle, SOL_SOCKET, SO_ERROR, &ec, &optlen)) throw MiracException(errno, "getsockopt()", __FUNCTION__); if (!ec) return true; conn_aptr = reinterpret_cast<struct addrinfo *> (conn_aptr)->ai_next; } struct addrinfo *addr = reinterpret_cast<struct addrinfo *> (conn_aptr); if (!addr) throw MiracException("peer unavailable", __FUNCTION__); /* note, the SOCK_NONBLOCK is specific to Linux 2.6.27+, * on other platforms use either fcntl() or ioctl(h, FIONBIO, 1) */ handle = socket(addr->ai_family, addr->ai_socktype | SOCK_NONBLOCK, addr->ai_protocol); if (handle < 0) throw MiracException(errno, "socket()", __FUNCTION__); if (connect(handle, addr->ai_addr, addr->ai_addrlen)) { if (errno == EINPROGRESS) return false; throw MiracException(errno, "connect()", __FUNCTION__); } return true; } std::string MiracNetwork::GetPeerAddress () { int ec; socklen_t addrsize = std::max(sizeof(sockaddr_in), sizeof(sockaddr_in6)); std::unique_ptr<uint8_t []> addrbuf(new uint8_t[addrsize]); std::unique_ptr<char []> namebuf(new char [MIRAC_MAX_NAMELEN + 1]); std::unique_ptr<char []> servbuf(new char [MIRAC_MAX_NAMELEN + 1]); if (getpeername(handle, reinterpret_cast<struct sockaddr *> (addrbuf.get()), &addrsize)) throw MiracException(errno, "getpeername()", __FUNCTION__); ec = getnameinfo( reinterpret_cast<struct sockaddr *> (addrbuf.get()), addrsize, namebuf.get(), MIRAC_MAX_NAMELEN, servbuf.get(), MIRAC_MAX_NAMELEN, NI_NOFQDN|NI_NUMERICHOST|NI_NUMERICSERV); if (ec) throw MiracException(gai_strerror(ec), __FUNCTION__); return std::string(namebuf.get()); } unsigned short MiracNetwork::GetHostPort () { socklen_t addrsize = std::max(sizeof(sockaddr_in), sizeof(sockaddr_in6)); std::unique_ptr<uint8_t []> addrbuf(new uint8_t[addrsize]); if (getsockname(handle, reinterpret_cast<struct sockaddr *> (addrbuf.get()), &addrsize)) throw MiracException(errno, "getsockname()", __FUNCTION__); struct sockaddr *saddr = reinterpret_cast<struct sockaddr *> (addrbuf.get()); if (saddr->sa_family == AF_INET) { struct sockaddr_in *ip4addr = reinterpret_cast<struct sockaddr_in *> (saddr); return ntohs(ip4addr->sin_port); } else if (saddr->sa_family == AF_INET6) { struct sockaddr_in6 *ip6addr = reinterpret_cast<struct sockaddr_in6 *> (saddr); return ntohs(ip6addr->sin6_port); } return 0; } bool MiracNetwork::Receive (std::string &message) { int ec; char nb[page_size]; do { ec = recv(handle, nb, page_size, 0); if (ec > 0) message.append(nb, ec); else if (ec < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; throw MiracException(errno, "recv()", __FUNCTION__); } else // ec == 0 throw MiracConnectionLostException( __FUNCTION__); } while (ec > 0); return true; } bool MiracNetwork::Receive (std::string &message, size_t length) { int ec; char nb[page_size]; do { ec = recv(handle, nb, page_size, 0); if (ec > 0) recv_buf.append(nb, ec); else if (ec < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; throw MiracException(errno, "recv()", __FUNCTION__); } else // ec == 0 throw MiracConnectionLostException( __FUNCTION__); } while (ec > 0); if (recv_buf.size() < length) return false; message = recv_buf.substr(0, length); recv_buf.erase(0, length); return true; } bool MiracNetwork::Send (const std::string &message) { int ec; if (!message.empty()) send_buf.append(message); do { ec = send(handle, send_buf.c_str(), send_buf.size(), MSG_NOSIGNAL); if (ec > 0) send_buf.erase(0, ec); else { if (errno == EAGAIN || errno == EWOULDBLOCK) return false; if (errno == EPIPE || errno == ENOTCONN) throw MiracConnectionLostException(__FUNCTION__); throw MiracException(errno, "send()", __FUNCTION__); } } while (send_buf.size() > 0); return true; } <commit_msg>Handle 'Connection reset by peer' gracefully<commit_after>/* * This file is part of Wireless Display Software for Linux OS * * Copyright (C) 2014 Intel Corporation. * * Contact: Jussi Laako <jussi.laako@linux.intel.com> * * 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 */ #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include <algorithm> #include <memory> #include <unistd.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include "mirac-network.hpp" #define MIRAC_MAX_NAMELEN 255 MiracNetwork::MiracNetwork () { Init(); } MiracNetwork::MiracNetwork (int conn_handle) { Init(); handle = conn_handle; } MiracNetwork::~MiracNetwork () { Close(); } void MiracNetwork::Init () { long ps; handle = -1; ps = sysconf(_SC_PAGESIZE); page_size = (ps <= 0) ? 4096 : static_cast<size_t> (ps); conn_ares = NULL; } void MiracNetwork::Close () { if (handle >= 0) close(handle); handle = -1; if (conn_ares) { freeaddrinfo(reinterpret_cast<struct addrinfo *> (conn_ares)); conn_ares = NULL; } } void MiracNetwork::Bind (const char *address, const char *service) { int ec; int reuse = 1; struct addrinfo *addr_res = NULL; struct addrinfo *bind_addr; struct addrinfo addr_hint; Close(); memset(&addr_hint, 0x00, sizeof(addr_hint)); addr_hint.ai_flags = AI_PASSIVE; ec = getaddrinfo(address, service, &addr_hint, &addr_res); if (ec) throw MiracException(gai_strerror(ec), __FUNCTION__); bind_addr = addr_res; while (bind_addr) { /* note, the SOCK_NONBLOCK is specific to Linux 2.6.27+, * on other platforms use either fcntl() or ioctl(h, FIONBIO, 1) */ handle = socket(addr_res->ai_family, addr_res->ai_socktype | SOCK_NONBLOCK, addr_res->ai_protocol); if (handle < 0) throw MiracException(errno, "socket()", __FUNCTION__); if (setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))) throw MiracException(errno, "setsockopt()", __FUNCTION__); if (bind(handle, bind_addr->ai_addr, bind_addr->ai_addrlen) == 0) break; else if (!bind_addr->ai_next) throw MiracException(errno, "bind()", __FUNCTION__); close(handle); bind_addr = bind_addr->ai_next; } freeaddrinfo(addr_res); if (listen(handle, 1)) throw MiracException(errno, "listen()", __FUNCTION__); } MiracNetwork * MiracNetwork::Accept () { int ch; int nonblock = 1; ch = accept(handle, NULL, NULL); if (ch < 0) throw MiracException(errno, "accept()", __FUNCTION__); if (ioctl(ch, FIONBIO, &nonblock)) throw MiracException(errno, "ioctl(FIONBIO)", __FUNCTION__); return new MiracNetwork(ch); } bool MiracNetwork::Connect (const char *address, const char *service) { int ec = 0; if (address && service) { Close(); struct addrinfo addr_hint; memset(&addr_hint, 0x00, sizeof(addr_hint)); addr_hint.ai_socktype = SOCK_STREAM; ec = getaddrinfo(address, service, &addr_hint, reinterpret_cast<struct addrinfo **> (&conn_ares)); if (ec) throw MiracException(gai_strerror(ec), __FUNCTION__); conn_aptr = conn_ares; } else { socklen_t optlen = sizeof(ec); if (getsockopt(handle, SOL_SOCKET, SO_ERROR, &ec, &optlen)) throw MiracException(errno, "getsockopt()", __FUNCTION__); if (!ec) return true; conn_aptr = reinterpret_cast<struct addrinfo *> (conn_aptr)->ai_next; } struct addrinfo *addr = reinterpret_cast<struct addrinfo *> (conn_aptr); if (!addr) throw MiracException("peer unavailable", __FUNCTION__); /* note, the SOCK_NONBLOCK is specific to Linux 2.6.27+, * on other platforms use either fcntl() or ioctl(h, FIONBIO, 1) */ handle = socket(addr->ai_family, addr->ai_socktype | SOCK_NONBLOCK, addr->ai_protocol); if (handle < 0) throw MiracException(errno, "socket()", __FUNCTION__); if (connect(handle, addr->ai_addr, addr->ai_addrlen)) { if (errno == EINPROGRESS) return false; throw MiracException(errno, "connect()", __FUNCTION__); } return true; } std::string MiracNetwork::GetPeerAddress () { int ec; socklen_t addrsize = std::max(sizeof(sockaddr_in), sizeof(sockaddr_in6)); std::unique_ptr<uint8_t []> addrbuf(new uint8_t[addrsize]); std::unique_ptr<char []> namebuf(new char [MIRAC_MAX_NAMELEN + 1]); std::unique_ptr<char []> servbuf(new char [MIRAC_MAX_NAMELEN + 1]); if (getpeername(handle, reinterpret_cast<struct sockaddr *> (addrbuf.get()), &addrsize)) throw MiracException(errno, "getpeername()", __FUNCTION__); ec = getnameinfo( reinterpret_cast<struct sockaddr *> (addrbuf.get()), addrsize, namebuf.get(), MIRAC_MAX_NAMELEN, servbuf.get(), MIRAC_MAX_NAMELEN, NI_NOFQDN|NI_NUMERICHOST|NI_NUMERICSERV); if (ec) throw MiracException(gai_strerror(ec), __FUNCTION__); return std::string(namebuf.get()); } unsigned short MiracNetwork::GetHostPort () { socklen_t addrsize = std::max(sizeof(sockaddr_in), sizeof(sockaddr_in6)); std::unique_ptr<uint8_t []> addrbuf(new uint8_t[addrsize]); if (getsockname(handle, reinterpret_cast<struct sockaddr *> (addrbuf.get()), &addrsize)) throw MiracException(errno, "getsockname()", __FUNCTION__); struct sockaddr *saddr = reinterpret_cast<struct sockaddr *> (addrbuf.get()); if (saddr->sa_family == AF_INET) { struct sockaddr_in *ip4addr = reinterpret_cast<struct sockaddr_in *> (saddr); return ntohs(ip4addr->sin_port); } else if (saddr->sa_family == AF_INET6) { struct sockaddr_in6 *ip6addr = reinterpret_cast<struct sockaddr_in6 *> (saddr); return ntohs(ip6addr->sin6_port); } return 0; } bool MiracNetwork::Receive (std::string &message) { int ec; char nb[page_size]; do { ec = recv(handle, nb, page_size, 0); if (ec > 0) message.append(nb, ec); else if (ec < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (errno == ECONNRESET) throw MiracConnectionLostException( __FUNCTION__); throw MiracException(errno, "recv()", __FUNCTION__); } else // ec == 0 throw MiracConnectionLostException( __FUNCTION__); } while (ec > 0); return true; } bool MiracNetwork::Receive (std::string &message, size_t length) { int ec; char nb[page_size]; do { ec = recv(handle, nb, page_size, 0); if (ec > 0) recv_buf.append(nb, ec); else if (ec < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (errno == ECONNRESET) throw MiracConnectionLostException( __FUNCTION__); throw MiracException(errno, "recv()", __FUNCTION__); } else // ec == 0 throw MiracConnectionLostException( __FUNCTION__); } while (ec > 0); if (recv_buf.size() < length) return false; message = recv_buf.substr(0, length); recv_buf.erase(0, length); return true; } bool MiracNetwork::Send (const std::string &message) { int ec; if (!message.empty()) send_buf.append(message); do { ec = send(handle, send_buf.c_str(), send_buf.size(), MSG_NOSIGNAL); if (ec > 0) send_buf.erase(0, ec); else { if (errno == EAGAIN || errno == EWOULDBLOCK) return false; if (errno == EPIPE || errno == ENOTCONN) throw MiracConnectionLostException(__FUNCTION__); throw MiracException(errno, "send()", __FUNCTION__); } } while (send_buf.size() > 0); return true; } <|endoftext|>
<commit_before>#include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/Registry> #include <osgTerrain/Locator> #include "ESRIType.h" #include "ESRIShape.h" #include "ESRIShapeParser.h" #include "XBaseParser.h" class ESRIShapeReaderWriter : public osgDB::ReaderWriter { public: ESRIShapeReaderWriter() {} virtual const char* className() { return "ESRI Shape ReaderWriter"; } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"shp"); } virtual ReadResult readObject(const std::string& fileName, const Options* opt) const { return readNode(fileName,opt); } virtual ReadResult readNode(const std::string& file, const Options* options) const { std::string ext = osgDB::getFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile(file, options); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; bool useDouble = false; if (options && options->getOptionString().find("double")!=std::string::npos) { useDouble = true; } ESRIShape::ESRIShapeParser sp(fileName, useDouble); std::string xbaseFileName(osgDB::getNameLessExtension(fileName) + ".dbf"); ESRIShape::XBaseParser xbp(xbaseFileName); if (sp.getGeode() && (xbp.getAttributeList().empty() == false)) { if (sp.getGeode()->getNumDrawables() != xbp.getAttributeList().size()) { osg::notify(osg::WARN) << "ESRIShape loader : .dbf file containe different record number that .shp file." << std::endl << " .dbf record skipped." << std::endl; } else { osg::Geode * geode = sp.getGeode(); unsigned int i = 0; ESRIShape::XBaseParser::ShapeAttributeListList::iterator it, end = xbp.getAttributeList().end(); for (it = xbp.getAttributeList().begin(); it != end; ++it, ++i) { geode->getDrawable(i)->setUserData(it->get()); } } } if (sp.getGeode()) { std::string projFileName(osgDB::getNameLessExtension(fileName) + ".prj"); if (osgDB::fileExists(projFileName)) { std::ifstream fin(projFileName.c_str()); if (fin) { std::string projstring; while(!fin.eof()) { char readline[4096]; *readline = 0; fin.getline(readline, sizeof(readline)); if (!projstring.empty() && !fin.eof()) { projstring += '\n'; } projstring += readline; } if (!projstring.empty()) { osgTerrain::Locator* locator = new osgTerrain::Locator; sp.getGeode()->setUserData(locator); locator->setFormat("WKT"); locator->setCoordinateSystem(projstring); locator->setDefinedInFile(false); } } } } return sp.getGeode(); } }; REGISTER_OSGPLUGIN(shp, ESRIShapeReaderWriter) <commit_msg>Added option docs<commit_after>#include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/Registry> #include <osgTerrain/Locator> #include "ESRIType.h" #include "ESRIShape.h" #include "ESRIShapeParser.h" #include "XBaseParser.h" class ESRIShapeReaderWriter : public osgDB::ReaderWriter { public: ESRIShapeReaderWriter() { supportsExtension("shp","Geospatial Shape file format"); supportsOption("double","Read x,y,z data as double an stored as geometry in osg::Vec3dArray's."); } virtual const char* className() { return "ESRI Shape ReaderWriter"; } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"shp"); } virtual ReadResult readObject(const std::string& fileName, const Options* opt) const { return readNode(fileName,opt); } virtual ReadResult readNode(const std::string& file, const Options* options) const { std::string ext = osgDB::getFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile(file, options); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; bool useDouble = false; if (options && options->getOptionString().find("double")!=std::string::npos) { useDouble = true; } ESRIShape::ESRIShapeParser sp(fileName, useDouble); std::string xbaseFileName(osgDB::getNameLessExtension(fileName) + ".dbf"); ESRIShape::XBaseParser xbp(xbaseFileName); if (sp.getGeode() && (xbp.getAttributeList().empty() == false)) { if (sp.getGeode()->getNumDrawables() != xbp.getAttributeList().size()) { osg::notify(osg::WARN) << "ESRIShape loader : .dbf file containe different record number that .shp file." << std::endl << " .dbf record skipped." << std::endl; } else { osg::Geode * geode = sp.getGeode(); unsigned int i = 0; ESRIShape::XBaseParser::ShapeAttributeListList::iterator it, end = xbp.getAttributeList().end(); for (it = xbp.getAttributeList().begin(); it != end; ++it, ++i) { geode->getDrawable(i)->setUserData(it->get()); } } } if (sp.getGeode()) { std::string projFileName(osgDB::getNameLessExtension(fileName) + ".prj"); if (osgDB::fileExists(projFileName)) { std::ifstream fin(projFileName.c_str()); if (fin) { std::string projstring; while(!fin.eof()) { char readline[4096]; *readline = 0; fin.getline(readline, sizeof(readline)); if (!projstring.empty() && !fin.eof()) { projstring += '\n'; } projstring += readline; } if (!projstring.empty()) { osgTerrain::Locator* locator = new osgTerrain::Locator; sp.getGeode()->setUserData(locator); locator->setFormat("WKT"); locator->setCoordinateSystem(projstring); locator->setDefinedInFile(false); } } } } return sp.getGeode(); } }; REGISTER_OSGPLUGIN(shp, ESRIShapeReaderWriter) <|endoftext|>
<commit_before>/************************************************************************** *** *** Copyright (c) 1995-2000 Regents of the University of California, *** Andrew E. Caldwell, Andrew B. Kahng and Igor L. Markov *** Copyright (c) 2000-2007 Regents of the University of Michigan, *** Saurabh N. Adya, Jarrod A. Roy, David A. Papa and *** Igor L. Markov *** *** Contact author(s): abk@cs.ucsd.edu, imarkov@umich.edu *** Original Affiliation: UCLA, Computer Science Department, *** Los Angeles, CA 90095-1596 USA *** *** 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. *** *** ***************************************************************************/ // Created : November 1997, Mike Oliver, VLSI CAD ABKGROUP UCLA // 020811 ilm ported to g++ 3.0 #ifdef _MSC_VER #pragma warning(disable : 4786) #endif #include "abkrand.h" #include "abkMD5.h" #include <fstream> #include <cstdio> #ifdef _MSC_VER #define _X86_ #include <windows.h> #include <process.h> #else #include <unistd.h> #endif using std::ios; using std::ofstream; using std::ifstream; using std::cout; using std::cerr; using std::endl; ofstream *SeedHandler::_PseedOutFile = NULL; ifstream *SeedHandler::_PseedInFile = NULL; unsigned SeedHandler::_nextSeed = UINT_MAX; bool SeedHandler::_loggingOff = false; bool SeedHandler::_haveRandObj = false; bool SeedHandler::_cleaned = false; unsigned SeedHandler::_externalSeed = UINT_MAX; unsigned SeedHandler::_progOverrideExternalSeed = UINT_MAX; std::map<std::string, unsigned, SeedHandlerCompareStrings> SeedHandler::_counters; SeedCleaner cleaner; // when this object goes out of scope at the end of // execution, it will make sure that SeedHandler::clean() // gets called //: Maintains all random seeds used by a process. // Idea: First time you create a random object, an initial nondeterministic // seed (also called the "external seed" is created from system // information and logged to seeds.out. // Any random object created with a seed of UINT_MAX ("nondeterministic"), // and that does not use the snazzy new "local independence" feature, // then uses seeds from a sequence starting with the initial value // and increasing by 1 with each new nondeterministic random object // created. // // If the seed is overridden with a value other than UINT_MAX it is used, // and logged to seeds.out . // // However if seeds.in exists, the initial nondeterministic value // is taken from the second line of seeds.in rather than the system // clock, and subsequent *deterministic* values are taken from successive // lines of seeds.in rather than from the value passed. // // If seeds.out is in use or other errors occur trying to create it, // a warning is generated that the seeds will not be logged, and // the initial nondeterministic seed is printed (which should be // sufficient to recreate the run provided that all "deterministic" // seeds truly *are* deterministic (e.g. don't depend on external // devices). // // You can disable the logging function by calling the static // function SeedHandler::turnOffLogging(). This will not disable // the ability to override seeding with seeds.in . // NEW ULTRA-COOL FEATURE: (17 June 1999) // You now have the option, which I (Mike) highly recommend, // of specifying, instead of a seed, a "local identifier", which // is a string that should identify uniquely the random variable // (not necessarily the random object) being used. The suggested // format of this string is as follows: If your // RNG is called _rng and is a member of MyClass, pass // the string "MyClass::_rng". If it's a local variable // called rng in the method MyClass::myMethod(), pass // the string "MyClass::myMethod(),_rng". // // SeedHandler will maintain a collection of counters associated // with each of these strings. The sequence of random numbers // from a random object will be determined by three things: // 1) the "external seed" (same as "initial nondeterm seed"). // 2) the "local identifier" (the string described above). // 3) the counter saying how many RNG objects have previously // been created with the same local identifier. // When any one of these changes, the output should be effectively // independent of the previous RNG. Moreover you don't have // to worry about your regressions changing simply because someone // else's code which you call has changed the number of RNG objects // it uses. // ANOTHER NEW FEATURE (21 February 2001) // At times you may wish to control the external seed yourself, e.g. // by specifying the seed on the command line, rather than // using either seeds.in or the nondeterministic chooser. // To enable this, a static method SeedHandler::overrideExternalSeed() // has been added. If you call this method before any random // object has been created, you can set the external seed. // The file seeds.out will still be created unless you call // SeedHandler::turnOffLogging(). If seeds.in exists, it // will control -- your call to overrideExternalSeed() will // print a warning message and otherwise be ignored. //**************************************************************************** //**************************************************************************** //**************************************************************************** void SeedHandler::_init() { abkfatal(!_cleaned, "Can't create random object" " after calling SeedHandler::clean()"); if (!_haveRandObj) { _chooseInitNondetSeed(); if (!_loggingOff) { _initializeOutFile(); } } _haveRandObj = true; } //**************************************************************************** //**************************************************************************** SeedHandler::SeedHandler(unsigned seed) : _locIdent(NULL), _counter(UINT_MAX), _isSeedMultipartite(false) { _init(); if (seed == UINT_MAX) _seed = _nextSeed++; else // deterministic seed, take value given unless // seeds.in exists with valid value { if (_PseedInFile) { *_PseedInFile >> _seed; // cerr << "Seed read was " << _seed << endl; if (_PseedInFile->fail()) // if we've run out, go back // to accepting // seeds given { _PseedInFile->close(); delete _PseedInFile; _PseedInFile = NULL; _seed = seed; // cerr << "But read failed, substituting seed " // << _seed; } } else _seed = seed; if (!_loggingOff) { abkfatal(_PseedOutFile, "Internal error: unable to log " "random seed to file"); *_PseedOutFile << _seed << endl; } } } //**************************************************************************** //**************************************************************************** SeedHandler::SeedHandler(const char *locIdent, unsigned counterOverride) : _isSeedMultipartite(true) { _init(); _locIdent = strdup(locIdent); if (counterOverride != UINT_MAX) _counter = counterOverride; else { std::map<std::string, unsigned, SeedHandlerCompareStrings>::iterator iC; iC = _counters.find(_locIdent); if (iC == _counters.end()) _counters[_locIdent] = _counter = 0; else { iC->second++; _counter = iC->second; } } } //**************************************************************************** //**************************************************************************** SeedHandler::~SeedHandler() { if (!_isSeedMultipartite) { abkassert(_locIdent == NULL, "Non-null _locIdent with old-style seed"); } else { free(_locIdent); _locIdent = NULL; } } //**************************************************************************** //**************************************************************************** void SeedHandler::turnOffLogging() { _loggingOff = true; } //**************************************************************************** //**************************************************************************** void SeedHandler::overrideExternalSeed(unsigned extseed) { abkfatal(!_haveRandObj, "Can't call SeedHandler::overrideExternalSeed() " "after creating a random object"); abkfatal(extseed != UINT_MAX, "Can't pass UINT_MAX to SeedHandler::overrideExternalSeed()"); _progOverrideExternalSeed = extseed; } //**************************************************************************** //**************************************************************************** void SeedHandler::clean() { _cleaned = true; if (_PseedOutFile) { _PseedOutFile->seekp(0, ios::beg); // rewind file _PseedOutFile->put('0'); // mark not in use _PseedOutFile->close(); } if (_PseedInFile) _PseedInFile->close(); delete _PseedOutFile; delete _PseedInFile; _PseedOutFile = NULL; _PseedInFile = NULL; } //**************************************************************************** //**************************************************************************** void SeedHandler::_chooseInitNondetSeed() { _PseedInFile = new ifstream("seeds.in", ios::in); if (!*_PseedInFile) { delete _PseedInFile; _PseedInFile = NULL; } if (_PseedInFile) { unsigned DummyInUseLine; cerr << "File seeds.in exists and will override all seeds, " "including " "hardcoded ones " << endl; *_PseedInFile >> DummyInUseLine; abkwarn(!DummyInUseLine, "File seeds.in appears to come from a process " "that never completed\n"); *_PseedInFile >> _nextSeed; // cerr << "Init nondet seed read was "<<_nextSeed << endl; abkfatal(!(_PseedInFile->fail()), "File seeds.in exists but program " "was unable to read initial seed " "therefrom."); abkwarn(_progOverrideExternalSeed == UINT_MAX, "\nThere is a programmatic override of the external seed," " which will be ignored because seeds.in exists"); } else if (_progOverrideExternalSeed == UINT_MAX) { // Timer tm; time_t utime, zero = 0; abkfatal(time(&utime) != -1, "Can't get time\n"); double tm = difftime(utime, zero); char buf[255]; unsigned procID = getpid(); unsigned rndbuf; FILE *rnd = fopen("/dev/urandom", "r"); if (rnd) { (void) fread(&rndbuf, sizeof(rndbuf), 1, rnd); fclose(rnd); sprintf(buf, "%g %d %d", tm, procID, rndbuf); } else sprintf(buf, "%g %d", tm, procID); MD5 hash(buf); _nextSeed = hash; } else { _nextSeed = _progOverrideExternalSeed; } _externalSeed = _nextSeed; } //**************************************************************************** //**************************************************************************** void SeedHandler::_initializeOutFile() { unsigned inUse; ifstream outFileAsInFile("seeds.out", ios::in); if (!!outFileAsInFile) { outFileAsInFile >> inUse; if (outFileAsInFile.fail()) { char errtxt[1023]; sprintf(errtxt, "Unable to determine whether file seeds.out is" " in use; random seeds from " "this process will not be logged.\n Initial non-" "deterministic seed is %u", _nextSeed); abkwarn(0, errtxt); _loggingOff = true; } else { if (inUse) { char errtxt[1023]; sprintf(errtxt, "File seeds.out is in use; random seeds " "from " "this process will not be logged.\nInitial " "non-" "deterministic seed is %u.\nIf there is no " "other process running in this directory, " "then " "an earlier\nprocess may have terminated\n" "abnormally. " "You should remove or rename seeds.out\n", _nextSeed); abkwarn(0, errtxt); _loggingOff = true; } } } outFileAsInFile.close(); if (!_loggingOff) { _PseedOutFile = new ofstream("seeds.out", ios::out); // overwrite file if (!_PseedOutFile) { char errtxt[1023]; sprintf(errtxt, "Unable to create file seeds.out; random seeds " "from " "this process will not be logged.\n Initial non-" "deterministic seed is %u", _nextSeed); abkwarn(0, errtxt); _loggingOff = true; delete _PseedOutFile; _PseedOutFile = NULL; } *_PseedOutFile << "1" << endl; // mark as in use *_PseedOutFile << _nextSeed << endl; // initial nondet seed } } //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** <commit_msg>par: quiet unused result warning again<commit_after>/************************************************************************** *** *** Copyright (c) 1995-2000 Regents of the University of California, *** Andrew E. Caldwell, Andrew B. Kahng and Igor L. Markov *** Copyright (c) 2000-2007 Regents of the University of Michigan, *** Saurabh N. Adya, Jarrod A. Roy, David A. Papa and *** Igor L. Markov *** *** Contact author(s): abk@cs.ucsd.edu, imarkov@umich.edu *** Original Affiliation: UCLA, Computer Science Department, *** Los Angeles, CA 90095-1596 USA *** *** 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. *** *** ***************************************************************************/ // Created : November 1997, Mike Oliver, VLSI CAD ABKGROUP UCLA // 020811 ilm ported to g++ 3.0 #ifdef _MSC_VER #pragma warning(disable : 4786) #endif #include "abkrand.h" #include "abkMD5.h" #include <fstream> #include <cstdio> #ifdef _MSC_VER #define _X86_ #include <windows.h> #include <process.h> #else #include <unistd.h> #endif using std::ios; using std::ofstream; using std::ifstream; using std::cout; using std::cerr; using std::endl; ofstream *SeedHandler::_PseedOutFile = NULL; ifstream *SeedHandler::_PseedInFile = NULL; unsigned SeedHandler::_nextSeed = UINT_MAX; bool SeedHandler::_loggingOff = false; bool SeedHandler::_haveRandObj = false; bool SeedHandler::_cleaned = false; unsigned SeedHandler::_externalSeed = UINT_MAX; unsigned SeedHandler::_progOverrideExternalSeed = UINT_MAX; std::map<std::string, unsigned, SeedHandlerCompareStrings> SeedHandler::_counters; SeedCleaner cleaner; // when this object goes out of scope at the end of // execution, it will make sure that SeedHandler::clean() // gets called //: Maintains all random seeds used by a process. // Idea: First time you create a random object, an initial nondeterministic // seed (also called the "external seed" is created from system // information and logged to seeds.out. // Any random object created with a seed of UINT_MAX ("nondeterministic"), // and that does not use the snazzy new "local independence" feature, // then uses seeds from a sequence starting with the initial value // and increasing by 1 with each new nondeterministic random object // created. // // If the seed is overridden with a value other than UINT_MAX it is used, // and logged to seeds.out . // // However if seeds.in exists, the initial nondeterministic value // is taken from the second line of seeds.in rather than the system // clock, and subsequent *deterministic* values are taken from successive // lines of seeds.in rather than from the value passed. // // If seeds.out is in use or other errors occur trying to create it, // a warning is generated that the seeds will not be logged, and // the initial nondeterministic seed is printed (which should be // sufficient to recreate the run provided that all "deterministic" // seeds truly *are* deterministic (e.g. don't depend on external // devices). // // You can disable the logging function by calling the static // function SeedHandler::turnOffLogging(). This will not disable // the ability to override seeding with seeds.in . // NEW ULTRA-COOL FEATURE: (17 June 1999) // You now have the option, which I (Mike) highly recommend, // of specifying, instead of a seed, a "local identifier", which // is a string that should identify uniquely the random variable // (not necessarily the random object) being used. The suggested // format of this string is as follows: If your // RNG is called _rng and is a member of MyClass, pass // the string "MyClass::_rng". If it's a local variable // called rng in the method MyClass::myMethod(), pass // the string "MyClass::myMethod(),_rng". // // SeedHandler will maintain a collection of counters associated // with each of these strings. The sequence of random numbers // from a random object will be determined by three things: // 1) the "external seed" (same as "initial nondeterm seed"). // 2) the "local identifier" (the string described above). // 3) the counter saying how many RNG objects have previously // been created with the same local identifier. // When any one of these changes, the output should be effectively // independent of the previous RNG. Moreover you don't have // to worry about your regressions changing simply because someone // else's code which you call has changed the number of RNG objects // it uses. // ANOTHER NEW FEATURE (21 February 2001) // At times you may wish to control the external seed yourself, e.g. // by specifying the seed on the command line, rather than // using either seeds.in or the nondeterministic chooser. // To enable this, a static method SeedHandler::overrideExternalSeed() // has been added. If you call this method before any random // object has been created, you can set the external seed. // The file seeds.out will still be created unless you call // SeedHandler::turnOffLogging(). If seeds.in exists, it // will control -- your call to overrideExternalSeed() will // print a warning message and otherwise be ignored. //**************************************************************************** //**************************************************************************** //**************************************************************************** void SeedHandler::_init() { abkfatal(!_cleaned, "Can't create random object" " after calling SeedHandler::clean()"); if (!_haveRandObj) { _chooseInitNondetSeed(); if (!_loggingOff) { _initializeOutFile(); } } _haveRandObj = true; } //**************************************************************************** //**************************************************************************** SeedHandler::SeedHandler(unsigned seed) : _locIdent(NULL), _counter(UINT_MAX), _isSeedMultipartite(false) { _init(); if (seed == UINT_MAX) _seed = _nextSeed++; else // deterministic seed, take value given unless // seeds.in exists with valid value { if (_PseedInFile) { *_PseedInFile >> _seed; // cerr << "Seed read was " << _seed << endl; if (_PseedInFile->fail()) // if we've run out, go back // to accepting // seeds given { _PseedInFile->close(); delete _PseedInFile; _PseedInFile = NULL; _seed = seed; // cerr << "But read failed, substituting seed " // << _seed; } } else _seed = seed; if (!_loggingOff) { abkfatal(_PseedOutFile, "Internal error: unable to log " "random seed to file"); *_PseedOutFile << _seed << endl; } } } //**************************************************************************** //**************************************************************************** SeedHandler::SeedHandler(const char *locIdent, unsigned counterOverride) : _isSeedMultipartite(true) { _init(); _locIdent = strdup(locIdent); if (counterOverride != UINT_MAX) _counter = counterOverride; else { std::map<std::string, unsigned, SeedHandlerCompareStrings>::iterator iC; iC = _counters.find(_locIdent); if (iC == _counters.end()) _counters[_locIdent] = _counter = 0; else { iC->second++; _counter = iC->second; } } } //**************************************************************************** //**************************************************************************** SeedHandler::~SeedHandler() { if (!_isSeedMultipartite) { abkassert(_locIdent == NULL, "Non-null _locIdent with old-style seed"); } else { free(_locIdent); _locIdent = NULL; } } //**************************************************************************** //**************************************************************************** void SeedHandler::turnOffLogging() { _loggingOff = true; } //**************************************************************************** //**************************************************************************** void SeedHandler::overrideExternalSeed(unsigned extseed) { abkfatal(!_haveRandObj, "Can't call SeedHandler::overrideExternalSeed() " "after creating a random object"); abkfatal(extseed != UINT_MAX, "Can't pass UINT_MAX to SeedHandler::overrideExternalSeed()"); _progOverrideExternalSeed = extseed; } //**************************************************************************** //**************************************************************************** void SeedHandler::clean() { _cleaned = true; if (_PseedOutFile) { _PseedOutFile->seekp(0, ios::beg); // rewind file _PseedOutFile->put('0'); // mark not in use _PseedOutFile->close(); } if (_PseedInFile) _PseedInFile->close(); delete _PseedOutFile; delete _PseedInFile; _PseedOutFile = NULL; _PseedInFile = NULL; } //**************************************************************************** //**************************************************************************** void SeedHandler::_chooseInitNondetSeed() { _PseedInFile = new ifstream("seeds.in", ios::in); if (!*_PseedInFile) { delete _PseedInFile; _PseedInFile = NULL; } if (_PseedInFile) { unsigned DummyInUseLine; cerr << "File seeds.in exists and will override all seeds, " "including " "hardcoded ones " << endl; *_PseedInFile >> DummyInUseLine; abkwarn(!DummyInUseLine, "File seeds.in appears to come from a process " "that never completed\n"); *_PseedInFile >> _nextSeed; // cerr << "Init nondet seed read was "<<_nextSeed << endl; abkfatal(!(_PseedInFile->fail()), "File seeds.in exists but program " "was unable to read initial seed " "therefrom."); abkwarn(_progOverrideExternalSeed == UINT_MAX, "\nThere is a programmatic override of the external seed," " which will be ignored because seeds.in exists"); } else if (_progOverrideExternalSeed == UINT_MAX) { // Timer tm; time_t utime, zero = 0; abkfatal(time(&utime) != -1, "Can't get time\n"); double tm = difftime(utime, zero); char buf[255]; unsigned procID = getpid(); unsigned rndbuf; FILE *rnd = fopen("/dev/urandom", "r"); if (rnd) { size_t x = fread(&rndbuf, sizeof(rndbuf), 1, rnd); (void) x; // unused fclose(rnd); sprintf(buf, "%g %d %d", tm, procID, rndbuf); } else sprintf(buf, "%g %d", tm, procID); MD5 hash(buf); _nextSeed = hash; } else { _nextSeed = _progOverrideExternalSeed; } _externalSeed = _nextSeed; } //**************************************************************************** //**************************************************************************** void SeedHandler::_initializeOutFile() { unsigned inUse; ifstream outFileAsInFile("seeds.out", ios::in); if (!!outFileAsInFile) { outFileAsInFile >> inUse; if (outFileAsInFile.fail()) { char errtxt[1023]; sprintf(errtxt, "Unable to determine whether file seeds.out is" " in use; random seeds from " "this process will not be logged.\n Initial non-" "deterministic seed is %u", _nextSeed); abkwarn(0, errtxt); _loggingOff = true; } else { if (inUse) { char errtxt[1023]; sprintf(errtxt, "File seeds.out is in use; random seeds " "from " "this process will not be logged.\nInitial " "non-" "deterministic seed is %u.\nIf there is no " "other process running in this directory, " "then " "an earlier\nprocess may have terminated\n" "abnormally. " "You should remove or rename seeds.out\n", _nextSeed); abkwarn(0, errtxt); _loggingOff = true; } } } outFileAsInFile.close(); if (!_loggingOff) { _PseedOutFile = new ofstream("seeds.out", ios::out); // overwrite file if (!_PseedOutFile) { char errtxt[1023]; sprintf(errtxt, "Unable to create file seeds.out; random seeds " "from " "this process will not be logged.\n Initial non-" "deterministic seed is %u", _nextSeed); abkwarn(0, errtxt); _loggingOff = true; delete _PseedOutFile; _PseedOutFile = NULL; } *_PseedOutFile << "1" << endl; // mark as in use *_PseedOutFile << _nextSeed << endl; // initial nondet seed } } //**************************************************************************** //**************************************************************************** //**************************************************************************** //**************************************************************************** <|endoftext|>
<commit_before>/* ** Copyright 2015 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <QMutexLocker> #include <QFileInfo> #include <QFile> #include <QDirIterator> #include <QDateTime> #include <set> #include <fstream> #include <sstream> #include "com/centreon/broker/dumper/directory_dumper.hh" #include "com/centreon/broker/dumper/internal.hh" #include "com/centreon/broker/dumper/dump.hh" #include "com/centreon/broker/dumper/remove.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::dumper; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] path Dumper path. * @param[in] tagname Dumper tagname. * @param[in] cache Persistent cache. */ directory_dumper::directory_dumper( std::string const& path, std::string const& tagname, misc::shared_ptr<persistent_cache> cache) try : _path(path), _tagname(tagname), _cache(cache) { // Set watcher timeout. _watcher.set_timeout(3000); // Get all the last modified timestamps from the cache. _get_last_timestamps_from_cache(); // Set the watch and the initial events. std::set<std::string> files_found = _set_watch_over_directory(path); // Remove deleted files. _remove_deleted_files(files_found); } catch (std::exception const& e) { throw (exceptions::msg() << "dumper: directory dumper couldn't initialize: " << e.what()); } /** * Destructor. */ directory_dumper::~directory_dumper() { try { // Save the last modified timestamps to the cache. _save_last_timestamps_to_cache(); } catch (std::exception const& e) { logging::error(logging::medium) << "dump: directory dumper error while trying to save the cache: " << e.what(); } } /** * Read data from the dumper. * * @param[out] d Next available event. * @param[in] deadline Timeout. * * @return Respect io::stream::read()'s return value. */ bool directory_dumper::read( misc::shared_ptr<io::data>& d, time_t deadline) { d.clear(); // Get an event already in the event list. if (!_event_list.empty()) { unsigned int type = _event_list.front().second->type(); if (type == dump::static_type()) _last_modified_timestamps[ _event_list.front().second.ref_as<dump>().filename.toStdString()] = _event_list.front().first; else if (type == dumper::remove::static_type()) _last_modified_timestamps.erase( _event_list.front().second.ref_as<dumper::remove>().filename.toStdString()); d = _event_list.front().second; _event_list.pop_front(); return (true); } // If no events, watch the directory for new events. std::vector<file::directory_event> events = _watcher.get_events(); for (std::vector<file::directory_event>::const_iterator it(events.begin()), end(events.end()); it != end; ++it) { if (it->get_type() == file::directory_event::directory_deleted && it->get_path() == _path) throw (exceptions::msg() << "dumper: directory '" << _path << "' deleted"); else if (it->get_type() == file::directory_event::deleted) { misc::shared_ptr<dumper::remove> d(new dumper::remove); d->filename = QString::fromStdString( _get_relative_filename(it->get_path())); d->tag = QString::fromStdString(_tagname); _event_list.push_back(std::make_pair(timestamp(), d)); } else if (it->get_type() == file::directory_event::created && it->get_file_type() == file::directory_event::directory) { _set_watch_over_directory(it->get_path()); } else if (it->get_file_type() == file::directory_event::file) _event_list.push_back(_dump_a_file(it->get_path())); } } /** * Write data to the dumper. * * @param[in] d Data to write. * * @return Always return 1, or throw exceptions. */ unsigned int directory_dumper::write(misc::shared_ptr<io::data> const& d) { (void)d; throw (exceptions::msg() << "dumper: attempt to write from a directory dumper stream"); return (1); } /** * Get the list of last modified timestamps from the persistent cache. */ void directory_dumper::_get_last_timestamps_from_cache() { // No cache, nothing to do. if (_cache.isNull()) return ; misc::shared_ptr<io::data> d; while (true) { _cache->get(d); if (d.isNull()) return; if (d->type() == timestamp_cache::static_type()) { timestamp_cache const& ts = d.ref_as<timestamp_cache const>(); _last_modified_timestamps[ts.filename.toStdString()] = ts.last_modified; } } } /** * Save the list of last modified timestamps to the persistent cache. */ void directory_dumper::_save_last_timestamps_to_cache() { // No cache, nothing to do. if (_cache.isNull()) return ; _cache->transaction(); for (std::map<std::string, timestamp>::const_iterator it(_last_modified_timestamps.begin()), end(_last_modified_timestamps.end()); it != end; ++it) { misc::shared_ptr<timestamp_cache> d(new timestamp_cache); d->filename = QString::fromStdString(it->first); d->last_modified = it->second; _cache->add(d); } _cache->commit(); } /** * Set the watch over the directory. * * @param[in] path The directory path. * * @return All the files which were found and dumper. */ std::set<std::string> directory_dumper::_set_watch_over_directory(std::string const& path) { // Basic checks. QFileInfo directory_info(QString::fromStdString(path)); if (!directory_info.exists()) throw (exceptions::msg() << "dumper: directory dumper path '" << path << "' doesn't exist"); if (!directory_info.isDir()) throw (exceptions::msg() << "dumper: directory dumper path '" << path << "' is not a directory"); if (!directory_info.isReadable()) throw (exceptions::msg() << "dumper: directory dumper path '" << path << "' can not be accessed"); // Add the directory to the directory watcher. try { _watcher.add_directory(path); } catch (std::exception const& e) { throw (exceptions::msg() << "dumper: " << e.what()); } // Dump all the files that weren't already dumped at last once // using last modified cached timestamp. std::set<std::string> found_files; { QDirIterator dir( QDir(QString::fromStdString(path), QString(), QDir::Name | QDir::IgnoreCase, QDir::Files)); while (dir.hasNext()) { QString filepath = dir.next(); std::map<std::string, timestamp>::const_iterator found_timestamp( _last_modified_timestamps.find(filepath.toStdString())); if (found_timestamp == _last_modified_timestamps.end() || found_timestamp->second < QFileInfo(filepath).lastModified().toTime_t()) _event_list.push_back(_dump_a_file(filepath.toStdString())); found_files.insert(filepath.toStdString()); } } // Iterate over directories. { QDirIterator dir( QDir(QString::fromStdString(path), QString(), QDir::Name | QDir::IgnoreCase, QDir::Dirs | QDir::NoDotAndDotDot)); while (dir.hasNext()) { QString filepath = dir.next(); std::set<std::string> ret = _set_watch_over_directory( filepath.toStdString()); found_files.insert(ret.begin(), ret.end()); } } return (found_files); } /** * Remove all the files which were deleted. * * @param[in] found_files List of files found. */ void directory_dumper::_remove_deleted_files( std::set<std::string> const& found_files) { // Every file that wasn't found has been deleted for (std::map<std::string, timestamp>::const_iterator it(_last_modified_timestamps.begin()), end(_last_modified_timestamps.end()); it != end; ++it) if (found_files.find(it->first) == found_files.end()) { misc::shared_ptr<dumper::remove> d(new dumper::remove); d->filename = QString::fromStdString(it->first); d->tag = QString::fromStdString(_tagname); _event_list.push_back(std::make_pair(timestamp(), d)); } } /** * Dump a file. * * @param[in] path The path of the file. * * @return A pair of a timestamp containing the time of the dump, * and an io::data dump containing the file. */ std::pair<timestamp, misc::shared_ptr<io::data> > directory_dumper::_dump_a_file( std::string const& path) { QFile file(QString::fromStdString(path)); file.open(QFile::ReadOnly); if (!file.isReadable()) throw (exceptions::msg() << "dumper: can't read '" << path << "'"); timestamp ts(::time(NULL)); QString content = file.readAll(); misc::shared_ptr<dumper::dump> dump(new dumper::dump); dump->filename = QString::fromStdString(_get_relative_filename(path)); dump->content = content; dump->tag = QString::fromStdString(_tagname); return (std::make_pair(ts, dump)); } /** * Get a filename relative to the path being watched. * * @param[in] path The path being watched. * * @return The filename. */ std::string directory_dumper::_get_relative_filename(std::string const& path) { std::string ret = path; ret.replace(0, _path.size(), ""); return (ret); } <commit_msg>dumper: fix directory_dumper write method.<commit_after>/* ** Copyright 2015 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <QMutexLocker> #include <QFileInfo> #include <QFile> #include <QDirIterator> #include <QDateTime> #include <set> #include <fstream> #include <sstream> #include "com/centreon/broker/dumper/directory_dumper.hh" #include "com/centreon/broker/dumper/internal.hh" #include "com/centreon/broker/dumper/dump.hh" #include "com/centreon/broker/dumper/remove.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::dumper; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] path Dumper path. * @param[in] tagname Dumper tagname. * @param[in] cache Persistent cache. */ directory_dumper::directory_dumper( std::string const& path, std::string const& tagname, misc::shared_ptr<persistent_cache> cache) try : _path(path), _tagname(tagname), _cache(cache) { // Set watcher timeout. _watcher.set_timeout(3000); // Get all the last modified timestamps from the cache. _get_last_timestamps_from_cache(); // Set the watch and the initial events. std::set<std::string> files_found = _set_watch_over_directory(path); // Remove deleted files. _remove_deleted_files(files_found); } catch (std::exception const& e) { throw (exceptions::msg() << "dumper: directory dumper couldn't initialize: " << e.what()); } /** * Destructor. */ directory_dumper::~directory_dumper() { try { // Save the last modified timestamps to the cache. _save_last_timestamps_to_cache(); } catch (std::exception const& e) { logging::error(logging::medium) << "dump: directory dumper error while trying to save the cache: " << e.what(); } } /** * Read data from the dumper. * * @param[out] d Next available event. * @param[in] deadline Timeout. * * @return Respect io::stream::read()'s return value. */ bool directory_dumper::read( misc::shared_ptr<io::data>& d, time_t deadline) { d.clear(); // Get an event already in the event list. if (!_event_list.empty()) { unsigned int type = _event_list.front().second->type(); if (type == dump::static_type()) _last_modified_timestamps[ _event_list.front().second.ref_as<dump>().filename.toStdString()] = _event_list.front().first; else if (type == dumper::remove::static_type()) _last_modified_timestamps.erase( _event_list.front().second.ref_as<dumper::remove>().filename.toStdString()); d = _event_list.front().second; _event_list.pop_front(); return (true); } // If no events, watch the directory for new events. std::vector<file::directory_event> events = _watcher.get_events(); for (std::vector<file::directory_event>::const_iterator it(events.begin()), end(events.end()); it != end; ++it) { if (it->get_type() == file::directory_event::directory_deleted && it->get_path() == _path) throw (exceptions::msg() << "dumper: directory '" << _path << "' deleted"); else if (it->get_type() == file::directory_event::deleted) { misc::shared_ptr<dumper::remove> d(new dumper::remove); d->filename = QString::fromStdString( _get_relative_filename(it->get_path())); d->tag = QString::fromStdString(_tagname); _event_list.push_back(std::make_pair(timestamp(), d)); } else if (it->get_type() == file::directory_event::created && it->get_file_type() == file::directory_event::directory) { _set_watch_over_directory(it->get_path()); } else if (it->get_file_type() == file::directory_event::file) _event_list.push_back(_dump_a_file(it->get_path())); } } /** * Write data to the dumper. * * @param[in] d Data to write. * * @return Always return 1, or throw exceptions. */ unsigned int directory_dumper::write(misc::shared_ptr<io::data> const& d) { (void)d; throw (io::exceptions::shutdown(false, true) << "cannot write to a dumper directory"); return (1); } /** * Get the list of last modified timestamps from the persistent cache. */ void directory_dumper::_get_last_timestamps_from_cache() { // No cache, nothing to do. if (_cache.isNull()) return ; misc::shared_ptr<io::data> d; while (true) { _cache->get(d); if (d.isNull()) return; if (d->type() == timestamp_cache::static_type()) { timestamp_cache const& ts = d.ref_as<timestamp_cache const>(); _last_modified_timestamps[ts.filename.toStdString()] = ts.last_modified; } } } /** * Save the list of last modified timestamps to the persistent cache. */ void directory_dumper::_save_last_timestamps_to_cache() { // No cache, nothing to do. if (_cache.isNull()) return ; _cache->transaction(); for (std::map<std::string, timestamp>::const_iterator it(_last_modified_timestamps.begin()), end(_last_modified_timestamps.end()); it != end; ++it) { misc::shared_ptr<timestamp_cache> d(new timestamp_cache); d->filename = QString::fromStdString(it->first); d->last_modified = it->second; _cache->add(d); } _cache->commit(); } /** * Set the watch over the directory. * * @param[in] path The directory path. * * @return All the files which were found and dumper. */ std::set<std::string> directory_dumper::_set_watch_over_directory(std::string const& path) { // Basic checks. QFileInfo directory_info(QString::fromStdString(path)); if (!directory_info.exists()) throw (exceptions::msg() << "dumper: directory dumper path '" << path << "' doesn't exist"); if (!directory_info.isDir()) throw (exceptions::msg() << "dumper: directory dumper path '" << path << "' is not a directory"); if (!directory_info.isReadable()) throw (exceptions::msg() << "dumper: directory dumper path '" << path << "' can not be accessed"); // Add the directory to the directory watcher. try { _watcher.add_directory(path); } catch (std::exception const& e) { throw (exceptions::msg() << "dumper: " << e.what()); } // Dump all the files that weren't already dumped at last once // using last modified cached timestamp. std::set<std::string> found_files; { QDirIterator dir( QDir(QString::fromStdString(path), QString(), QDir::Name | QDir::IgnoreCase, QDir::Files)); while (dir.hasNext()) { QString filepath = dir.next(); std::map<std::string, timestamp>::const_iterator found_timestamp( _last_modified_timestamps.find(filepath.toStdString())); if (found_timestamp == _last_modified_timestamps.end() || found_timestamp->second < QFileInfo(filepath).lastModified().toTime_t()) _event_list.push_back(_dump_a_file(filepath.toStdString())); found_files.insert(filepath.toStdString()); } } // Iterate over directories. { QDirIterator dir( QDir(QString::fromStdString(path), QString(), QDir::Name | QDir::IgnoreCase, QDir::Dirs | QDir::NoDotAndDotDot)); while (dir.hasNext()) { QString filepath = dir.next(); std::set<std::string> ret = _set_watch_over_directory( filepath.toStdString()); found_files.insert(ret.begin(), ret.end()); } } return (found_files); } /** * Remove all the files which were deleted. * * @param[in] found_files List of files found. */ void directory_dumper::_remove_deleted_files( std::set<std::string> const& found_files) { // Every file that wasn't found has been deleted for (std::map<std::string, timestamp>::const_iterator it(_last_modified_timestamps.begin()), end(_last_modified_timestamps.end()); it != end; ++it) if (found_files.find(it->first) == found_files.end()) { misc::shared_ptr<dumper::remove> d(new dumper::remove); d->filename = QString::fromStdString(it->first); d->tag = QString::fromStdString(_tagname); _event_list.push_back(std::make_pair(timestamp(), d)); } } /** * Dump a file. * * @param[in] path The path of the file. * * @return A pair of a timestamp containing the time of the dump, * and an io::data dump containing the file. */ std::pair<timestamp, misc::shared_ptr<io::data> > directory_dumper::_dump_a_file( std::string const& path) { QFile file(QString::fromStdString(path)); file.open(QFile::ReadOnly); if (!file.isReadable()) throw (exceptions::msg() << "dumper: can't read '" << path << "'"); timestamp ts(::time(NULL)); QString content = file.readAll(); misc::shared_ptr<dumper::dump> dump(new dumper::dump); dump->filename = QString::fromStdString(_get_relative_filename(path)); dump->content = content; dump->tag = QString::fromStdString(_tagname); return (std::make_pair(ts, dump)); } /** * Get a filename relative to the path being watched. * * @param[in] path The path being watched. * * @return The filename. */ std::string directory_dumper::_get_relative_filename(std::string const& path) { std::string ret = path; ret.replace(0, _path.size(), ""); return (ret); } <|endoftext|>
<commit_before>#include "coord_client.h" CoordinatorClient::CoordinatorClient(const QString &, QObject *parent) : QObject(parent) { } CoordinatorClient::~CoordinatorClient() { } void CoordinatorClient::openItem(QUrl item) { if (item.scheme() == "file") { QFileInfo fileInfo(item.path()); QString binary; if (fileInfo.isDir()) { binary = "runcible-dir-list"; } else { binary = "runcible-open-ext-" + fileInfo.suffix(); } QProcess::startDetached(binary, QStringList() << fileInfo.absoluteFilePath()); } else { qDebug() << "Cannot open non-file item " << item; } } void CoordinatorClient::openItem(QString program, QUrl item) { // TODO(cbiffle): this is stubbed out to avoid using COP. QProcess::startDetached(program, QStringList() << item.toString()); } <commit_msg>Switched the coordinator client to use QCOP.<commit_after>#include "coord_client.h" #include <QCopChannel> CoordinatorClient::CoordinatorClient(const QString &, QObject *parent) : QObject(parent) { } CoordinatorClient::~CoordinatorClient() { } void CoordinatorClient::openItem(QUrl item) { QByteArray data; QDataStream out(&data, QIODevice::WriteOnly); out << item; qDebug() << "Sending openItem(QUrl)"; if (!QCopChannel::send("runcible/coordinator", "openItem(QUrl)", data)) { qDebug() << "Send failed."; } } void CoordinatorClient::openItem(QString program, QUrl item) { QByteArray data; QDataStream out(&data, QIODevice::WriteOnly); out << program << item; qDebug() << "Sending openItem(QString,QUrl)"; if (!QCopChannel::send("runcible/coordinator", "openItem(QString,QUrl)", data)) { qDebug() << "Send failed."; } } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/base/Planner.h" #include "ompl/util/Exception.h" #include "ompl/base/GoalSampleableRegion.h" #include "ompl/base/GoalLazySamples.h" #include <boost/thread.hpp> ompl::base::Planner::Planner(const SpaceInformationPtr &si, const std::string &name) : si_(si), pis_(this), name_(name), setup_(false), msg_(name) { if (!si_) throw Exception(name_, "Invalid space information instance for planner"); } const ompl::base::PlannerSpecs& ompl::base::Planner::getSpecs(void) const { return specs_; } const std::string& ompl::base::Planner::getName(void) const { return name_; } void ompl::base::Planner::setName(const std::string &name) { name_ = name; msg_.setPrefix(name_); } const ompl::base::SpaceInformationPtr& ompl::base::Planner::getSpaceInformation(void) const { return si_; } const ompl::base::ProblemDefinitionPtr& ompl::base::Planner::getProblemDefinition(void) const { return pdef_; } void ompl::base::Planner::setProblemDefinition(const ProblemDefinitionPtr &pdef) { pdef_ = pdef; pis_.update(); } const ompl::base::PlannerInputStates& ompl::base::Planner::getPlannerInputStates(void) const { return pis_; } void ompl::base::Planner::setup(void) { if (!si_->isSetup()) { msg_.inform("Space information setup was not yet called. Calling now."); si_->setup(); } if (setup_) msg_.warn("Planner setup called multiple times"); else setup_ = true; } void ompl::base::Planner::checkValidity(void) { if (!isSetup()) setup(); pis_.checkValidity(); } bool ompl::base::Planner::isSetup(void) const { return setup_; } void ompl::base::Planner::clear(void) { pis_.clear(); pis_.update(); } void ompl::base::Planner::getPlannerData(PlannerData &data) const { data.si = si_; } bool ompl::base::Planner::solve(const PlannerTerminationConditionFn &ptc, double checkInterval) { return solve(PlannerThreadedTerminationCondition(ptc, checkInterval)); } bool ompl::base::Planner::solve(double solveTime) { if (solveTime < 1.0) return solve(timedPlannerTerminationCondition(solveTime)); else return solve(timedPlannerTerminationCondition(solveTime, std::min(solveTime / 100.0, 0.1))); } void ompl::base::Planner::printProperties(std::ostream &out) const { out << "Planner " + getName() + " specs:" << std::endl; out << "Multithreaded: " << (getSpecs().multithreaded ? "Yes" : "No") << std::endl; out << "Reports approximate solutions: " << (getSpecs().approximateSolutions ? "Yes" : "No") << std::endl; out << "Can optimize solutions: " << (getSpecs().optimizingPaths ? "Yes" : "No") << std::endl; out << "Aware of the following parameters:"; std::vector<std::string> params; params_.getParamNames(params); for (unsigned int i = 0 ; i < params.size() ; ++i) out << " " << params[i]; out << std::endl; } void ompl::base::Planner::printSettings(std::ostream &out) const { out << "Declared parameters for planner " << getName() << ":" << std::endl; params_.print(out); } void ompl::base::PlannerInputStates::clear(void) { if (tempState_) { si_->freeState(tempState_); tempState_ = NULL; } addedStartStates_ = 0; sampledGoalsCount_ = 0; pdef_ = NULL; si_ = NULL; } void ompl::base::PlannerInputStates::restart(void) { addedStartStates_ = 0; sampledGoalsCount_ = 0; } bool ompl::base::PlannerInputStates::update(void) { if (!planner_) throw Exception("No planner set for PlannerInputStates"); return use(planner_->getSpaceInformation(), planner_->getProblemDefinition()); } void ompl::base::PlannerInputStates::checkValidity(void) const { std::string error; if (!pdef_) error = "Problem definition not specified"; else { if (pdef_->getStartStateCount() <= 0) error = "No start states specified"; else if (!pdef_->getGoal()) error = "No goal specified"; } if (!error.empty()) { if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } } bool ompl::base::PlannerInputStates::use(const SpaceInformationPtr &si, const ProblemDefinitionPtr &pdef) { if (si && pdef) return use(si.get(), pdef.get()); else { clear(); return true; } } bool ompl::base::PlannerInputStates::use(const SpaceInformation *si, const ProblemDefinition *pdef) { if (pdef_ != pdef || si_ != si) { clear(); pdef_ = pdef; si_ = si; return true; } return false; } const ompl::base::State* ompl::base::PlannerInputStates::nextStart(void) { if (pdef_ == NULL || si_ == NULL) { std::string error = "Missing space information or problem definition"; if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } while (addedStartStates_ < pdef_->getStartStateCount()) { const base::State *st = pdef_->getStartState(addedStartStates_); addedStartStates_++; bool bounds = si_->satisfiesBounds(st); bool valid = bounds ? si_->isValid(st) : false; if (bounds && valid) return st; else { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.warn("Skipping invalid start state (invalid %s)", bounds ? "state": "bounds"); } } return NULL; } const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(void) { static PlannerAlwaysTerminatingCondition ptc; return nextGoal(ptc); } const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(const PlannerTerminationCondition &ptc) { if (pdef_ == NULL || si_ == NULL) { std::string error = "Missing space information or problem definition"; if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } const GoalSampleableRegion *goal = dynamic_cast<const GoalSampleableRegion*>(pdef_->getGoal().get()); if (goal) { const GoalLazySamples *gls = dynamic_cast<const GoalLazySamples*>(goal); bool first = true; bool attempt = true; while (attempt) { attempt = false; if (sampledGoalsCount_ < goal->maxSampleCount()) { if (tempState_ == NULL) tempState_ = si_->allocState(); do { goal->sampleGoal(tempState_); sampledGoalsCount_++; bool bounds = si_->satisfiesBounds(tempState_); bool valid = bounds ? si_->isValid(tempState_) : false; if (bounds && valid) return tempState_; else { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.warn("Skipping invalid goal state (invalid %s)", bounds ? "state": "bounds"); } } while (sampledGoalsCount_ < goal->maxSampleCount() && !ptc()); } if (gls && goal->canSample() && !ptc()) { if (first) { first = false; msg::Interface msg(planner_ ? planner_->getName() : ""); msg.debug("Waiting for goal region samples ..."); } boost::this_thread::sleep(time::seconds(0.01)); attempt = !ptc(); } } } return NULL; } bool ompl::base::PlannerInputStates::haveMoreStartStates(void) const { if (pdef_) return addedStartStates_ < pdef_->getStartStateCount(); return false; } bool ompl::base::PlannerInputStates::haveMoreGoalStates(void) const { if (pdef_ && pdef_->getGoal()) { const GoalSampleableRegion *goal = dynamic_cast<const GoalSampleableRegion*>(pdef_->getGoal().get()); if (goal) return sampledGoalsCount_ < goal->maxSampleCount(); } return false; } <commit_msg>small simplification<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/base/Planner.h" #include "ompl/util/Exception.h" #include "ompl/base/GoalSampleableRegion.h" #include <boost/thread.hpp> ompl::base::Planner::Planner(const SpaceInformationPtr &si, const std::string &name) : si_(si), pis_(this), name_(name), setup_(false), msg_(name) { if (!si_) throw Exception(name_, "Invalid space information instance for planner"); } const ompl::base::PlannerSpecs& ompl::base::Planner::getSpecs(void) const { return specs_; } const std::string& ompl::base::Planner::getName(void) const { return name_; } void ompl::base::Planner::setName(const std::string &name) { name_ = name; msg_.setPrefix(name_); } const ompl::base::SpaceInformationPtr& ompl::base::Planner::getSpaceInformation(void) const { return si_; } const ompl::base::ProblemDefinitionPtr& ompl::base::Planner::getProblemDefinition(void) const { return pdef_; } void ompl::base::Planner::setProblemDefinition(const ProblemDefinitionPtr &pdef) { pdef_ = pdef; pis_.update(); } const ompl::base::PlannerInputStates& ompl::base::Planner::getPlannerInputStates(void) const { return pis_; } void ompl::base::Planner::setup(void) { if (!si_->isSetup()) { msg_.inform("Space information setup was not yet called. Calling now."); si_->setup(); } if (setup_) msg_.warn("Planner setup called multiple times"); else setup_ = true; } void ompl::base::Planner::checkValidity(void) { if (!isSetup()) setup(); pis_.checkValidity(); } bool ompl::base::Planner::isSetup(void) const { return setup_; } void ompl::base::Planner::clear(void) { pis_.clear(); pis_.update(); } void ompl::base::Planner::getPlannerData(PlannerData &data) const { data.si = si_; } bool ompl::base::Planner::solve(const PlannerTerminationConditionFn &ptc, double checkInterval) { return solve(PlannerThreadedTerminationCondition(ptc, checkInterval)); } bool ompl::base::Planner::solve(double solveTime) { if (solveTime < 1.0) return solve(timedPlannerTerminationCondition(solveTime)); else return solve(timedPlannerTerminationCondition(solveTime, std::min(solveTime / 100.0, 0.1))); } void ompl::base::Planner::printProperties(std::ostream &out) const { out << "Planner " + getName() + " specs:" << std::endl; out << "Multithreaded: " << (getSpecs().multithreaded ? "Yes" : "No") << std::endl; out << "Reports approximate solutions: " << (getSpecs().approximateSolutions ? "Yes" : "No") << std::endl; out << "Can optimize solutions: " << (getSpecs().optimizingPaths ? "Yes" : "No") << std::endl; out << "Aware of the following parameters:"; std::vector<std::string> params; params_.getParamNames(params); for (unsigned int i = 0 ; i < params.size() ; ++i) out << " " << params[i]; out << std::endl; } void ompl::base::Planner::printSettings(std::ostream &out) const { out << "Declared parameters for planner " << getName() << ":" << std::endl; params_.print(out); } void ompl::base::PlannerInputStates::clear(void) { if (tempState_) { si_->freeState(tempState_); tempState_ = NULL; } addedStartStates_ = 0; sampledGoalsCount_ = 0; pdef_ = NULL; si_ = NULL; } void ompl::base::PlannerInputStates::restart(void) { addedStartStates_ = 0; sampledGoalsCount_ = 0; } bool ompl::base::PlannerInputStates::update(void) { if (!planner_) throw Exception("No planner set for PlannerInputStates"); return use(planner_->getSpaceInformation(), planner_->getProblemDefinition()); } void ompl::base::PlannerInputStates::checkValidity(void) const { std::string error; if (!pdef_) error = "Problem definition not specified"; else { if (pdef_->getStartStateCount() <= 0) error = "No start states specified"; else if (!pdef_->getGoal()) error = "No goal specified"; } if (!error.empty()) { if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } } bool ompl::base::PlannerInputStates::use(const SpaceInformationPtr &si, const ProblemDefinitionPtr &pdef) { if (si && pdef) return use(si.get(), pdef.get()); else { clear(); return true; } } bool ompl::base::PlannerInputStates::use(const SpaceInformation *si, const ProblemDefinition *pdef) { if (pdef_ != pdef || si_ != si) { clear(); pdef_ = pdef; si_ = si; return true; } return false; } const ompl::base::State* ompl::base::PlannerInputStates::nextStart(void) { if (pdef_ == NULL || si_ == NULL) { std::string error = "Missing space information or problem definition"; if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } while (addedStartStates_ < pdef_->getStartStateCount()) { const base::State *st = pdef_->getStartState(addedStartStates_); addedStartStates_++; bool bounds = si_->satisfiesBounds(st); bool valid = bounds ? si_->isValid(st) : false; if (bounds && valid) return st; else { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.warn("Skipping invalid start state (invalid %s)", bounds ? "state": "bounds"); } } return NULL; } const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(void) { static PlannerAlwaysTerminatingCondition ptc; return nextGoal(ptc); } const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(const PlannerTerminationCondition &ptc) { if (pdef_ == NULL || si_ == NULL) { std::string error = "Missing space information or problem definition"; if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } const GoalSampleableRegion *goal = dynamic_cast<const GoalSampleableRegion*>(pdef_->getGoal().get()); if (goal) { bool first = true; bool attempt = true; while (attempt) { attempt = false; if (sampledGoalsCount_ < goal->maxSampleCount()) { if (tempState_ == NULL) tempState_ = si_->allocState(); do { goal->sampleGoal(tempState_); sampledGoalsCount_++; bool bounds = si_->satisfiesBounds(tempState_); bool valid = bounds ? si_->isValid(tempState_) : false; if (bounds && valid) return tempState_; else { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.warn("Skipping invalid goal state (invalid %s)", bounds ? "state": "bounds"); } } while (sampledGoalsCount_ < goal->maxSampleCount() && !ptc()); } if (goal->canSample() && !ptc()) { if (first) { first = false; msg::Interface msg(planner_ ? planner_->getName() : ""); msg.debug("Waiting for goal region samples ..."); } boost::this_thread::sleep(time::seconds(0.01)); attempt = !ptc(); } } } return NULL; } bool ompl::base::PlannerInputStates::haveMoreStartStates(void) const { if (pdef_) return addedStartStates_ < pdef_->getStartStateCount(); return false; } bool ompl::base::PlannerInputStates::haveMoreGoalStates(void) const { if (pdef_ && pdef_->getGoal()) { const GoalSampleableRegion *goal = dynamic_cast<const GoalSampleableRegion*>(pdef_->getGoal().get()); if (goal) return sampledGoalsCount_ < goal->maxSampleCount(); } return false; } <|endoftext|>
<commit_before>/************************************************************************************* ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_socket.cpp * @version * @brief * @author duye * @date 2014-2-16 * @note * * 2. 2014-06-21 duye move to gohoop * 1. 2014-02-16 duye Created this file * */ #include <g_sys.h> #include <g_socket.h> #include <net/if.h> namespace gsys { const struct in6_addr IN6ADDR_ANY = IN6ADDR_ANY_INIT; SockAddr::SockAddr() : SockAddr(INADDR_ANY, 0) {} SockAddr::SockAddr(const GUint32 ip, const GUint16 port) { m_addrLen = sizeof(sockaddr_in); bzero(&m_addr, m_addrLen); m_addr.sin_family = AF_INET; m_addr.sin_port = htons(port); m_addr.sin_addr.s_addr = htonl(ip); } SockAddr::~SockAddr() {} void SockAddr::setIP(const GUint32 ip) { m_addr.sin_addr.s_addr = htonl(ip); } GUint32 SockAddr::ip() { return ntohl(m_addr.sin_addr.s_addr); } GUint8* SockAddr::ipStr() { return (GUint8*)inet_ntoa(m_addr.sin_addr); } void SockAddr::setPort(const GUint16 port) { m_addr.sin_port = htons(port); } GUint16 SockAddr::port() { return ntohs(m_addr.sin_port); } sockaddr_in& SockAddr::addr() { return m_addr; } GUint16 SockAddr::addrLen() const { return m_addrLen; } IPv6Addr::IPv6Addr() { m_addrLen = sizeof(sockaddr_in6); bzero(&m_sockAddr, m_addrLen); m_sockAddr.sin6_family = AF_INET6; m_sockAddr.sin6_port = 0; m_sockAddr.sin6_addr = IN6ADDR_ANY; } IPv6Addr::IPv6Addr(const GUint8 ip[16], const GUint16 port) { bzero(&m_sockAddr, sizeof(m_sockAddr)); m_sockAddr.sin6_family = AF_INET6; m_sockAddr.sin6_port = htons(port); memcpy(m_sockAddr.sin6_addr.s6_addr, ip, 16); } IPv6Addr::~IPv6Addr() {} GUint8* IPv6Addr::ip() { return m_sockAddr.sin6_addr.s6_addr; } GUint16 IPv6Addr::port() { return ntohs(m_sockAddr.sin6_port); } sockaddr_in6& IPv6Addr::addr() { return m_sockAddr; } GUint16 IPv6Addr::addrLen() const { return m_addrLen; } Socket::Socket() : m_sockfd(-1), m_isInit(false) {} Socket::~Socket() { uninit(); } GResult Socket::open(const NetProtocol& protocol, const std::string& if_name) { GInt32 domain = AF_INET; GInt32 sock_type = -1; GInt32 sock_protocol = -1; switch (protocol) { case G_IPPROTO_TCP: { sock_protocol = IPPROTO_TCP; sock_type = SOCK_STREAM; break; } case G_IPPROTO_UDP: { sock_protocol = IPPROTO_UDP; sock_type = SOCK_DGRAM; break; } case G_IPPROTO_SCTP: { sock_protocol = IPPROTO_SCTP; setError("[warn]%s:argument protocol(%d) not support (%s:%d)\n", __FUNCTION__, protocol, __FILE__, __LINE__); return G_NO; // not support } case G_IPPROTO_TIPC: { //sock_protocol = IPPROTO_TIPC; setError("[warn]%s:argument protocol(%d) not support (%s:%d)\n", __FUNCTION__, protocol, __FILE__, __LINE__); return G_NO; // not support } default: { setError("[error]%s:argument protocol(%d) invalid (%s:%d)\n", __FUNCTION__, protocol, __FILE__, __LINE__); return G_NO; } } m_sockfd = ::socket(domain, sock_type, sock_protocol); if (m_sockfd < 0) { setError("[error]%s: socket(%d, %d, %d) ret=%d invalid (%s:%d)\n", __FUNCTION__, domain, sock_type, sock_protocol, m_sockfd, __FILE__, __LINE__); return G_NO; } // init socket option initOption(if_name); m_isInit = true; return G_YES; } GResult Socket::close(const GInt32 how) { // how = 0 : stop receive data // how = 1 : stop send data // how = 2 : both above way if (!m_isInit) { return G_YES; } return (shutdown(m_sockfd, how) == 0 ? G_YES : G_NO); } GInt32 Socket::sockfd() const { return m_sockfd; } GInt8* Socket::getError() { return m_error; } GResult Socket::initOption(const std::string& if_name) { GResult ret = G_YES; // setting specified interface struct ifreq interface; strncpy(interface.ifr_ifrn.ifrn_name, if_name.c_str(), if_name.length()); if (setsockopt(m_sockfd, SOL_SOCKET, SO_BINDTODEVICE, (char*)&interface, sizeof(interface)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = G_NO; } // set address reuse, address reuse flag, 1 reuse GInt32 reuse = 1; if (setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = G_NO; } // send time limit, unit ms int send_time = 2000; if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&send_time, sizeof(int)) == -1) { ret = false; } // receive time limit, unit ms int recv_time = 2000; if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&recv_time, sizeof(int)) == -1) { ret = false; } // set send data buffer size GInt32 send_buf_size = 0xFFFF; if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&send_buf_size, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = false; } // set receive data buffer size GInt32 recv_buf_size = 0xFFFF; if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&recv_buf_size, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = false; } // don't copy data from system buffer to socket buffer when send data /* GInt32 is_copy = 0; if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&is_copy, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = false; } // don't copy data from system buffer to GSocket buffer when receive data if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&is_copy, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = false; } */ // let data send completly after execute close GSocket /* struct STR_Linger { GInt16 l_onoff; GInt16 l_linger; }; STR_Linger linger; linger.l_onoff = 1; // 1. allow wait; 0. force close linger.l_linger = 1; // the time of waiting unit s if (setsockopt(m_sockfd, SOL_GSocket, SO_LINGER, (const char*)&linger, sizeof(STR_Linger)) == -1) { ret = false; } */ return ret; } void Socket::setError(const GInt8* args, ...) { System::pformat(m_error, G_ERROR_BUF_SIZE, args); } GInt64 Transfer::send(Socket& socket, const GUint8* data, const GUint64 len, const GInt32 flags) { return ::send(socket.sockfd(), data, len, flags); } GInt64 Transfer::sendmsg(Socket& socket, const struct msghdr* msg, const GInt32 flags) { return ::sendmsg(socket.sockfd(), msg, flags); } GInt64 Transfer::sendto(Socket& socket, SockAddr& dst_addr, const GUint8* data, const GUint64 len, const GInt32 flags) { return ::sendto(socket.sockfd(), data, len, flags, (const struct sockaddr*)&dst_addr.addr(), dst_addr.addrLen()); } GInt64 Transfer::recv(Socket& socket, GUint8* buffer, const GUint64 size, const GInt32 flags) { return ::recv(socket.sockfd(), buffer, size, flags); } GInt64 Transfer::recvmsg(Socket& socket, struct msghdr* msg, const GInt32 flags) { return ::recvmsg(socket.sockfd(), msg, flags); } GInt64 Transfer::recvfrom(Socket& socket, SockAddr& src_addr, GUint8* buffer, const GUint64 size, const GInt32 flags) { GUint32 addr_len = src_addr.addLen(); return ::recvfrom(socket.sockfd(), buffer, size, flags, (struct sockaddr*)&src_addr.addr(), &addr_len); } SocketServer::SocketServer() {} SocketServer::SocketServer(const SocketInfo& socket_info) { setSocketInfo(socket_info); } SocketServer::~SocketServer() { close(); } void SocketServer::setSocketInfo(const SocketInfo& socket_info) { m_socketInfo = socket_info; m_addr.setIP(m_socketInfo.serverIP()); m_addr.setPort(m_socketInfo.serverPort()); } GResult SocketServer::bind() { if (IS_NO(m_socket.open(m_socketInfo.protocol(), m_socketInfo.localIfName()))) { setError("[error]%s:Socket not init (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); return G_NO; } return ::bind(m_socket.sockfd(), (const struct sockaddr*)&m_addr.addr(), m_addr.addrLen()) < 0 ? G_NO : G_YES; } GResult SocketServer::listen(const GUint32 max_connect_num) { return ::listen(m_socket.sockfd(), max_connect_num) == 0 ? G_YES : G_NO; } GInt32 SocketServer::accept(SockAddr& client_addr, const RecvMode& mode) { GUint16 addr_len = client_addr.addrLen(); if (mode == G_RECV_BLOCK) { return ::accept(m_socket.sockfd(), (struct sockaddr*)&client_addr.addr(), &addr_len); } else if (mode == G_RECV_UNBLOCK) { return ::accept4(m_socket.sockfd(), (struct sockaddr*)&client_addr.addr(), &addr_len, SOCK_NONBLOCK); } return -1; } GInt64 SocketServer::recvfrom(SockAddr& client_addr, GUint8* buffer, const GUint64 size, const RecvMode& mode) { if (mode == G_RECV_BLOCK) { return Transfer::recvfrom(m_socket, client_addr, buffer, size); } else if (mode == G_RECV_UNBLOCK) { return Transfer::recvfrom(m_socket, client_addr, buffer, size, MSG_DONTWAIT); } return -1; } GResult SocketServer::close() { return m_socket.close(); } GInt8* SocketServer::getError() { return m_error; } void SocketServer::setError(const GInt8* args, ...) { System::pformat(m_error, G_ERROR_BUF_SIZE, args); } SocketClient::SocketClient(const SocketInfo& socket_info) { setSocketInfo(socket_info); } SocketClient::~SocketClient() { close(); } void SocketClient::setSocketInfo(const SocketInfo& socket_info) { m_socketInfo = socket_info; m_addr.setIP(m_socketInfo.serverIP()); m_addr.setPort(m_socketInfo.serverPort()); } GResult SocketClient::connect() { if (IS_NO(m_socket.open(m_socketInfo.protocol(), m_socketInfo.localIfName()))) { setError("[error]%s:Socket not init (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); return G_NO; } return ::connect(m_socket.sockfd(), (const struct sockaddr*)&m_addr.addr(), m_addr.addrLen()) < 0 ? G_NO : G_YES; } GInt64 SocketClient::send(const GUint8* data, const GUint64 len, const GInt32 flags) { return Transfer::send(m_socket, data, len, flags); } GInt64 SocketClient::recv(GUint8* buffer, const GUint64 size, const RecvMode& mode) { if (mode == G_RECV_BLOCK) { return Transfer::recv(m_socket, buffer, size); } else if (mode == G_RECV_UNBLOCK) { return Transfer::recv(m_socket, buffer, size, MSG_DONTWAIT); } return -1 } GResult SocketClient::close() { return m_socket.close(); } GInt8* SocketClient::getError() { return m_error; } void SocketClient::setError(const GInt8* args, ...) { System::pformat(m_error, G_ERROR_BUF_SIZE, args); } } <commit_msg>Update g_socket.cpp<commit_after>/************************************************************************************* ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_socket.cpp * @version * @brief * @author duye * @date 2014-2-16 * @note * * 2. 2014-06-21 duye move to gohoop * 1. 2014-02-16 duye Created this file * */ #include <g_sys.h> #include <g_socket.h> #include <net/if.h> namespace gsys { const struct in6_addr IN6ADDR_ANY = IN6ADDR_ANY_INIT; SockAddr::SockAddr() : SockAddr(INADDR_ANY, 0) {} SockAddr::SockAddr(const GUint32 ip, const GUint16 port) { m_addrLen = sizeof(sockaddr_in); bzero(&m_addr, m_addrLen); m_addr.sin_family = AF_INET; m_addr.sin_port = htons(port); m_addr.sin_addr.s_addr = htonl(ip); } SockAddr::~SockAddr() {} void SockAddr::setIP(const GUint32 ip) { m_addr.sin_addr.s_addr = htonl(ip); } GUint32 SockAddr::ip() { return ntohl(m_addr.sin_addr.s_addr); } GUint8* SockAddr::ipStr() { return (GUint8*)inet_ntoa(m_addr.sin_addr); } void SockAddr::setPort(const GUint16 port) { m_addr.sin_port = htons(port); } GUint16 SockAddr::port() { return ntohs(m_addr.sin_port); } sockaddr_in& SockAddr::addr() { return m_addr; } GUint16 SockAddr::addrLen() const { return m_addrLen; } IPv6Addr::IPv6Addr() { m_addrLen = sizeof(sockaddr_in6); bzero(&m_sockAddr, m_addrLen); m_sockAddr.sin6_family = AF_INET6; m_sockAddr.sin6_port = 0; m_sockAddr.sin6_addr = IN6ADDR_ANY; } IPv6Addr::IPv6Addr(const GUint8 ip[16], const GUint16 port) { bzero(&m_sockAddr, sizeof(m_sockAddr)); m_sockAddr.sin6_family = AF_INET6; m_sockAddr.sin6_port = htons(port); memcpy(m_sockAddr.sin6_addr.s6_addr, ip, 16); } IPv6Addr::~IPv6Addr() {} GUint8* IPv6Addr::ip() { return m_sockAddr.sin6_addr.s6_addr; } GUint16 IPv6Addr::port() { return ntohs(m_sockAddr.sin6_port); } sockaddr_in6& IPv6Addr::addr() { return m_sockAddr; } GUint16 IPv6Addr::addrLen() const { return m_addrLen; } Socket::Socket() : m_sockfd(-1), m_isInit(false) {} Socket::~Socket() { uninit(); } GResult Socket::open(const NetProtocol& protocol, const std::string& if_name) { GInt32 domain = AF_INET; GInt32 sock_type = -1; GInt32 sock_protocol = -1; switch (protocol) { case G_IPPROTO_TCP: { sock_protocol = IPPROTO_TCP; sock_type = SOCK_STREAM; break; } case G_IPPROTO_UDP: { sock_protocol = IPPROTO_UDP; sock_type = SOCK_DGRAM; break; } case G_IPPROTO_SCTP: { sock_protocol = IPPROTO_SCTP; setError("[warn]%s:argument protocol(%d) not support (%s:%d)\n", __FUNCTION__, protocol, __FILE__, __LINE__); return G_NO; // not support } case G_IPPROTO_TIPC: { //sock_protocol = IPPROTO_TIPC; setError("[warn]%s:argument protocol(%d) not support (%s:%d)\n", __FUNCTION__, protocol, __FILE__, __LINE__); return G_NO; // not support } default: { setError("[error]%s:argument protocol(%d) invalid (%s:%d)\n", __FUNCTION__, protocol, __FILE__, __LINE__); return G_NO; } } m_sockfd = ::socket(domain, sock_type, sock_protocol); if (m_sockfd < 0) { setError("[error]%s: socket(%d, %d, %d) ret=%d invalid (%s:%d)\n", __FUNCTION__, domain, sock_type, sock_protocol, m_sockfd, __FILE__, __LINE__); return G_NO; } // init socket option initOption(if_name); m_isInit = true; return G_YES; } GResult Socket::close(const GInt32 how) { // how = 0 : stop receive data // how = 1 : stop send data // how = 2 : both above way if (!m_isInit) { return G_YES; } return (shutdown(m_sockfd, how) == 0 ? G_YES : G_NO); } GInt32 Socket::sockfd() const { return m_sockfd; } GInt8* Socket::getError() { return m_error; } GResult Socket::initOption(const std::string& if_name) { GResult ret = G_YES; // setting specified interface struct ifreq interface; strncpy(interface.ifr_ifrn.ifrn_name, if_name.c_str(), if_name.length()); if (setsockopt(m_sockfd, SOL_SOCKET, SO_BINDTODEVICE, (char*)&interface, sizeof(interface)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = G_NO; } // set address reuse, address reuse flag, 1 reuse GInt32 reuse = 1; if (setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = G_NO; } // send time limit, unit ms int send_time = 2000; if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&send_time, sizeof(int)) == -1) { ret = false; } // receive time limit, unit ms int recv_time = 2000; if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&recv_time, sizeof(int)) == -1) { ret = false; } // set send data buffer size GInt32 send_buf_size = 0xFFFF; if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&send_buf_size, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = false; } // set receive data buffer size GInt32 recv_buf_size = 0xFFFF; if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&recv_buf_size, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = false; } // don't copy data from system buffer to socket buffer when send data /* GInt32 is_copy = 0; if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&is_copy, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = false; } // don't copy data from system buffer to GSocket buffer when receive data if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&is_copy, sizeof(GInt32)) == -1) { setError("[warn]%s:setsockopt() failed (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); ret = false; } */ // let data send completly after execute close GSocket /* struct STR_Linger { GInt16 l_onoff; GInt16 l_linger; }; STR_Linger linger; linger.l_onoff = 1; // 1. allow wait; 0. force close linger.l_linger = 1; // the time of waiting unit s if (setsockopt(m_sockfd, SOL_GSocket, SO_LINGER, (const char*)&linger, sizeof(STR_Linger)) == -1) { ret = false; } */ return ret; } void Socket::setError(const GInt8* args, ...) { System::pformat(m_error, G_ERROR_BUF_SIZE, args); } GInt64 Transfer::send(Socket& socket, const GUint8* data, const GUint64 len, const GInt32 flags) { return ::send(socket.sockfd(), data, len, flags); } GInt64 Transfer::sendmsg(Socket& socket, const struct msghdr* msg, const GInt32 flags) { return ::sendmsg(socket.sockfd(), msg, flags); } GInt64 Transfer::sendto(Socket& socket, SockAddr& dst_addr, const GUint8* data, const GUint64 len, const GInt32 flags) { return ::sendto(socket.sockfd(), data, len, flags, (const struct sockaddr*)&dst_addr.addr(), dst_addr.addrLen()); } GInt64 Transfer::recv(Socket& socket, GUint8* buffer, const GUint64 size, const GInt32 flags) { return ::recv(socket.sockfd(), buffer, size, flags); } GInt64 Transfer::recvmsg(Socket& socket, struct msghdr* msg, const GInt32 flags) { return ::recvmsg(socket.sockfd(), msg, flags); } GInt64 Transfer::recvfrom(Socket& socket, SockAddr& src_addr, GUint8* buffer, const GUint64 size, const GInt32 flags) { GUint32 addr_len = src_addr.addLen(); return ::recvfrom(socket.sockfd(), buffer, size, flags, (struct sockaddr*)&src_addr.addr(), &addr_len); } SocketServer::SocketServer() {} SocketServer::SocketServer(const SocketInfo& socket_info) { setSocketInfo(socket_info); } SocketServer::~SocketServer() { close(); } void SocketServer::setSocketInfo(const SocketInfo& socket_info) { m_socketInfo = socket_info; m_addr.setIP(m_socketInfo.serverIP()); m_addr.setPort(m_socketInfo.serverPort()); } GResult SocketServer::bind() { if (IS_NO(m_socket.open(m_socketInfo.protocol(), m_socketInfo.localIfName()))) { setError("[error]%s:Socket not init (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); return G_NO; } return ::bind(m_socket.sockfd(), (const struct sockaddr*)&m_addr.addr(), m_addr.addrLen()) < 0 ? G_NO : G_YES; } GResult SocketServer::listen(const GUint32 max_connect_num) { return ::listen(m_socket.sockfd(), max_connect_num) == 0 ? G_YES : G_NO; } GInt32 SocketServer::accept(SockAddr& client_addr, const RecvMode& mode) { GUint16 addr_len = client_addr.addrLen(); if (mode == G_RECV_BLOCK) { return ::accept(m_socket.sockfd(), (struct sockaddr*)&client_addr.addr(), &addr_len); } else if (mode == G_RECV_UNBLOCK) { return ::accept4(m_socket.sockfd(), (struct sockaddr*)&client_addr.addr(), &addr_len, SOCK_NONBLOCK); } return -1; } GInt64 SocketServer::recvfrom(SockAddr& client_addr, GUint8* buffer, const GUint64 size, const RecvMode& mode) { if (mode == G_RECV_BLOCK) { return Transfer::recvfrom(m_socket, client_addr, buffer, size); } else if (mode == G_RECV_UNBLOCK) { return Transfer::recvfrom(m_socket, client_addr, buffer, size, MSG_DONTWAIT); } return -1; } GResult SocketServer::close() { return m_socket.close(); } GInt8* SocketServer::getError() { return m_error; } void SocketServer::setError(const GInt8* args, ...) { System::pformat(m_error, G_ERROR_BUF_SIZE, args); } SocketClient::SocketClient(const SocketInfo& socket_info) { setSocketInfo(socket_info); } SocketClient::~SocketClient() { close(); } void SocketClient::setSocketInfo(const SocketInfo& socket_info) { m_socketInfo = socket_info; m_addr.setIP(m_socketInfo.serverIP()); m_addr.setPort(m_socketInfo.serverPort()); } GResult SocketClient::connect() { if (IS_NO(m_socket.open(m_socketInfo.protocol(), m_socketInfo.localIfName()))) { setError("[error]%s:Socket not init (%s:%d)\n", __FUNCTION__, __FILE__, __LINE__); return G_NO; } return ::connect(m_socket.sockfd(), (const struct sockaddr*)&m_addr.addr(), m_addr.addrLen()) < 0 ? G_NO : G_YES; } GInt64 SocketClient::send(const GUint8* data, const GUint64 len, const GInt32 flags) { return Transfer::send(m_socket, data, len, flags); } GInt64 SocketClient::recv(GUint8* buffer, const GUint64 size, const RecvMode& mode) { if (mode == G_RECV_BLOCK) { return Transfer::recv(m_socket, buffer, size); } else if (mode == G_RECV_UNBLOCK) { return Transfer::recv(m_socket, buffer, size, MSG_DONTWAIT); } return -1 } GResult SocketClient::close() { return m_socket.close(); } GInt8* SocketClient::getError() { return m_error; } void SocketClient::setError(const GInt8* args, ...) { System::pformat(m_error, G_ERROR_BUF_SIZE, args); } } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "OffscreenScene.h" #include "SDLDisplayEngine.h" #include "SceneNode.h" #include "OGLTexture.h" #include "../base/Exception.h" #include <iostream> using namespace boost; using namespace std; namespace avg { OffscreenScene::OffscreenScene(Player * pPlayer, NodePtr pRootNode) : Scene(pPlayer, pRootNode) { if (!pRootNode) { throw (Exception(AVG_ERR_XML_PARSE, "Root node of a scene tree needs to be a <scene> node.")); } if (pRootNode->getID() == "") { throw (Exception(AVG_ERR_XML_PARSE, "Root node of a scene tree needs to have an id.")); } } OffscreenScene::~OffscreenScene() { glDeleteTextures(1, &m_TexID); } void OffscreenScene::initPlayback(DisplayEngine* pDisplayEngine, AudioEngine* pAudioEngine, TestHelper* pTestHelper) { Scene::initPlayback(pDisplayEngine, pAudioEngine, pTestHelper); glGenTextures(1, &m_TexID); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OffscreenScene::initPlayback: glGenTextures()"); glBindTexture(GL_TEXTURE_2D, m_TexID); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OffscreenScene::initPlayback: glBindTexture()"); IntPoint size = getSize(); // Mipmaps needed for FBO support on nVidia cards (!?) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glPixelStorei(GL_UNPACK_ROW_LENGTH, size.x); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OffscreenScene::initPlayback: glTexImage2D()"); unsigned multiSampleSamples = dynamic_cast<SDLDisplayEngine*>(pDisplayEngine) ->getOGLOptions().m_MultiSampleSamples; m_pFBO = FBOPtr(new FBO(size, R8G8B8X8, m_TexID, multiSampleSamples)); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); } void OffscreenScene::render() { m_pFBO->activate(); getDisplayEngine()->render(getRootNode(), true); m_pFBO->deactivate(); m_pFBO->copyToDestTexture(); OGLTexturePtr pTex(new OGLTexture(getSize(), B8G8R8X8, MaterialInfo(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true), getDisplayEngine(), PBO)); pTex->setTexID(m_TexID); BitmapPtr pBmp = pTex->readbackBmp(); pBmp->save(getID()+".png"); } std::string OffscreenScene::getID() const { return getRootNode()->getID(); } bool OffscreenScene::isRunning() const { return (m_pFBO != FBOPtr()); } unsigned OffscreenScene::getTexID() const { return m_pFBO->getTexture(); } } <commit_msg>Removed debugging code which was causing make distcheck to fail.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "OffscreenScene.h" #include "SDLDisplayEngine.h" #include "SceneNode.h" #include "OGLTexture.h" #include "../base/Exception.h" #include <iostream> using namespace boost; using namespace std; namespace avg { OffscreenScene::OffscreenScene(Player * pPlayer, NodePtr pRootNode) : Scene(pPlayer, pRootNode) { if (!pRootNode) { throw (Exception(AVG_ERR_XML_PARSE, "Root node of a scene tree needs to be a <scene> node.")); } if (pRootNode->getID() == "") { throw (Exception(AVG_ERR_XML_PARSE, "Root node of a scene tree needs to have an id.")); } } OffscreenScene::~OffscreenScene() { glDeleteTextures(1, &m_TexID); } void OffscreenScene::initPlayback(DisplayEngine* pDisplayEngine, AudioEngine* pAudioEngine, TestHelper* pTestHelper) { Scene::initPlayback(pDisplayEngine, pAudioEngine, pTestHelper); glGenTextures(1, &m_TexID); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OffscreenScene::initPlayback: glGenTextures()"); glBindTexture(GL_TEXTURE_2D, m_TexID); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OffscreenScene::initPlayback: glBindTexture()"); IntPoint size = getSize(); // Mipmaps needed for FBO support on nVidia cards (!?) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glPixelStorei(GL_UNPACK_ROW_LENGTH, size.x); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OffscreenScene::initPlayback: glTexImage2D()"); unsigned multiSampleSamples = dynamic_cast<SDLDisplayEngine*>(pDisplayEngine) ->getOGLOptions().m_MultiSampleSamples; m_pFBO = FBOPtr(new FBO(size, R8G8B8X8, m_TexID, multiSampleSamples)); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); } void OffscreenScene::render() { m_pFBO->activate(); getDisplayEngine()->render(getRootNode(), true); m_pFBO->deactivate(); m_pFBO->copyToDestTexture(); /* OGLTexturePtr pTex(new OGLTexture(getSize(), B8G8R8X8, MaterialInfo(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, true), getDisplayEngine(), PBO)); pTex->setTexID(m_TexID); BitmapPtr pBmp = pTex->readbackBmp(); pBmp->save(getID()+".png"); */ } std::string OffscreenScene::getID() const { return getRootNode()->getID(); } bool OffscreenScene::isRunning() const { return (m_pFBO != FBOPtr()); } unsigned OffscreenScene::getTexID() const { return m_pFBO->getTexture(); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fileidentifierconverter.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: sb $ $Date: 2001-06-06 07:32:36 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_ #include <ucbhelper/fileidentifierconverter.hxx> #endif #ifndef _COM_SUN_STAR_UCB_CONTENTPROVIDERINFO_HPP_ #include <com/sun/star/ucb/ContentProviderInfo.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDERMANAGER_HPP_ #include <com/sun/star/ucb/XContentProviderManager.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XFILEIDENTIFIERCONVERTER_HPP_ #include <com/sun/star/ucb/XFileIdentifierConverter.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif using namespace com::sun; using namespace com::sun::star; namespace ucb { //============================================================================ // // getLocalFileURL // //============================================================================ rtl::OUString getLocalFileURL( uno::Reference< star::ucb::XContentProviderManager > const & rManager) SAL_THROW((com::sun::star::uno::RuntimeException)) { OSL_ASSERT(rManager.is()); static sal_Char const * const aBaseURLs[] = { "file:///", "vnd.sun.star.wfs:///" }; sal_Int32 nMaxLocality = -1; rtl::OUString aMaxBaseURL; for (int i = 0; i < sizeof aBaseURLs / sizeof (sal_Char const *); ++i) { rtl::OUString aBaseURL(rtl::OUString::createFromAscii(aBaseURLs[i])); uno::Reference< star::ucb::XFileIdentifierConverter > xConverter(rManager->queryContentProvider(aBaseURL), uno::UNO_QUERY); if (xConverter.is()) { sal_Int32 nLocality = xConverter->getFileProviderLocality(aBaseURL); if (nLocality > nMaxLocality) { nMaxLocality = nLocality; aMaxBaseURL = aBaseURL; } } } return aMaxBaseURL; } //============================================================================ // // getFileURLFromSystemPath // //============================================================================ rtl::OUString getFileURLFromSystemPath( uno::Reference< star::ucb::XContentProviderManager > const & rManager, rtl::OUString const & rBaseURL, rtl::OUString const & rSystemPath) SAL_THROW((com::sun::star::uno::RuntimeException)) { OSL_ASSERT(rManager.is()); uno::Reference< star::ucb::XFileIdentifierConverter > xConverter(rManager->queryContentProvider(rBaseURL), uno::UNO_QUERY); if (xConverter.is()) return xConverter->getFileURLFromSystemPath(rBaseURL, rSystemPath); else return rtl::OUString(); } //============================================================================ // // getSystemPathFromFileURL // //============================================================================ rtl::OUString getSystemPathFromFileURL( uno::Reference< star::ucb::XContentProviderManager > const & rManager, rtl::OUString const & rURL) SAL_THROW((com::sun::star::uno::RuntimeException)) { OSL_ASSERT(rManager.is()); uno::Reference< star::ucb::XFileIdentifierConverter > xConverter(rManager->queryContentProvider(rURL), uno::UNO_QUERY); if (xConverter.is()) return xConverter->getSystemPathFromFileURL(rURL); else return rtl::OUString(); } } <commit_msg>INTEGRATION: CWS sb33 (1.4.166); FILE MERGED 2005/06/27 16:12:36 sb 1.4.166.1: #i51181# Reduced getLocalFileURL to the minimum, so that it no longer instantiates the catch-all gnomevfs UCP for the nonexistent vnd.sun.star.wfs schema.<commit_after>/************************************************************************* * * $RCSfile: fileidentifierconverter.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2005-07-07 10:55:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_ #include <ucbhelper/fileidentifierconverter.hxx> #endif #ifndef _COM_SUN_STAR_UCB_CONTENTPROVIDERINFO_HPP_ #include <com/sun/star/ucb/ContentProviderInfo.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDERMANAGER_HPP_ #include <com/sun/star/ucb/XContentProviderManager.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XFILEIDENTIFIERCONVERTER_HPP_ #include <com/sun/star/ucb/XFileIdentifierConverter.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif using namespace com::sun; using namespace com::sun::star; namespace ucb { //============================================================================ // // getLocalFileURL // //============================================================================ rtl::OUString getLocalFileURL( uno::Reference< star::ucb::XContentProviderManager > const &) SAL_THROW((com::sun::star::uno::RuntimeException)) { // If there were more file systems than just "file:///" (e.g., the obsolete // "vnd.sun.star.wfs:///"), this code should query all relevant UCPs for // their com.sun.star.ucb.XFileIdentifierConverter.getFileProviderLocality // and return the most local one: return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("file:///")); } //============================================================================ // // getFileURLFromSystemPath // //============================================================================ rtl::OUString getFileURLFromSystemPath( uno::Reference< star::ucb::XContentProviderManager > const & rManager, rtl::OUString const & rBaseURL, rtl::OUString const & rSystemPath) SAL_THROW((com::sun::star::uno::RuntimeException)) { OSL_ASSERT(rManager.is()); uno::Reference< star::ucb::XFileIdentifierConverter > xConverter(rManager->queryContentProvider(rBaseURL), uno::UNO_QUERY); if (xConverter.is()) return xConverter->getFileURLFromSystemPath(rBaseURL, rSystemPath); else return rtl::OUString(); } //============================================================================ // // getSystemPathFromFileURL // //============================================================================ rtl::OUString getSystemPathFromFileURL( uno::Reference< star::ucb::XContentProviderManager > const & rManager, rtl::OUString const & rURL) SAL_THROW((com::sun::star::uno::RuntimeException)) { OSL_ASSERT(rManager.is()); uno::Reference< star::ucb::XFileIdentifierConverter > xConverter(rManager->queryContentProvider(rURL), uno::UNO_QUERY); if (xConverter.is()) return xConverter->getSystemPathFromFileURL(rURL); else return rtl::OUString(); } } <|endoftext|>
<commit_before>#include <stdio.h> #include <vector> #include <cmath> #include "ChSystemParallel.h" #include "ChLcpSystemDescriptorParallel.h" #include "utils/input_output.h" #include "utils/generators.h" using namespace chrono; using std::cout; using std::endl; // ======================================================================= enum ProblemType { SETTLING, DROPPING }; ProblemType problem = SETTLING; // ======================================================================= // Global problem definitions int threads = 8; // Simulation parameters double gravity = 9.81; double time_step = 0.0001; double time_settling_min = 1; double time_settling_max = 5; double time_dropping = 1; int max_iteration = 20; // Output const char* data_folder = "../CRATER"; const char* checkpoint_file = "../CRATER/settled.dat"; double out_fps = 30; // Parameters for the granular material int Id_g = 1; double r_g = 1e-3 / 2; double rho_g = 2500; double vol_g = (4.0/3) * PI * r_g * r_g * r_g; double mass_g = rho_g * vol_g; ChVector<> inertia_g = 0.4 * mass_g * r_g * r_g * ChVector<>(1,1,1); float Y_g = 1e8; float mu_g = 0.3; float alpha_g = 0.1; // Parameters for the falling ball int Id_b = 0; double R_b = 2.54e-2 / 2; double rho_b = 2000; double vol_b = (4.0/3) * PI * R_b * R_b * R_b; double mass_b = rho_b * vol_b; ChVector<> inertia_b = 0.4 * mass_b * R_b * R_b * ChVector<>(1,1,1); float Y_b = 1e8; float mu_b = 0.3; float alpha_b = 0.1; // Parameters for the containing bin int binId = -200; double hDimX = 4.5e-2; // length in x direction double hDimY = 4.5e-2; // depth in y direction double hDimZ = 7.5e-2; // height in z direction double hThickness = 0.5e-2; // wall thickness float Y_c = 2e6; float mu_c = 0.3; float alpha_c = 0.6; // Height of the generator domain double genHeight = 8e-2; // Drop height (above surface of settled granular material) double h = 10e-2; // ======================================================================= void AddWall(ChSharedBodyDEMPtr& body, const ChVector<>& loc, const ChVector<>& dim) { // Append to collision geometry body->GetCollisionModel()->AddBox(dim.x, dim.y, dim.z, loc); // Append to assets ChSharedPtr<ChBoxShape> box_shape = ChSharedPtr<ChAsset>(new ChBoxShape); box_shape->SetColor(ChColor(1, 0, 0)); box_shape->Pos = loc; box_shape->Rot = ChQuaternion<>(1, 0, 0, 0); box_shape->GetBoxGeometry().Size = dim; body->GetAssets().push_back(box_shape); } int CreateObjects(ChSystemParallel* system) { // Create a material for the granular material ChSharedPtr<ChMaterialSurfaceDEM> mat_g; mat_g = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM); mat_g->SetYoungModulus(Y_g); mat_g->SetFriction(mu_g); mat_g->SetDissipationFactor(alpha_g); // Create a material for the container ChSharedPtr<ChMaterialSurfaceDEM> mat_c; mat_c = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM); mat_c->SetYoungModulus(Y_c); mat_c->SetFriction(mu_c); mat_c->SetDissipationFactor(alpha_c); // Create a mixture entirely made out of spheres utils::Generator gen(system); utils::MixtureIngredientPtr& m1 = gen.AddMixtureIngredient(utils::SPHERE, 1.0); m1->setDefaultMaterialDEM(mat_g); m1->setDefaultDensity(rho_g); m1->setDefaultSize(r_g); gen.setBodyIdentifier(Id_g); double r = 1.01 * r_g; gen.createObjectsBox(utils::POISSON_DISK, 2 * r, ChVector<>(0, 0, r + genHeight/2), ChVector<>(hDimX - r, hDimY - r, genHeight/2)); cout << "Number bodies generated: " << gen.getTotalNumBodies() << endl; // Create the containing bin ChSharedBodyDEMPtr bin(new ChBodyDEM(new ChCollisionModelParallel)); bin->SetMaterialSurfaceDEM(mat_c); bin->SetIdentifier(binId); bin->SetMass(1); bin->SetPos(ChVector<>(0, 0, 0)); bin->SetRot(ChQuaternion<>(1, 0, 0, 0)); bin->SetCollide(true); bin->SetBodyFixed(true); bin->GetCollisionModel()->ClearModel(); AddWall(bin, ChVector<>(0, 0, -hThickness), ChVector<>(hDimX, hDimY, hThickness)); AddWall(bin, ChVector<>(-hDimX-hThickness, 0, hDimZ), ChVector<>(hThickness, hDimY, hDimZ)); AddWall(bin, ChVector<>( hDimX+hThickness, 0, hDimZ), ChVector<>(hThickness, hDimY, hDimZ)); AddWall(bin, ChVector<>(0, -hDimY-hThickness, hDimZ), ChVector<>(hDimX, hThickness, hDimZ)); AddWall(bin, ChVector<>(0, hDimY+hThickness, hDimZ), ChVector<>(hDimX, hThickness, hDimZ)); bin->GetCollisionModel()->BuildModel(); system->AddBody(bin); return gen.getTotalNumBodies(); } // ======================================================================= // Create the falling ball such that its bottom point is at the specified // height and its downward initial velocity has the specified magnitude. void CreateFallingBall(ChSystemParallel* system, double z, double vz) { // Create a material for the falling ball ChSharedPtr<ChMaterialSurfaceDEM> mat_b; mat_b = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM); mat_b->SetYoungModulus(1e8f); mat_b->SetFriction(0.4f); mat_b->SetDissipationFactor(0.1f); // Create the falling ball, but do not add it to the system ChSharedBodyDEMPtr ball(new ChBodyDEM(new ChCollisionModelParallel)); ball->SetMaterialSurfaceDEM(mat_b); ball->SetIdentifier(Id_b); ball->SetMass(mass_b); ball->SetInertiaXX(inertia_b); ball->SetPos(ChVector<>(0, 0, z + R_b)); ball->SetRot(ChQuaternion<>(1, 0, 0, 0)); ball->SetPos_dt(ChVector<>(0, 0, -vz)); ball->SetCollide(true); ball->SetBodyFixed(false); ball->GetCollisionModel()->ClearModel(); ball->GetCollisionModel()->AddSphere(R_b); ball->GetCollisionModel()->BuildModel(); ChSharedPtr<ChSphereShape> ball_shape = ChSharedPtr<ChAsset>(new ChSphereShape); ball_shape->SetColor(ChColor(0, 0, 1)); ball_shape->GetSphereGeometry().rad = R_b; ball_shape->Pos = ChVector<>(0, 0, 0); ball_shape->Rot = ChQuaternion<>(1, 0, 0, 0); ball->GetAssets().push_back(ball_shape); system->AddBody(ball); } // ======================================================================== // These utility functions find the height of the highest or lowest sphere // in the granular mix, respectively. We only look at bodies whith stricty // positive identifiers. double FindHighest(ChSystem* sys) { double highest = 0; for (int i = 0; i < sys->Get_bodylist()->size(); ++i) { ChBody* body = (ChBody*) sys->Get_bodylist()->at(i); if (body->GetIdentifier() > 0 && body->GetPos().z > highest) highest = body->GetPos().z; } return highest; } double FindLowest(ChSystem* sys) { double lowest = 1000; for (int i = 0; i < sys->Get_bodylist()->size(); ++i) { ChBody* body = (ChBody*) sys->Get_bodylist()->at(i); if (body->GetIdentifier() > 0 && body->GetPos().z < lowest) lowest = body->GetPos().z; } return lowest; } // ======================================================================== // This utility function returns true if all bodies in the granular mix // have a linear velocity whose magnitude is below the specified value. bool CheckSettled(ChSystem* sys, double threshold) { double t2 = threshold * threshold; for (int i = 0; i < sys->Get_bodylist()->size(); ++i) { ChBody* body = (ChBody*) sys->Get_bodylist()->at(i); if (body->GetIdentifier() > 0) { double vel2 = body->GetPos_dt().Length2(); if (vel2 > t2) return false; } } return true; } // ======================================================================== int main(int argc, char* argv[]) { // Create system ChSystemParallelDEM* msystem = new ChSystemParallelDEM(); // Set number of threads. int max_threads = msystem->GetParallelThreadNumber(); if (threads > max_threads) threads = max_threads; msystem->SetParallelThreadNumber(threads); omp_set_num_threads(threads); // Set gravitational acceleration msystem->Set_G_acc(ChVector<>(0, 0, -gravity)); // Edit system settings msystem->SetMaxiter(max_iteration); msystem->SetIterLCPmaxItersSpeed(max_iteration); msystem->SetTol(1e-3); msystem->SetTolSpeeds(1e-3); msystem->SetStep(time_step); ((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetMaxIteration(max_iteration); ((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetTolerance(0); ((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetContactRecoverySpeed(1); ((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->setBinsPerAxis(I3(10, 10, 10)); ((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->setBodyPerBin(100, 50); ((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->ChangeNarrowphase(new ChCNarrowphaseR); // Depending on problem type: // - Select end simulation times // - Create granular material and container // - Create falling ball double time_end; if (problem == SETTLING) { time_end = time_settling_max; // Create containing bin and the granular material at randomized initial positions CreateObjects(msystem); } else { time_end = time_dropping; // Create the granular material bodies and the container from the checkpoint file. utils::ReadCheckpoint(msystem, checkpoint_file); // Create the falling ball just above the granular material with a velocity // given by free fall from the specified height and starting at rest. double z = FindHighest(msystem); double vz = std::sqrt(2 * gravity * h); CreateFallingBall(msystem, z, vz); } // Number of steps int num_steps = std::ceil(time_end / time_step); int out_steps = std::ceil((1 / time_step) / out_fps); // Zero velocity level for settling check (fraction of a grain radius per second) double zero_v = 0.1 * r_g; // Perform the simulation double time = 0; int sim_frame = 0; int out_frame = 0; int next_out_frame = 0; double exec_time = 0; while (time < time_end) { if (sim_frame == next_out_frame) { char filename[100]; sprintf(filename, "%s/POVRAY/data_%03d.dat", data_folder, out_frame); utils::WriteShapesPovray(msystem, filename); cout << " --------------------------------- " << out_frame << " " << time << " " << endl; cout << " " << FindLowest(msystem) << endl; cout << " " << exec_time << endl; out_frame++; next_out_frame += out_steps; } if (problem == SETTLING && time > time_settling_min && CheckSettled(msystem, zero_v)) { cout << "Granular material settled... time = " << time << endl; break; } msystem->DoStepDynamics(time_step); time += time_step; sim_frame++; exec_time += msystem->mtimer_step(); } // Create a checkpoint from the last state if (problem == SETTLING) utils::WriteCheckpoint(msystem, checkpoint_file); // Final stats cout << "==================================" << endl; cout << "Number of bodies: " << msystem->Get_bodylist()->size() << endl; cout << "Lowest position: " << FindLowest(msystem) << endl; cout << "Simulation time: " << exec_time << endl; cout << "Number of threads: " << threads << endl; return 0; } <commit_msg>For efficiency, generate granules in layers.<commit_after>#include <stdio.h> #include <vector> #include <cmath> #include "ChSystemParallel.h" #include "ChLcpSystemDescriptorParallel.h" #include "utils/input_output.h" #include "utils/generators.h" using namespace chrono; using std::cout; using std::endl; // ======================================================================= enum ProblemType { SETTLING, DROPPING }; ProblemType problem = SETTLING; // ======================================================================= // Global problem definitions int threads = 8; // Simulation parameters double gravity = 9.81; double time_step = 0.0001; double time_settling_min = 1; double time_settling_max = 5; double time_dropping = 1; int max_iteration = 20; // Output const char* data_folder = "../CRATER"; const char* checkpoint_file = "../CRATER/settled.dat"; double out_fps = 30; // Parameters for the granular material int Id_g = 1; double r_g = 1e-3 / 2; double rho_g = 2500; double vol_g = (4.0/3) * PI * r_g * r_g * r_g; double mass_g = rho_g * vol_g; ChVector<> inertia_g = 0.4 * mass_g * r_g * r_g * ChVector<>(1,1,1); float Y_g = 1e8; float mu_g = 0.3; float alpha_g = 0.1; // Parameters for the falling ball int Id_b = 0; double R_b = 2.54e-2 / 2; double rho_b = 2000; double vol_b = (4.0/3) * PI * R_b * R_b * R_b; double mass_b = rho_b * vol_b; ChVector<> inertia_b = 0.4 * mass_b * R_b * R_b * ChVector<>(1,1,1); float Y_b = 1e8; float mu_b = 0.3; float alpha_b = 0.1; // Parameters for the containing bin int binId = -200; double hDimX = 4.5e-2; // length in x direction double hDimY = 4.5e-2; // depth in y direction double hDimZ = 7.5e-2; // height in z direction double hThickness = 0.5e-2; // wall thickness float Y_c = 2e6; float mu_c = 0.3; float alpha_c = 0.6; // Number of layers and height of one layer for generator domain int numLayers = 4; double layerHeight = 1e-2; // Drop height (above surface of settled granular material) double h = 10e-2; // ======================================================================= void AddWall(ChSharedBodyDEMPtr& body, const ChVector<>& loc, const ChVector<>& dim) { // Append to collision geometry body->GetCollisionModel()->AddBox(dim.x, dim.y, dim.z, loc); // Append to assets ChSharedPtr<ChBoxShape> box_shape = ChSharedPtr<ChAsset>(new ChBoxShape); box_shape->SetColor(ChColor(1, 0, 0)); box_shape->Pos = loc; box_shape->Rot = ChQuaternion<>(1, 0, 0, 0); box_shape->GetBoxGeometry().Size = dim; body->GetAssets().push_back(box_shape); } int CreateObjects(ChSystemParallel* system) { // Create a material for the granular material ChSharedPtr<ChMaterialSurfaceDEM> mat_g; mat_g = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM); mat_g->SetYoungModulus(Y_g); mat_g->SetFriction(mu_g); mat_g->SetDissipationFactor(alpha_g); // Create a material for the container ChSharedPtr<ChMaterialSurfaceDEM> mat_c; mat_c = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM); mat_c->SetYoungModulus(Y_c); mat_c->SetFriction(mu_c); mat_c->SetDissipationFactor(alpha_c); // Create a mixture entirely made out of spheres utils::Generator gen(system); utils::MixtureIngredientPtr& m1 = gen.AddMixtureIngredient(utils::SPHERE, 1.0); m1->setDefaultMaterialDEM(mat_g); m1->setDefaultDensity(rho_g); m1->setDefaultSize(r_g); gen.setBodyIdentifier(Id_g); double r = 1.01 * r_g; for (int i = 0; i < numLayers; i++) { double center = r + layerHeight / 2 + i * (r + layerHeight); gen.createObjectsBox(utils::POISSON_DISK, 2 * r, ChVector<>(0, 0, center), ChVector<>(hDimX - r, hDimY - r, layerHeight/2)); cout << "Layer " << i << "total bodies: " << gen.getTotalNumBodies() << endl; } // Create the containing bin ChSharedBodyDEMPtr bin(new ChBodyDEM(new ChCollisionModelParallel)); bin->SetMaterialSurfaceDEM(mat_c); bin->SetIdentifier(binId); bin->SetMass(1); bin->SetPos(ChVector<>(0, 0, 0)); bin->SetRot(ChQuaternion<>(1, 0, 0, 0)); bin->SetCollide(true); bin->SetBodyFixed(true); bin->GetCollisionModel()->ClearModel(); AddWall(bin, ChVector<>(0, 0, -hThickness), ChVector<>(hDimX, hDimY, hThickness)); AddWall(bin, ChVector<>(-hDimX-hThickness, 0, hDimZ), ChVector<>(hThickness, hDimY, hDimZ)); AddWall(bin, ChVector<>( hDimX+hThickness, 0, hDimZ), ChVector<>(hThickness, hDimY, hDimZ)); AddWall(bin, ChVector<>(0, -hDimY-hThickness, hDimZ), ChVector<>(hDimX, hThickness, hDimZ)); AddWall(bin, ChVector<>(0, hDimY+hThickness, hDimZ), ChVector<>(hDimX, hThickness, hDimZ)); bin->GetCollisionModel()->BuildModel(); system->AddBody(bin); return gen.getTotalNumBodies(); } // ======================================================================= // Create the falling ball such that its bottom point is at the specified // height and its downward initial velocity has the specified magnitude. void CreateFallingBall(ChSystemParallel* system, double z, double vz) { // Create a material for the falling ball ChSharedPtr<ChMaterialSurfaceDEM> mat_b; mat_b = ChSharedPtr<ChMaterialSurfaceDEM>(new ChMaterialSurfaceDEM); mat_b->SetYoungModulus(1e8f); mat_b->SetFriction(0.4f); mat_b->SetDissipationFactor(0.1f); // Create the falling ball, but do not add it to the system ChSharedBodyDEMPtr ball(new ChBodyDEM(new ChCollisionModelParallel)); ball->SetMaterialSurfaceDEM(mat_b); ball->SetIdentifier(Id_b); ball->SetMass(mass_b); ball->SetInertiaXX(inertia_b); ball->SetPos(ChVector<>(0, 0, z + R_b)); ball->SetRot(ChQuaternion<>(1, 0, 0, 0)); ball->SetPos_dt(ChVector<>(0, 0, -vz)); ball->SetCollide(true); ball->SetBodyFixed(false); ball->GetCollisionModel()->ClearModel(); ball->GetCollisionModel()->AddSphere(R_b); ball->GetCollisionModel()->BuildModel(); ChSharedPtr<ChSphereShape> ball_shape = ChSharedPtr<ChAsset>(new ChSphereShape); ball_shape->SetColor(ChColor(0, 0, 1)); ball_shape->GetSphereGeometry().rad = R_b; ball_shape->Pos = ChVector<>(0, 0, 0); ball_shape->Rot = ChQuaternion<>(1, 0, 0, 0); ball->GetAssets().push_back(ball_shape); system->AddBody(ball); } // ======================================================================== // These utility functions find the height of the highest or lowest sphere // in the granular mix, respectively. We only look at bodies whith stricty // positive identifiers. double FindHighest(ChSystem* sys) { double highest = 0; for (int i = 0; i < sys->Get_bodylist()->size(); ++i) { ChBody* body = (ChBody*) sys->Get_bodylist()->at(i); if (body->GetIdentifier() > 0 && body->GetPos().z > highest) highest = body->GetPos().z; } return highest; } double FindLowest(ChSystem* sys) { double lowest = 1000; for (int i = 0; i < sys->Get_bodylist()->size(); ++i) { ChBody* body = (ChBody*) sys->Get_bodylist()->at(i); if (body->GetIdentifier() > 0 && body->GetPos().z < lowest) lowest = body->GetPos().z; } return lowest; } // ======================================================================== // This utility function returns true if all bodies in the granular mix // have a linear velocity whose magnitude is below the specified value. bool CheckSettled(ChSystem* sys, double threshold) { double t2 = threshold * threshold; for (int i = 0; i < sys->Get_bodylist()->size(); ++i) { ChBody* body = (ChBody*) sys->Get_bodylist()->at(i); if (body->GetIdentifier() > 0) { double vel2 = body->GetPos_dt().Length2(); if (vel2 > t2) return false; } } return true; } // ======================================================================== int main(int argc, char* argv[]) { // Create system ChSystemParallelDEM* msystem = new ChSystemParallelDEM(); // Set number of threads. int max_threads = msystem->GetParallelThreadNumber(); if (threads > max_threads) threads = max_threads; msystem->SetParallelThreadNumber(threads); omp_set_num_threads(threads); // Set gravitational acceleration msystem->Set_G_acc(ChVector<>(0, 0, -gravity)); // Edit system settings msystem->SetMaxiter(max_iteration); msystem->SetIterLCPmaxItersSpeed(max_iteration); msystem->SetTol(1e-3); msystem->SetTolSpeeds(1e-3); msystem->SetStep(time_step); ((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetMaxIteration(max_iteration); ((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetTolerance(0); ((ChLcpSolverParallelDEM*) msystem->GetLcpSolverSpeed())->SetContactRecoverySpeed(1); ((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->setBinsPerAxis(I3(10, 10, 10)); ((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->setBodyPerBin(100, 50); ((ChCollisionSystemParallel*) msystem->GetCollisionSystem())->ChangeNarrowphase(new ChCNarrowphaseR); // Depending on problem type: // - Select end simulation times // - Create granular material and container // - Create falling ball double time_end; if (problem == SETTLING) { time_end = time_settling_max; // Create containing bin and the granular material at randomized initial positions CreateObjects(msystem); } else { time_end = time_dropping; // Create the granular material bodies and the container from the checkpoint file. utils::ReadCheckpoint(msystem, checkpoint_file); // Create the falling ball just above the granular material with a velocity // given by free fall from the specified height and starting at rest. double z = FindHighest(msystem); double vz = std::sqrt(2 * gravity * h); CreateFallingBall(msystem, z, vz); } // Number of steps int num_steps = std::ceil(time_end / time_step); int out_steps = std::ceil((1 / time_step) / out_fps); // Zero velocity level for settling check (fraction of a grain radius per second) double zero_v = 0.1 * r_g; // Perform the simulation double time = 0; int sim_frame = 0; int out_frame = 0; int next_out_frame = 0; double exec_time = 0; while (time < time_end) { if (sim_frame == next_out_frame) { char filename[100]; sprintf(filename, "%s/POVRAY/data_%03d.dat", data_folder, out_frame); utils::WriteShapesPovray(msystem, filename); cout << " --------------------------------- " << out_frame << " " << time << " " << endl; cout << " " << FindLowest(msystem) << endl; cout << " " << exec_time << endl; out_frame++; next_out_frame += out_steps; } if (problem == SETTLING && time > time_settling_min && CheckSettled(msystem, zero_v)) { cout << "Granular material settled... time = " << time << endl; break; } msystem->DoStepDynamics(time_step); time += time_step; sim_frame++; exec_time += msystem->mtimer_step(); } // Create a checkpoint from the last state if (problem == SETTLING) utils::WriteCheckpoint(msystem, checkpoint_file); // Final stats cout << "==================================" << endl; cout << "Number of bodies: " << msystem->Get_bodylist()->size() << endl; cout << "Lowest position: " << FindLowest(msystem) << endl; cout << "Simulation time: " << exec_time << endl; cout << "Number of threads: " << threads << endl; return 0; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep12/call_omi_setup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file call_omi_setup.C * * Contains the wrapper for Istep 12.6 * exp_omi_setup * p10_omi_setup */ #include <stdint.h> #include <trace/interface.H> #include <initservice/taskargs.H> #include <errl/errlentry.H> #include <isteps/hwpisteperror.H> #include <errl/errludtarget.H> #include <initservice/isteps_trace.H> #include <istepHelperFuncs.H> // captureError // Fapi Support #include <config.h> #include <fapi2/plat_hwp_invoker.H> // HWP #include <exp_omi_setup.H> using namespace ISTEP; using namespace ISTEP_ERROR; using namespace ERRORLOG; using namespace TARGETING; using namespace ISTEPS_TRACE; namespace ISTEP_12 { void* call_omi_setup (void *io_pArgs) { IStepError l_StepError; errlHndl_t l_err = nullptr; TRACFCOMP( g_trac_isteps_trace, "call_omi_setup entry" ); do { // 12.6.a exp_omi_setup.C // - Set any register (via I2C) on the Explorer before OMI is // trained TargetHandleList l_ocmbTargetList; getAllChips(l_ocmbTargetList, TYPE_OCMB_CHIP); TRACFCOMP(g_trac_isteps_trace, "call_omi_setup: %d OCMBs found", l_ocmbTargetList.size()); for (const auto & l_ocmb_target : l_ocmbTargetList) { // call the HWP with each target fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP> l_fapi_ocmb_target (l_ocmb_target); TRACFCOMP(g_trac_isteps_trace, "exp_omi_setup HWP target HUID 0x%.08x", get_huid(l_ocmb_target)); FAPI_INVOKE_HWP(l_err, exp_omi_setup, l_fapi_ocmb_target); // process return code if ( l_err ) { TRACFCOMP(g_trac_isteps_trace, "ERROR : call exp_omi_setup HWP: failed on target 0x%08X. " TRACE_ERR_FMT, get_huid(l_ocmb_target), TRACE_ERR_ARGS(l_err)); // Capture error captureError(l_err, l_StepError, HWPF_COMP_ID, l_ocmb_target); } } // Do not continue if an error was encountered if(!l_StepError.isNull()) { TRACFCOMP( g_trac_isteps_trace, INFO_MRK "call_omi_setup exited early because exp_omi_setup " "had failures" ); break; } // 12.6.b p10_omi_setup.C // - File does not currently exist // - TODO: RTC 248244 } while (0); TRACFCOMP(g_trac_isteps_trace, "call_omi_setup exit" ); // end task, returning any errorlogs to IStepDisp return l_StepError.getErrorHandle(); } }; <commit_msg>Parellelize omi_setup istep<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep12/call_omi_setup.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file call_omi_setup.C * * Contains the wrapper for Istep 12.6 * exp_omi_setup * p10_omi_setup */ #include <stdint.h> #include <trace/interface.H> #include <initservice/taskargs.H> #include <errl/errlentry.H> #include <util/threadpool.H> #include <sys/task.h> #include <initservice/istepdispatcherif.H> #include <isteps/hwpisteperror.H> #include <errl/errludtarget.H> #include <initservice/isteps_trace.H> #include <istepHelperFuncs.H> // captureError // Fapi Support #include <config.h> #include <fapi2/plat_hwp_invoker.H> // HWP #include <exp_omi_setup.H> using namespace ISTEP; using namespace ISTEP_ERROR; using namespace ERRORLOG; using namespace TARGETING; using namespace ISTEPS_TRACE; namespace ISTEP_12 { // // @brief Mutex to prevent threads from adding details to the step // error log at the same time. mutex_t g_stepErrorMutex = MUTEX_INITIALIZER; /******************************************************************************* * @brief base work item class for isteps (used by thread pool) */ class IStepWorkItem { public: virtual ~IStepWorkItem(){} virtual void operator()() = 0; }; /******************************************************************************* * @brief Ocmb specific work item class */ class OcmbWorkItem: public IStepWorkItem { private: IStepError* iv_pStepError; const TARGETING::Target* iv_pOcmb; public: /** * @brief task function, called by threadpool to run the HWP on the * target */ void operator()(); /** * @brief ctor * * @param[in] i_Ocmb target Ocmb to operate on * @param[in] i_istepError error accumulator for this istep */ OcmbWorkItem(const TARGETING::Target& i_Ocmb, IStepError& i_stepError): iv_pStepError(&i_stepError), iv_pOcmb(&i_Ocmb) {} // delete default copy/move constructors and operators OcmbWorkItem() = delete; OcmbWorkItem(const OcmbWorkItem& ) = delete; OcmbWorkItem& operator=(const OcmbWorkItem& ) = delete; OcmbWorkItem(OcmbWorkItem&&) = delete; OcmbWorkItem& operator=(OcmbWorkItem&&) = delete; /** * @brief destructor */ ~OcmbWorkItem(){}; }; //****************************************************************************** void OcmbWorkItem::operator()() { errlHndl_t l_err = nullptr; // reset watchdog for each ocmb as this function can be very slow INITSERVICE::sendProgressCode(); // call the HWP with each target fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP> l_fapi_ocmb_target (iv_pOcmb); TRACFCOMP(g_trac_isteps_trace, "exp_omi_setup HWP target HUID 0x%.08x", get_huid(iv_pOcmb)); FAPI_INVOKE_HWP(l_err, exp_omi_setup, l_fapi_ocmb_target); // process return code if ( l_err ) { TRACFCOMP(g_trac_isteps_trace, "ERROR : call exp_omi_setup HWP: failed on target 0x%08X. " TRACE_ERR_FMT, get_huid(iv_pOcmb), TRACE_ERR_ARGS(l_err)); //addErrorDetails may not be thread-safe. Protect with mutex. mutex_lock(&g_stepErrorMutex); // Capture error captureError(l_err, *iv_pStepError, HWPF_COMP_ID, iv_pOcmb); mutex_unlock(&g_stepErrorMutex); } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS running exp_omi_setup HWP on target HUID %.8X.", TARGETING::get_huid(iv_pOcmb)); } } void* call_omi_setup (void *io_pArgs) { IStepError l_StepError; errlHndl_t l_err = nullptr; TRACFCOMP( g_trac_isteps_trace, "call_omi_setup entry" ); Util::ThreadPool<IStepWorkItem> threadpool; constexpr size_t MAX_OCMB_THREADS = 4; uint32_t l_numThreads = 0; do { // 12.6.a exp_omi_setup.C // - Set any register (via I2C) on the Explorer before OMI is // trained TargetHandleList l_ocmbTargetList; getAllChips(l_ocmbTargetList, TYPE_OCMB_CHIP); TRACFCOMP(g_trac_isteps_trace, "call_omi_setup: %d OCMBs found", l_ocmbTargetList.size()); for (const auto & l_ocmb_target : l_ocmbTargetList) { // Create a new workitem from this membuf and feed it to the // thread pool for processing. Thread pool handles workitem // cleanup. threadpool.insert(new OcmbWorkItem(*l_ocmb_target, l_StepError)); } //Don't create more threads than we have targets size_t l_numTargets = l_ocmbTargetList.size(); l_numThreads = std::min(MAX_OCMB_THREADS, l_numTargets); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Starting %llu thread(s) to handle %llu OCMB target(s)", l_numThreads, l_numTargets); //Set the number of threads to use in the threadpool Util::ThreadPoolManager::setThreadCount(l_numThreads); //create and start worker threads threadpool.start(); //wait for all workitems to complete, then clean up all threads. l_err = threadpool.shutdown(); if(l_err) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK"call_omi_setup: thread pool returned an error" TRACE_ERR_FMT, TRACE_ERR_ARGS(l_err)); //addErrorDetails may not be thread-safe. Protect with mutex. mutex_lock(&g_stepErrorMutex); // Capture error captureError(l_err, l_StepError, HWPF_COMP_ID, nullptr); mutex_unlock(&g_stepErrorMutex); } // Do not continue if an error was encountered if(!l_StepError.isNull()) { TRACFCOMP( g_trac_isteps_trace, INFO_MRK "call_omi_setup exited early because exp_omi_setup " "had failures" ); break; } // 12.6.b p10_omi_setup.C // - File does not currently exist // - TODO: RTC 248244 } while (0); TRACFCOMP(g_trac_isteps_trace, "call_omi_setup exit" ); // end task, returning any errorlogs to IStepDisp return l_StepError.getErrorHandle(); } }; <|endoftext|>
<commit_before>#include "IdDictionary.hpp" #include <ros/console.h> using namespace std; IdDictionary::IdDictionary() { translated = false; } bool IdDictionary::contains(int n) { mutex.lock(); for (vector<int>::iterator it = ids.begin(); it != ids.end(); it++) { if (*it == n) { mutex.unlock(); return true; } } mutex.unlock(); return false; } void IdDictionary::insert(int n) { if (contains(n)) { return; } if (translated) { ROS_ERROR("insert: Ids already translated!"); } mutex.lock(); ROS_DEBUG("Inserted id %d", n); ids.push_back(n); mutex.unlock(); } int IdDictionary::size() { return ids.size(); } void IdDictionary::translateIds() { if (translated) { return; } mutex.lock(); ROS_DEBUG("Translating dictionary with %d ids", size()); translated = true; std::sort(ids.begin(), ids.end()); int id = 0; for (vector<int>::iterator it = ids.begin(); it != ids.end(); it++, id++) { backward[id] = *it; forward[*it] = id; } mutex.unlock(); } bool IdDictionary::isTranslated() { return translated; } int IdDictionary::getForward(int n) { if (!translated) { ROS_ERROR("getForward: Ids not translated!"); } mutex.lock(); if (forward.count(n)) { mutex.unlock(); return forward[n]; } else { ROS_ERROR("getForward: Unknown id %d", n); mutex.unlock(); return -1; } } int IdDictionary::getBackward(int n) { if (!translated) { ROS_ERROR("getBackward: Ids not translated!"); } mutex.lock(); if (backward.count(n)) { mutex.unlock(); return backward[n]; } else { ROS_ERROR("getBackward: Unknown id %d", n); mutex.unlock(); return -1; } }<commit_msg>Changed returning<commit_after>#include "IdDictionary.hpp" #include <ros/console.h> using namespace std; IdDictionary::IdDictionary() { translated = false; } bool IdDictionary::contains(int n) { mutex.lock(); for (vector<int>::iterator it = ids.begin(); it != ids.end(); it++) { if (*it == n) { mutex.unlock(); return true; } } mutex.unlock(); return false; } void IdDictionary::insert(int n) { if (contains(n)) { return; } if (translated) { ROS_ERROR("insert: Ids already translated!"); } mutex.lock(); ROS_DEBUG("Inserted id %d", n); ids.push_back(n); mutex.unlock(); } int IdDictionary::size() { return ids.size(); } void IdDictionary::translateIds() { if (translated) { return; } mutex.lock(); ROS_DEBUG("Translating dictionary with %d ids", size()); translated = true; std::sort(ids.begin(), ids.end()); int id = 0; for (vector<int>::iterator it = ids.begin(); it != ids.end(); it++, id++) { backward[id] = *it; forward[*it] = id; } mutex.unlock(); } bool IdDictionary::isTranslated() { return translated; } int IdDictionary::getForward(int n) { if (!translated) { ROS_ERROR("getForward: Ids not translated!"); } mutex.lock(); if (forward.count(n)) { int result = forward[n]; mutex.unlock(); return result; } else { ROS_ERROR("getForward: Unknown id %d", n); mutex.unlock(); return -1; } } int IdDictionary::getBackward(int n) { if (!translated) { ROS_ERROR("getBackward: Ids not translated!"); } mutex.lock(); if (backward.count(n)) { int result = backward[n]; mutex.unlock(); return result; } else { ROS_ERROR("getBackward: Unknown id %d", n); mutex.unlock(); return -1; } }<|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "gtest/gtest.h" #include "PathPattern.h" TEST(PathPattern, CompareEqualPaths) { auto a = PathPattern("/abba/cadabra"); auto b = Path("/abba/cadabra"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathsWithTrailingSlash) { auto a = PathPattern("/abba/cadabra/"); auto b = Path("/abba/cadabra"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareDifferentLength) { auto a = PathPattern("/abba/cadabra/gattaca"); auto b = Path("/abba/cadabra"); EXPECT_FALSE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithSingleWildcard) { auto a = PathPattern("/abba/?/gattaca"); auto b = Path("/abba/cadabra/gattaca"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithMultipleWildcards) { auto a = PathPattern("/?/cadabra/?"); auto b = Path("/abba/cadabra/gattaca"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithGreedyWildcard) { auto a = PathPattern("/abba/*"); auto b = Path("/abba/cadabra/gattaca"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithGreedyWildcardAndSamePartCount) { auto a = PathPattern("/abba/*"); auto b = Path("/abba/cadabra"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithGreedyWildcardCatchAll) { auto a = PathPattern("/*"); auto b = Path("/abba/cadabra/gattaca"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithMixedWildcards) { auto a = PathPattern("/?/cadabra/*"); auto b = Path("/abba/cadabra/gattaca/c"); auto c = Path("/abba/cordoba/gattaca/c"); EXPECT_TRUE(a.match(b)); EXPECT_FALSE(a.tch(c)); }<commit_msg>Fixed accidental deletion of characters in test code.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "gtest/gtest.h" #include "PathPattern.h" TEST(PathPattern, CompareEqualPaths) { auto a = PathPattern("/abba/cadabra"); auto b = Path("/abba/cadabra"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathsWithTrailingSlash) { auto a = PathPattern("/abba/cadabra/"); auto b = Path("/abba/cadabra"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareDifferentLength) { auto a = PathPattern("/abba/cadabra/gattaca"); auto b = Path("/abba/cadabra"); EXPECT_FALSE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithSingleWildcard) { auto a = PathPattern("/abba/?/gattaca"); auto b = Path("/abba/cadabra/gattaca"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithMultipleWildcards) { auto a = PathPattern("/?/cadabra/?"); auto b = Path("/abba/cadabra/gattaca"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithGreedyWildcard) { auto a = PathPattern("/abba/*"); auto b = Path("/abba/cadabra/gattaca"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithGreedyWildcardAndSamePartCount) { auto a = PathPattern("/abba/*"); auto b = Path("/abba/cadabra"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithGreedyWildcardCatchAll) { auto a = PathPattern("/*"); auto b = Path("/abba/cadabra/gattaca"); EXPECT_TRUE(a.match(b)); } TEST(PathPattern, CompareEqualPathWithMixedWildcards) { auto a = PathPattern("/?/cadabra/*"); auto b = Path("/abba/cadabra/gattaca/c"); auto c = Path("/abba/cordoba/gattaca/c"); EXPECT_TRUE(a.match(b)); EXPECT_FALSE(a.match(c)); }<|endoftext|>
<commit_before>/* * This file is part of meego-im-framework * * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * Contact: Kimmo Surakka <kimmo.surakka@nokia.com> * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "maliitquickpluginfactory.h" #include "maliit-plugins-quick/input-method/minputmethodquickplugin.h" class MyPlugin : public MInputMethodQuickPlugin { Q_DISABLE_COPY(MyPlugin) private: const QString m_filename; public: explicit MyPlugin(const QString &filename) : MInputMethodQuickPlugin() , m_filename(filename) {} virtual QString qmlFileName() const { return m_filename; } virtual QString name() const { static QFileInfo info(m_filename); return info.baseName(); } }; MaliitQuickPluginFactory::MaliitQuickPluginFactory(QObject *parent) : QObject(parent) , MImAbstractPluginFactory() {} MaliitQuickPluginFactory::~MaliitQuickPluginFactory() {} QString MaliitQuickPluginFactory::fileExtension() const { return "qml"; } MInputMethodPlugin * MaliitQuickPluginFactory::create(const QString &file) const { return new MyPlugin(file); } Q_EXPORT_PLUGIN2(MaliitQuickPluginFactory, MaliitQuickPluginFactory) <commit_msg>Normalize some includes<commit_after>/* * This file is part of meego-im-framework * * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * Contact: Kimmo Surakka <kimmo.surakka@nokia.com> * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "maliitquickpluginfactory.h" #include "minputmethodquickplugin.h" class MyPlugin : public MInputMethodQuickPlugin { Q_DISABLE_COPY(MyPlugin) private: const QString m_filename; public: explicit MyPlugin(const QString &filename) : MInputMethodQuickPlugin() , m_filename(filename) {} virtual QString qmlFileName() const { return m_filename; } virtual QString name() const { static QFileInfo info(m_filename); return info.baseName(); } }; MaliitQuickPluginFactory::MaliitQuickPluginFactory(QObject *parent) : QObject(parent) , MImAbstractPluginFactory() {} MaliitQuickPluginFactory::~MaliitQuickPluginFactory() {} QString MaliitQuickPluginFactory::fileExtension() const { return "qml"; } MInputMethodPlugin * MaliitQuickPluginFactory::create(const QString &file) const { return new MyPlugin(file); } Q_EXPORT_PLUGIN2(MaliitQuickPluginFactory, MaliitQuickPluginFactory) <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "load_pipe.h" #include "pipe_declaration_types.h" #include "providers.h" #include <vistk/pipeline/config.h> #include <vistk/pipeline/process.h> #include <boost/algorithm/string/join.hpp> #include <boost/tuple/tuple.hpp> #include <boost/foreach.hpp> #include <boost/variant.hpp> #include <algorithm> #include <utility> #include <vector> /** * \file pipe_bakery.cxx * * \brief Implementation of baking a pipeline. */ namespace vistk { namespace { static config_flag_t const flag_read_only = config_flag_t("ro"); static config_provider_t const provider_config = config_provider_t("CONF"); static config_provider_t const provider_environment = config_provider_t("ENV"); static config_provider_t const provider_system = config_provider_t("SYS"); } class VISTK_PIPELINE_UTIL_NO_EXPORT pipe_bakery : public boost::static_visitor<> { public: pipe_bakery(); ~pipe_bakery(); void operator () (config_pipe_block const& config_block); void operator () (process_pipe_block const& process_block); void operator () (connect_pipe_block const& connect_block); void operator () (group_pipe_block const& group_block); /** * \note We do *not* want std::map for the groupings. With a map, we may * hide errors in the blocks (setting ro values, duplicate process names, * etc.) */ typedef std::pair<config_provider_t, config::value_t> provider_request_t; typedef boost::variant<config::value_t, provider_request_t> config_reference_t; typedef boost::tuple<config_reference_t, bool> config_info_t; typedef std::pair<config::key_t, config_info_t> config_decl_t; typedef std::vector<config_decl_t> config_decls_t; typedef std::pair<process::name_t, process_registry::type_t> process_decl_t; typedef std::vector<process_decl_t> process_decls_t; typedef std::pair<process::port_addr_t, process::port_addr_t> connection_t; typedef std::vector<connection_t> connections_t; typedef boost::tuple<process::port_t, process::port_flags_t, process::port_addr_t> mapping_t; typedef std::vector<mapping_t> mappings_t; typedef std::pair<mappings_t, mappings_t> group_info_t; typedef std::pair<process::name_t, group_info_t> group_decl_t; typedef std::vector<group_decl_t> group_decls_t; static config::key_t flatten_keys(config::keys_t const& keys); void register_config_value(config::key_t const& root_key, config_value_t const& value); config_decls_t m_configs; process_decls_t m_processes; connections_t m_connections; group_decls_t m_groups; }; class VISTK_PIPELINE_UTIL_NO_EXPORT provider_dereferencer : public boost::static_visitor<pipe_bakery::config_reference_t> { public: provider_dereferencer(); provider_dereferencer(config_t const conf); ~provider_dereferencer(); pipe_bakery::config_reference_t operator () (config::value_t const& value) const; pipe_bakery::config_reference_t operator () (pipe_bakery::provider_request_t const& request) const; private: typedef std::map<config_provider_t, provider_t> provider_map_t; provider_map_t m_providers; }; class VISTK_PIPELINE_UTIL_NO_EXPORT ensure_provided : public boost::static_visitor<config::value_t> { public: config::value_t operator () (config::value_t const& value) const; config::value_t operator () (pipe_bakery::provider_request_t const& request) const; }; pipeline_t bake_pipe_blocks(pipe_blocks const& blocks) { pipeline_t pipeline; pipe_bakery bakery; std::for_each(blocks.begin(), blocks.end(), boost::apply_visitor(bakery)); // Build configuration. { // Dereference (non-configuration) providers. { BOOST_FOREACH (pipe_bakery::config_decl_t& decl, bakery.m_configs) { pipe_bakery::config_reference_t& ref = decl.second.get<0>(); ref = boost::apply_visitor(provider_dereferencer(), ref); } } config_t conf = config::empty_config(); BOOST_FOREACH (pipe_bakery::config_decl_t& decl, bakery.m_configs) { pipe_bakery::config_reference_t const& ref = decl.second.get<0>(); config::key_t const key = decl.first; config::value_t val; // Only add provided configurations to the configuration. try { val = boost::apply_visitor(ensure_provided(), ref); } catch (...) { continue; } conf->set_value(key, val); } // Dereference configuration providers. { /// \todo Sort requests so circular requests don't occur. /// \todo Find config provider requests. config::keys_t keys; provider_dereferencer deref(conf); /// \todo This is algorithmically naive, but I'm not sure if there's a faster way. BOOST_FOREACH (config::key_t const& key, keys) { BOOST_FOREACH (pipe_bakery::config_decl_t& decl, bakery.m_configs) { config::key_t const& cur_key = decl.first; if (key != cur_key) { continue; } pipe_bakery::config_reference_t& ref = decl.second.get<0>(); ref = boost::apply_visitor(deref, ref); config::value_t const val = boost::apply_visitor(ensure_provided(), ref); // Set the value in the intermediate configuration. conf->set_value(cur_key, val); } } } /// \todo Build final configuration. } /// \todo Bake pipe blocks into a pipeline. return pipeline; } pipe_bakery ::pipe_bakery() { } pipe_bakery ::~pipe_bakery() { } void pipe_bakery ::operator () (config_pipe_block const& config_block) { config::key_t const root_key = flatten_keys(config_block.key); config_values_t const& values = config_block.values; BOOST_FOREACH (config_value_t const& value, values) { register_config_value(root_key, value); } } void pipe_bakery ::operator () (process_pipe_block const& process_block) { config_values_t const& values = process_block.config_values; // Build the configuration value for the name of the process. config_value_t name_value; name_value.key.key_path.push_back(process::config_name); name_value.key.options.flags = config_flags_t(); (*name_value.key.options.flags).push_back(flag_read_only); name_value.value = process_block.name; register_config_value(process_block.name, name_value); BOOST_FOREACH (config_value_t const& value, values) { register_config_value(process_block.name, value); } m_processes.push_back(process_decl_t(process_block.name, process_block.type)); } void pipe_bakery ::operator () (connect_pipe_block const& connect_block) { m_connections.push_back(connection_t(connect_block.from, connect_block.to)); } void pipe_bakery ::operator () (group_pipe_block const& group_block) { config_values_t const& values = group_block.config_values; BOOST_FOREACH (config_value_t const& value, values) { register_config_value(group_block.name, value); } process::port_flags_t default_flags; mappings_t input_mappings; BOOST_FOREACH (input_map_t const& map, group_block.input_mappings) { process::port_flags_t flags = default_flags; if (map.options.flags) { flags = *map.options.flags; } mapping_t const mapping = mapping_t(map.from, flags, map.to); input_mappings.push_back(mapping); } mappings_t output_mappings; BOOST_FOREACH (output_map_t const& map, group_block.output_mappings) { process::port_flags_t flags = default_flags; if (map.options.flags) { flags = *map.options.flags; } mapping_t const mapping = mapping_t(map.to, flags, map.from); output_mappings.push_back(mapping); } group_info_t const info = group_info_t(input_mappings, output_mappings); group_decl_t const decl = group_decl_t(group_block.name, info); m_groups.push_back(decl); } void pipe_bakery ::register_config_value(config::key_t const& root_key, config_value_t const& value) { config_key_t const key = value.key; config::key_t const subkey = flatten_keys(key.key_path); config_reference_t c_value; if (key.options.provider) { c_value = provider_request_t(*key.options.provider, value.value); } else { c_value = value.value; } bool is_readonly = false; if (key.options.flags) { BOOST_FOREACH (config_flag_t const& flag, *key.options.flags) { if (flag == flag_read_only) { is_readonly = true; } else { /// \todo Log warning about unrecognized flag. } } } config::key_t const full_key = root_key + config::block_sep + subkey; config_info_t const info = config_info_t(c_value, is_readonly); config_decl_t const decl = config_decl_t(full_key, info); m_configs.push_back(decl); } config::key_t pipe_bakery ::flatten_keys(config::keys_t const& keys) { return boost::join(keys, config::block_sep); } provider_dereferencer ::provider_dereferencer() { m_providers[provider_system] = provider_t(new system_provider); m_providers[provider_environment] = provider_t(new environment_provider); } provider_dereferencer ::provider_dereferencer(config_t const conf) { m_providers[provider_config] = provider_t(new config_provider(conf)); } provider_dereferencer ::~provider_dereferencer() { } pipe_bakery::config_reference_t provider_dereferencer ::operator () (config::value_t const& value) const { return value; } pipe_bakery::config_reference_t provider_dereferencer ::operator () (pipe_bakery::provider_request_t const& request) const { provider_map_t::const_iterator const i = m_providers.find(request.first); if (i == m_providers.end()) { return request; } return (*i->second)(request.second); } config::value_t ensure_provided ::operator () (config::value_t const& value) const { return value; } config::value_t ensure_provided ::operator () (pipe_bakery::provider_request_t const& /*request*/) const { /// \todo Throw an exception. return config::value_t(); } } <commit_msg>Add a sorter for configuration provider requests<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "load_pipe.h" #include "pipe_declaration_types.h" #include "providers.h" #include <vistk/pipeline/config.h> #include <vistk/pipeline/process.h> #include <boost/algorithm/string/join.hpp> #include <boost/graph/directed_graph.hpp> #include <boost/graph/topological_sort.hpp> #include <boost/tuple/tuple.hpp> #include <boost/foreach.hpp> #include <boost/variant.hpp> #include <algorithm> #include <utility> #include <vector> /** * \file pipe_bakery.cxx * * \brief Implementation of baking a pipeline. */ namespace vistk { namespace { static config_flag_t const flag_read_only = config_flag_t("ro"); static config_provider_t const provider_config = config_provider_t("CONF"); static config_provider_t const provider_environment = config_provider_t("ENV"); static config_provider_t const provider_system = config_provider_t("SYS"); } class VISTK_PIPELINE_UTIL_NO_EXPORT pipe_bakery : public boost::static_visitor<> { public: pipe_bakery(); ~pipe_bakery(); void operator () (config_pipe_block const& config_block); void operator () (process_pipe_block const& process_block); void operator () (connect_pipe_block const& connect_block); void operator () (group_pipe_block const& group_block); /** * \note We do *not* want std::map for the groupings. With a map, we may * hide errors in the blocks (setting ro values, duplicate process names, * etc.) */ typedef std::pair<config_provider_t, config::value_t> provider_request_t; typedef boost::variant<config::value_t, provider_request_t> config_reference_t; typedef boost::tuple<config_reference_t, bool> config_info_t; typedef std::pair<config::key_t, config_info_t> config_decl_t; typedef std::vector<config_decl_t> config_decls_t; typedef std::pair<process::name_t, process_registry::type_t> process_decl_t; typedef std::vector<process_decl_t> process_decls_t; typedef std::pair<process::port_addr_t, process::port_addr_t> connection_t; typedef std::vector<connection_t> connections_t; typedef boost::tuple<process::port_t, process::port_flags_t, process::port_addr_t> mapping_t; typedef std::vector<mapping_t> mappings_t; typedef std::pair<mappings_t, mappings_t> group_info_t; typedef std::pair<process::name_t, group_info_t> group_decl_t; typedef std::vector<group_decl_t> group_decls_t; static config::key_t flatten_keys(config::keys_t const& keys); void register_config_value(config::key_t const& root_key, config_value_t const& value); config_decls_t m_configs; process_decls_t m_processes; connections_t m_connections; group_decls_t m_groups; }; class VISTK_PIPELINE_UTIL_NO_EXPORT provider_dereferencer : public boost::static_visitor<pipe_bakery::config_reference_t> { public: provider_dereferencer(); provider_dereferencer(config_t const conf); ~provider_dereferencer(); pipe_bakery::config_reference_t operator () (config::value_t const& value) const; pipe_bakery::config_reference_t operator () (pipe_bakery::provider_request_t const& request) const; private: typedef std::map<config_provider_t, provider_t> provider_map_t; provider_map_t m_providers; }; class VISTK_PIPELINE_UTIL_NO_EXPORT ensure_provided : public boost::static_visitor<config::value_t> { public: config::value_t operator () (config::value_t const& value) const; config::value_t operator () (pipe_bakery::provider_request_t const& request) const; }; class VISTK_PIPELINE_UTIL_NO_EXPORT config_provider_sorter : public boost::static_visitor<> { public: void operator () (config::key_t const& key, config::value_t const& value) const; void operator () (config::key_t const& key, pipe_bakery::provider_request_t const& request); config::keys_t sorted() const; private: struct vertex_name_t { typedef boost::vertex_property_tag kind; }; typedef boost::property<vertex_name_t, config::key_t> name_property_t; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, name_property_t> config_graph_t; typedef boost::graph_traits<config_graph_t>::vertex_descriptor vertex_t; typedef std::vector<vertex_t> vertices_t; typedef std::map<config::key_t, vertex_t> vertex_map_t; vertex_map_t m_vertex_map; config_graph_t m_graph; }; pipeline_t bake_pipe_blocks(pipe_blocks const& blocks) { pipeline_t pipeline; pipe_bakery bakery; std::for_each(blocks.begin(), blocks.end(), boost::apply_visitor(bakery)); // Build configuration. { // Dereference (non-configuration) providers. { BOOST_FOREACH (pipe_bakery::config_decl_t& decl, bakery.m_configs) { pipe_bakery::config_reference_t& ref = decl.second.get<0>(); ref = boost::apply_visitor(provider_dereferencer(), ref); } } config_t conf = config::empty_config(); BOOST_FOREACH (pipe_bakery::config_decl_t& decl, bakery.m_configs) { pipe_bakery::config_reference_t const& ref = decl.second.get<0>(); config::key_t const key = decl.first; config::value_t val; // Only add provided configurations to the configuration. try { val = boost::apply_visitor(ensure_provided(), ref); } catch (...) { continue; } conf->set_value(key, val); } // Dereference configuration providers. { /// \todo Sort requests so circular requests don't occur. /// \todo Find config provider requests. config::keys_t keys; provider_dereferencer deref(conf); /// \todo This is algorithmically naive, but I'm not sure if there's a faster way. BOOST_FOREACH (config::key_t const& key, keys) { BOOST_FOREACH (pipe_bakery::config_decl_t& decl, bakery.m_configs) { config::key_t const& cur_key = decl.first; if (key != cur_key) { continue; } pipe_bakery::config_reference_t& ref = decl.second.get<0>(); ref = boost::apply_visitor(deref, ref); config::value_t const val = boost::apply_visitor(ensure_provided(), ref); // Set the value in the intermediate configuration. conf->set_value(cur_key, val); } } } /// \todo Build final configuration. } /// \todo Bake pipe blocks into a pipeline. return pipeline; } pipe_bakery ::pipe_bakery() { } pipe_bakery ::~pipe_bakery() { } void pipe_bakery ::operator () (config_pipe_block const& config_block) { config::key_t const root_key = flatten_keys(config_block.key); config_values_t const& values = config_block.values; BOOST_FOREACH (config_value_t const& value, values) { register_config_value(root_key, value); } } void pipe_bakery ::operator () (process_pipe_block const& process_block) { config_values_t const& values = process_block.config_values; // Build the configuration value for the name of the process. config_value_t name_value; name_value.key.key_path.push_back(process::config_name); name_value.key.options.flags = config_flags_t(); (*name_value.key.options.flags).push_back(flag_read_only); name_value.value = process_block.name; register_config_value(process_block.name, name_value); BOOST_FOREACH (config_value_t const& value, values) { register_config_value(process_block.name, value); } m_processes.push_back(process_decl_t(process_block.name, process_block.type)); } void pipe_bakery ::operator () (connect_pipe_block const& connect_block) { m_connections.push_back(connection_t(connect_block.from, connect_block.to)); } void pipe_bakery ::operator () (group_pipe_block const& group_block) { config_values_t const& values = group_block.config_values; BOOST_FOREACH (config_value_t const& value, values) { register_config_value(group_block.name, value); } process::port_flags_t default_flags; mappings_t input_mappings; BOOST_FOREACH (input_map_t const& map, group_block.input_mappings) { process::port_flags_t flags = default_flags; if (map.options.flags) { flags = *map.options.flags; } mapping_t const mapping = mapping_t(map.from, flags, map.to); input_mappings.push_back(mapping); } mappings_t output_mappings; BOOST_FOREACH (output_map_t const& map, group_block.output_mappings) { process::port_flags_t flags = default_flags; if (map.options.flags) { flags = *map.options.flags; } mapping_t const mapping = mapping_t(map.to, flags, map.from); output_mappings.push_back(mapping); } group_info_t const info = group_info_t(input_mappings, output_mappings); group_decl_t const decl = group_decl_t(group_block.name, info); m_groups.push_back(decl); } void pipe_bakery ::register_config_value(config::key_t const& root_key, config_value_t const& value) { config_key_t const key = value.key; config::key_t const subkey = flatten_keys(key.key_path); config_reference_t c_value; if (key.options.provider) { c_value = provider_request_t(*key.options.provider, value.value); } else { c_value = value.value; } bool is_readonly = false; if (key.options.flags) { BOOST_FOREACH (config_flag_t const& flag, *key.options.flags) { if (flag == flag_read_only) { is_readonly = true; } else { /// \todo Log warning about unrecognized flag. } } } config::key_t const full_key = root_key + config::block_sep + subkey; config_info_t const info = config_info_t(c_value, is_readonly); config_decl_t const decl = config_decl_t(full_key, info); m_configs.push_back(decl); } config::key_t pipe_bakery ::flatten_keys(config::keys_t const& keys) { return boost::join(keys, config::block_sep); } provider_dereferencer ::provider_dereferencer() { m_providers[provider_system] = provider_t(new system_provider); m_providers[provider_environment] = provider_t(new environment_provider); } provider_dereferencer ::provider_dereferencer(config_t const conf) { m_providers[provider_config] = provider_t(new config_provider(conf)); } provider_dereferencer ::~provider_dereferencer() { } pipe_bakery::config_reference_t provider_dereferencer ::operator () (config::value_t const& value) const { return value; } pipe_bakery::config_reference_t provider_dereferencer ::operator () (pipe_bakery::provider_request_t const& request) const { provider_map_t::const_iterator const i = m_providers.find(request.first); if (i == m_providers.end()) { return request; } return (*i->second)(request.second); } config::value_t ensure_provided ::operator () (config::value_t const& value) const { return value; } config::value_t ensure_provided ::operator () (pipe_bakery::provider_request_t const& /*request*/) const { /// \todo Throw an exception. return config::value_t(); } config::keys_t config_provider_sorter ::sorted() const { vertices_t vertices; try { boost::topological_sort(m_graph, std::back_inserter(vertices)); } catch (boost::not_a_dag& e) { /// \todo Throw circular configuration provider exception. } config::keys_t keys; boost::property_map<config_graph_t, vertex_name_t>::const_type const key_prop = boost::get(vertex_name_t(), m_graph); BOOST_FOREACH (vertex_t const& vertex, vertices) { keys.push_back(boost::get(key_prop, vertex)); } return keys; } void config_provider_sorter ::operator () (config::key_t const& /*key*/, config::value_t const& /*value*/) const { } void config_provider_sorter ::operator () (config::key_t const& key, pipe_bakery::provider_request_t const& request) { if (request.first != provider_config) { return; } boost::property_map<config_graph_t, vertex_name_t>::type key_prop = boost::get(vertex_name_t(), m_graph); typedef std::pair<vertex_map_t::iterator, bool> insertion_t; insertion_t from_iter = m_vertex_map.insert(std::make_pair(key, vertex_t())); insertion_t to_iter = m_vertex_map.insert(std::make_pair(request.second, vertex_t())); vertex_t s; vertex_t t; if (from_iter.second) { s = boost::add_vertex(m_graph); key_prop[s] = key; from_iter.first->second = s; } s = from_iter.first->second; if (to_iter.second) { t = boost::add_vertex(m_graph); key_prop[s] = request.second; to_iter.first->second = t; } t = to_iter.first->second; boost::add_edge(s, t, m_graph); } } <|endoftext|>
<commit_before>/*- * Copyright (c) 2012, Achilleas Margaritis * Copyright (c) 2014, David T. Chisnall * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef PEGMATITE_AST_HPP #define PEGMATITE_AST_HPP #include <cassert> #include <list> #include <unordered_map> #include <memory> #include "parser.hh" namespace pegmatite { class ASTNode; template <class T, bool OPT> class ASTPtr; template <class T> class ASTList; template <class T> class BindAST; /** type of AST node stack. */ typedef std::vector<std::unique_ptr<ASTNode>> ASTStack; #ifdef USE_RTTI #define PEGMATITE_RTTI(thisclass, superclass) #else /** * Define the methods required for pegmatite's lightweight RTTI replacement to * work. This should be used at the end of the class definition and will * provide support for safe downcasting. */ #define PEGMATITE_RTTI(thisclass, superclass) \ friend ASTNode; \ protected: \ static char *classKind() \ { \ static char thisclass ## id; \ return &thisclass ## id; \ } \ public: \ virtual bool isa(char *x) \ { \ return (x == classKind()) || \ (superclass::isa(x)); \ } #endif /** * Base class for AST nodes. */ class ASTNode { public: /** * Constructs the AST node, with a null parent. */ ASTNode() : parent_node(0) {} /** * Copying AST nodes is not supported. */ ASTNode(const ASTNode&) = delete; /** * Destructor does nothing, virtual for subclasses to use. */ virtual ~ASTNode() {} /** * Returns the parent of this AST node, or `nullptr` if there isn't one * (either if this is the root, or if it is still in the stack waiting to * be added to the tree). */ ASTNode *parent() const { return parent_node; } /** * Interface for constructing the AST node. The input range `r` is the * range within the source. */ virtual void construct(const InputRange &r, ASTStack &st) {} private: /** * The parent AST node. */ ASTNode *parent_node; template <class T, bool OPT> friend class ASTPtr; template <class T> friend class ASTList; template <class T> friend class BindAST; #ifndef USE_RTTI protected: /** * Returns the kind of object class. This is a unique pointer that can be * tested against pointers returned by classKind() to determine whether * they can be safely compared. */ virtual char *kind() { return classKind(); } /** * Returns the unique identifier for this class. */ static char *classKind() { static char ASTNodeid; return &ASTNodeid; } public: /** * Root implementation of the RTTI-replacement for builds not wishing to * use RTTI. This returns true if `x` is the value returned from * `classKind()`, or false otherwise. */ virtual bool isa(char *x) { return x == classKind(); } /** * Returns true if this object is an instance of `T`. Note that this * *only* works with single-inheritance hierarchies. If you wish to use * multiple inheritance in your AST classes, then you must define * `USE_RTTI` and use the C++ RTTI mechanism. */ template <class T> bool isa() { return isa(T::classKind()); } /** * Returns a pointer to this object as a pointer to a child class, or * `nullptr` if the cast would be unsafe. * * Note that AST nodes are intended to be always used as unique pointers * and so the returned object is *only* valid as long as the unique pointer * is valid. */ template <class T> T* get_as() { return this ? (isa<T>() ? static_cast<T*>(this) : nullptr) : nullptr; } #else public: template <class T> T* get_as() { return dynamic_cast<T*>(this); } #endif }; class ASTMember; /** type of ast member vector. */ /** * The base class for non-leaf AST nodes. Subclasses can have instances of * `ASTMember` subclasses as fields and will automatically construct them. */ class ASTContainer : public ASTNode { public: /** * Constructs the container, setting a thread-local value to point to it * allowing constructors in fields of the subclass to register themselves * in the members vector. */ ASTContainer(); /** * Asks all members to construct themselves from the stack. The members are * asked to construct themselves in reverse order from a node stack (`st`). * * The input range (`r`) is unused, because the leaf nodes have already * constructed themselves at this point. */ virtual void construct(const InputRange &r, ASTStack &st); private: /** * The type used for tracking the fields of subclasses. */ typedef std::vector<ASTMember *> ASTMember_vector; /** * References to all of the fields of the subclass that will be * automatically constructed. */ ASTMember_vector members; friend class ASTMember; PEGMATITE_RTTI(ASTContainer, ASTNode) }; /** * Base class for children of `ASTContainer`. */ class ASTMember { public: /** * On construction, `ASTMember` sets its `container_node` field to the * `ASTContainer` currently under construction and registers itself with * the container, to be notified during the construction phase. */ ASTMember(); /** * Returns the container of which this object is a field. */ ASTContainer *container() const { return container_node; } /** * Interface for constructing references to AST objects from the stack. */ virtual void construct(ASTStack &st) = 0; virtual ~ASTMember(); protected: /** * The container that owns this object. */ ASTContainer *container_node; }; /** * An `ASTPtr` is a wrapper around a pointer to an AST object. It is intended * to be a member of an `ASTContainer` and will automatically pop the top item * from the stack and claim it when building the AST.. */ template <class T, bool OPT = false> class ASTPtr : public ASTMember { public: /** * Constructs the object in the */ ASTPtr() : ptr(nullptr) {} /** gets the underlying ptr value. @return the underlying ptr value. */ T *get() const { return ptr.get(); } /** auto conversion to the underlying object ptr. @return the underlying ptr value. */ const std::unique_ptr<T> &operator *() const { return ptr; } /** member access. @return the underlying ptr value. */ const std::unique_ptr<T> &operator ->() const { assert(ptr); return ptr; } explicit operator bool() const noexcept { return (bool)ptr; } /** * Pops the next matching object from the AST stack `st` and claims it. */ virtual void construct(ASTStack &st) { if (st.empty() && OPT) { return; } assert(!st.empty() && "Stack must not be empty"); //get the node ASTNode *node = st.back().get(); //get the object T *obj = node->get_as<T>(); assert((obj || OPT) && "Required objects must exist!"); //if the object is optional, simply return if (OPT && !obj) { return; } //set the new object ptr.reset(obj); //pop the node from the stack st.back().release(); st.pop_back(); ptr->parent_node = container_node; } private: /** * The node that we are pointing to. */ std::unique_ptr<T> ptr; }; /** A list of objects. It pops objects of the given type from the ast stack, until no more objects can be popped. It assumes ownership of objects. @param T type of object to control. */ template <class T> class ASTList : public ASTMember { public: ///list type. typedef std::list<std::unique_ptr<T>> container; ///the default constructor. ASTList() {} /** duplicates the objects of the given list. @param src source object. */ ASTList(const ASTList<T> &src) { _dup(src); } /** returns the container of objects. @return the container of objects. */ const container &objects() const { return child_objects; } /** * Pops objects of type T from the stack (`st`) until no more objects can * be popped. */ virtual void construct(ASTStack &st) { for(;;) { //if the stack is empty if (st.empty()) break; //get the node ASTNode *node = st.back().get(); //get the object T *obj = node->get_as<T>(); //if the object was not not of the appropriate type, //end the list parsing if (!obj) return; //remove the node from the stack st.back().release(); st.pop_back(); //insert the object in the list, in reverse order child_objects.push_front(std::unique_ptr<T>(obj)); //set the object's parent obj->parent_node = ASTMember::container(); } } virtual ~ASTList() {} private: //objects container child_objects; //duplicate the given list. void _dup(const ASTList<T> &src) { for (auto child : src.child_objects) { T *obj = new T(child.get()); child_objects.push_back(obj); obj->parent_node = ASTMember::container(); } } }; /** parses the given input. @param i input. @param g root rule of grammar. @param ws whitespace rule. @param el list of errors. @param d user data, passed to the parse procedures. @return pointer to ast node created, or null if there was an error. The return object must be deleted by the caller. */ std::unique_ptr<ASTNode> parse(Input &i, const Rule &g, const Rule &ws, ErrorList &el, const ParserDelegate &d); /** * A parser delegate that is responsible for creating AST nodes from the input. * * This class manages a mapping from rules in some grammar to AST nodes. * Instances of the `BindAST` class that are fields of a subclass of this will * automatically register rules on creation. * * The recommended use for this class is to only register rules on construction * (either explicitly in the constructor or implicitly via `BindAST` members). * This will give a completely reentrant delegate, which can be used by * multiple threads to parse multiple inputs safely. */ class ASTParserDelegate : ParserDelegate { /** * BindAST is a friend so that it can call the `set_parse_proc()` function, * which should never be called from anything else. */ template <class T> friend class BindAST; private: /** * The map from rules to parsing handlers. */ std::unordered_map<const Rule*, parse_proc> handlers; /** * Registers a callback in this delegate. This should only be called from * the `static` version of this function. */ void set_parse_proc(const Rule &r, parse_proc p); /** * Registers a callback for a specific rule in the instance of this class * currently under construction in this thread. This should only ever be * called by `BindAST` instances. */ static void bind_parse_proc(const Rule &r, parse_proc p); public: /** * Default constructor, registers this class in thread-local storage so * that it can be referenced by BindAST fields in subclasses when their * constructors are run. */ ASTParserDelegate(); virtual parse_proc get_parse_proc(const Rule &) const; /** * Parse an input `i`, starting from rule `g` in the grammar for which * this is a delegate. The rule `ws` is used as whitespace. Errors are * returned via the `el` parameter and the root of the AST via the `ast` * parameter. * * This function returns true on a successful parse, or false otherwise. */ template <class T> bool parse(Input &i, const Rule &g, const Rule &ws, ErrorList &el, std::unique_ptr<T> &ast) const { std::unique_ptr<ASTNode> node = pegmatite::parse(i, g, ws, el, *this); T *n = node->get_as<T>(); if (n) { node.release(); ast.reset(n); return true; } return false; } }; /** * The `BindAST` class is responsible for binding an action to a rule. The * template argument is the `ASTNode` subclass representing the action. Its * `construct()` method will be called when the rule is matched. */ template <class T> class BindAST { public: /** * Bind the AST class described in the grammar to the rule specified. */ BindAST(const Rule &r) { ASTParserDelegate::bind_parse_proc(r, [](const ParserPosition &b, const ParserPosition &e, void *d) { ASTStack *st = reinterpret_cast<ASTStack *>(d); T *obj = new T(); obj->construct(InputRange(b, e), *st); st->push_back(std::unique_ptr<ASTNode>(obj)); }); } }; } //namespace pegmatite #endif //PEGMATITE_AST_HPP <commit_msg>Add debug logging for AST building operations.<commit_after>/*- * Copyright (c) 2012, Achilleas Margaritis * Copyright (c) 2014, David T. Chisnall * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef PEGMATITE_AST_HPP #define PEGMATITE_AST_HPP #include <cassert> #include <list> #include <unordered_map> #include <memory> #include <cxxabi.h> #include "parser.hh" namespace pegmatite { template <class T> void debug_log(const char *msg, int depth, T *obj) { #ifdef DEBUG_AST_CONSTRUCTION const char *mangled = typeid(T).name(); char *buffer = (char*)malloc(strlen(mangled)); int err; size_t s; char *demangled = abi::__cxa_demangle(mangled, buffer, &s, &err); fprintf(stderr, "[%d] %s %s (%p) off the AST stack\n", depth, msg, demangled ? demangled : mangled, obj); free((void*)(demangled ? demangled : buffer)); #endif // DEBUG_AST_CONSTRUCTION } class ASTNode; template <class T, bool OPT> class ASTPtr; template <class T> class ASTList; template <class T> class BindAST; /** type of AST node stack. */ typedef std::vector<std::unique_ptr<ASTNode>> ASTStack; #ifdef USE_RTTI #define PEGMATITE_RTTI(thisclass, superclass) #else /** * Define the methods required for pegmatite's lightweight RTTI replacement to * work. This should be used at the end of the class definition and will * provide support for safe downcasting. */ #define PEGMATITE_RTTI(thisclass, superclass) \ friend ASTNode; \ protected: \ static char *classKind() \ { \ static char thisclass ## id; \ return &thisclass ## id; \ } \ public: \ virtual bool isa(char *x) \ { \ return (x == classKind()) || \ (superclass::isa(x)); \ } #endif /** * Base class for AST nodes. */ class ASTNode { public: /** * Constructs the AST node, with a null parent. */ ASTNode() : parent_node(0) {} /** * Copying AST nodes is not supported. */ ASTNode(const ASTNode&) = delete; /** * Destructor does nothing, virtual for subclasses to use. */ virtual ~ASTNode() {} /** * Returns the parent of this AST node, or `nullptr` if there isn't one * (either if this is the root, or if it is still in the stack waiting to * be added to the tree). */ ASTNode *parent() const { return parent_node; } /** * Interface for constructing the AST node. The input range `r` is the * range within the source. */ virtual void construct(const InputRange &r, ASTStack &st) {} private: /** * The parent AST node. */ ASTNode *parent_node; template <class T, bool OPT> friend class ASTPtr; template <class T> friend class ASTList; template <class T> friend class BindAST; #ifndef USE_RTTI protected: /** * Returns the kind of object class. This is a unique pointer that can be * tested against pointers returned by classKind() to determine whether * they can be safely compared. */ virtual char *kind() { return classKind(); } /** * Returns the unique identifier for this class. */ static char *classKind() { static char ASTNodeid; return &ASTNodeid; } public: /** * Root implementation of the RTTI-replacement for builds not wishing to * use RTTI. This returns true if `x` is the value returned from * `classKind()`, or false otherwise. */ virtual bool isa(char *x) { return x == classKind(); } /** * Returns true if this object is an instance of `T`. Note that this * *only* works with single-inheritance hierarchies. If you wish to use * multiple inheritance in your AST classes, then you must define * `USE_RTTI` and use the C++ RTTI mechanism. */ template <class T> bool isa() { return isa(T::classKind()); } /** * Returns a pointer to this object as a pointer to a child class, or * `nullptr` if the cast would be unsafe. * * Note that AST nodes are intended to be always used as unique pointers * and so the returned object is *only* valid as long as the unique pointer * is valid. */ template <class T> T* get_as() { return this ? (isa<T>() ? static_cast<T*>(this) : nullptr) : nullptr; } #else public: template <class T> T* get_as() { return dynamic_cast<T*>(this); } #endif }; class ASTMember; /** type of ast member vector. */ /** * The base class for non-leaf AST nodes. Subclasses can have instances of * `ASTMember` subclasses as fields and will automatically construct them. */ class ASTContainer : public ASTNode { public: /** * Constructs the container, setting a thread-local value to point to it * allowing constructors in fields of the subclass to register themselves * in the members vector. */ ASTContainer(); /** * Asks all members to construct themselves from the stack. The members are * asked to construct themselves in reverse order from a node stack (`st`). * * The input range (`r`) is unused, because the leaf nodes have already * constructed themselves at this point. */ virtual void construct(const InputRange &r, ASTStack &st); private: /** * The type used for tracking the fields of subclasses. */ typedef std::vector<ASTMember *> ASTMember_vector; /** * References to all of the fields of the subclass that will be * automatically constructed. */ ASTMember_vector members; friend class ASTMember; PEGMATITE_RTTI(ASTContainer, ASTNode) }; /** * Base class for children of `ASTContainer`. */ class ASTMember { public: /** * On construction, `ASTMember` sets its `container_node` field to the * `ASTContainer` currently under construction and registers itself with * the container, to be notified during the construction phase. */ ASTMember(); /** * Returns the container of which this object is a field. */ ASTContainer *container() const { return container_node; } /** * Interface for constructing references to AST objects from the stack. */ virtual void construct(ASTStack &st) = 0; virtual ~ASTMember(); protected: /** * The container that owns this object. */ ASTContainer *container_node; }; /** * An `ASTPtr` is a wrapper around a pointer to an AST object. It is intended * to be a member of an `ASTContainer` and will automatically pop the top item * from the stack and claim it when building the AST.. */ template <class T, bool OPT = false> class ASTPtr : public ASTMember { public: /** * Constructs the object in the */ ASTPtr() : ptr(nullptr) {} /** gets the underlying ptr value. @return the underlying ptr value. */ T *get() const { return ptr.get(); } /** auto conversion to the underlying object ptr. @return the underlying ptr value. */ const std::unique_ptr<T> &operator *() const { return ptr; } /** member access. @return the underlying ptr value. */ const std::unique_ptr<T> &operator ->() const { assert(ptr); return ptr; } explicit operator bool() const noexcept { return (bool)ptr; } /** * Pops the next matching object from the AST stack `st` and claims it. */ virtual void construct(ASTStack &st) { if (st.empty() && OPT) { return; } assert(!st.empty() && "Stack must not be empty"); //get the node ASTNode *node = st.back().get(); //get the object T *obj = node->get_as<T>(); assert((obj || OPT) && "Required objects must exist!"); //if the object is optional, simply return if (OPT && !obj) { return; } debug_log("Popped", st.size()-1, obj); //set the new object ptr.reset(obj); //pop the node from the stack st.back().release(); st.pop_back(); ptr->parent_node = container_node; } private: /** * The node that we are pointing to. */ std::unique_ptr<T> ptr; }; /** A list of objects. It pops objects of the given type from the ast stack, until no more objects can be popped. It assumes ownership of objects. @param T type of object to control. */ template <class T> class ASTList : public ASTMember { public: ///list type. typedef std::list<std::unique_ptr<T>> container; ///the default constructor. ASTList() {} /** duplicates the objects of the given list. @param src source object. */ ASTList(const ASTList<T> &src) { _dup(src); } /** returns the container of objects. @return the container of objects. */ const container &objects() const { return child_objects; } /** * Pops objects of type T from the stack (`st`) until no more objects can * be popped. */ virtual void construct(ASTStack &st) { for(;;) { //if the stack is empty if (st.empty()) break; //get the node ASTNode *node = st.back().get(); //get the object T *obj = node->get_as<T>(); //if the object was not not of the appropriate type, //end the list parsing if (!obj) return; debug_log("Popped", st.size()-1, obj); //remove the node from the stack st.back().release(); st.pop_back(); //insert the object in the list, in reverse order child_objects.push_front(std::unique_ptr<T>(obj)); //set the object's parent obj->parent_node = ASTMember::container(); } } virtual ~ASTList() {} private: //objects container child_objects; //duplicate the given list. void _dup(const ASTList<T> &src) { for (auto child : src.child_objects) { T *obj = new T(child.get()); child_objects.push_back(obj); obj->parent_node = ASTMember::container(); } } }; /** parses the given input. @param i input. @param g root rule of grammar. @param ws whitespace rule. @param el list of errors. @param d user data, passed to the parse procedures. @return pointer to ast node created, or null if there was an error. The return object must be deleted by the caller. */ std::unique_ptr<ASTNode> parse(Input &i, const Rule &g, const Rule &ws, ErrorList &el, const ParserDelegate &d); /** * A parser delegate that is responsible for creating AST nodes from the input. * * This class manages a mapping from rules in some grammar to AST nodes. * Instances of the `BindAST` class that are fields of a subclass of this will * automatically register rules on creation. * * The recommended use for this class is to only register rules on construction * (either explicitly in the constructor or implicitly via `BindAST` members). * This will give a completely reentrant delegate, which can be used by * multiple threads to parse multiple inputs safely. */ class ASTParserDelegate : ParserDelegate { /** * BindAST is a friend so that it can call the `set_parse_proc()` function, * which should never be called from anything else. */ template <class T> friend class BindAST; private: /** * The map from rules to parsing handlers. */ std::unordered_map<const Rule*, parse_proc> handlers; /** * Registers a callback in this delegate. This should only be called from * the `static` version of this function. */ void set_parse_proc(const Rule &r, parse_proc p); /** * Registers a callback for a specific rule in the instance of this class * currently under construction in this thread. This should only ever be * called by `BindAST` instances. */ static void bind_parse_proc(const Rule &r, parse_proc p); public: /** * Default constructor, registers this class in thread-local storage so * that it can be referenced by BindAST fields in subclasses when their * constructors are run. */ ASTParserDelegate(); virtual parse_proc get_parse_proc(const Rule &) const; /** * Parse an input `i`, starting from rule `g` in the grammar for which * this is a delegate. The rule `ws` is used as whitespace. Errors are * returned via the `el` parameter and the root of the AST via the `ast` * parameter. * * This function returns true on a successful parse, or false otherwise. */ template <class T> bool parse(Input &i, const Rule &g, const Rule &ws, ErrorList &el, std::unique_ptr<T> &ast) const { std::unique_ptr<ASTNode> node = pegmatite::parse(i, g, ws, el, *this); T *n = node->get_as<T>(); if (n) { node.release(); ast.reset(n); return true; } return false; } }; /** * The `BindAST` class is responsible for binding an action to a rule. The * template argument is the `ASTNode` subclass representing the action. Its * `construct()` method will be called when the rule is matched. */ template <class T> class BindAST { public: /** * Bind the AST class described in the grammar to the rule specified. */ BindAST(const Rule &r) { ASTParserDelegate::bind_parse_proc(r, [](const ParserPosition &b, const ParserPosition &e, void *d) { ASTStack *st = reinterpret_cast<ASTStack *>(d); T *obj = new T(); obj->construct(InputRange(b, e), *st); st->push_back(std::unique_ptr<ASTNode>(obj)); debug_log("Constructed", st->size()-1, obj); }); } }; } //namespace pegmatite #endif //PEGMATITE_AST_HPP <|endoftext|>
<commit_before>/* * Copyright (C) 2019 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "leveled_compaction_strategy.hh" #include <algorithm> namespace sstables { compaction_descriptor leveled_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) { // NOTE: leveled_manifest creation may be slightly expensive, so later on, // we may want to store it in the strategy itself. However, the sstable // lists managed by the manifest may become outdated. For example, one // sstable in it may be marked for deletion after compacted. // Currently, we create a new manifest whenever it's time for compaction. leveled_manifest manifest = leveled_manifest::create(cfs, candidates, _max_sstable_size_in_mb, _stcs_options); if (!_last_compacted_keys) { generate_last_compacted_keys(manifest); } auto candidate = manifest.get_compaction_candidates(*_last_compacted_keys, _compaction_counter); if (!candidate.sstables.empty()) { leveled_manifest::logger.debug("leveled: Compacting {} out of {} sstables", candidate.sstables.size(), cfs.get_sstables()->size()); return candidate; } // if there is no sstable to compact in standard way, try compacting based on droppable tombstone ratio // unlike stcs, lcs can look for sstable with highest droppable tombstone ratio, so as not to choose // a sstable which droppable data shadow data in older sstable, by starting from highest levels which // theoretically contain oldest non-overlapping data. auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds(); for (auto level = int(manifest.get_level_count()); level >= 0; level--) { auto& sstables = manifest.get_level(level); // filter out sstables which droppable tombstone ratio isn't greater than the defined threshold. auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool { return !worth_dropping_tombstones(sst, gc_before); }); sstables.erase(e, sstables.end()); if (sstables.empty()) { continue; } auto& sst = *std::max_element(sstables.begin(), sstables.end(), [&] (auto& i, auto& j) { return i->estimate_droppable_tombstone_ratio(gc_before) < j->estimate_droppable_tombstone_ratio(gc_before); }); return sstables::compaction_descriptor({ sst }, cfs.get_sstable_set(), service::get_local_compaction_priority(), sst->get_sstable_level()); } return {}; } compaction_descriptor leveled_compaction_strategy::get_major_compaction_job(column_family& cf, std::vector<sstables::shared_sstable> candidates) { if (candidates.empty()) { return compaction_descriptor(); } auto& sst = *std::max_element(candidates.begin(), candidates.end(), [&] (sstables::shared_sstable& sst1, sstables::shared_sstable& sst2) { return sst1->get_sstable_level() < sst2->get_sstable_level(); }); return compaction_descriptor(std::move(candidates), cf.get_sstable_set(), service::get_local_compaction_priority(), sst->get_sstable_level(), _max_sstable_size_in_mb*1024*1024); } void leveled_compaction_strategy::notify_completion(const std::vector<shared_sstable>& removed, const std::vector<shared_sstable>& added) { if (removed.empty() || added.empty()) { return; } auto min_level = std::numeric_limits<uint32_t>::max(); for (auto& sstable : removed) { min_level = std::min(min_level, sstable->get_sstable_level()); } const sstables::sstable *last = nullptr; int target_level = 0; for (auto& candidate : added) { if (!last || last->compare_by_first_key(*candidate) < 0) { last = &*candidate; } target_level = std::max(target_level, int(candidate->get_sstable_level())); } _last_compacted_keys.value().at(min_level) = last->get_last_decorated_key(); for (int i = leveled_manifest::MAX_LEVELS - 1; i > 0; i--) { _compaction_counter[i]++; } _compaction_counter[target_level] = 0; if (leveled_manifest::logger.level() == logging::log_level::debug) { for (auto j = 0U; j < _compaction_counter.size(); j++) { leveled_manifest::logger.debug("CompactionCounter: {}: {}", j, _compaction_counter[j]); } } } void leveled_compaction_strategy::generate_last_compacted_keys(leveled_manifest& manifest) { std::vector<std::optional<dht::decorated_key>> last_compacted_keys(leveled_manifest::MAX_LEVELS); for (auto i = 0; i < leveled_manifest::MAX_LEVELS - 1; i++) { if (manifest.get_level(i + 1).empty()) { continue; } const sstables::sstable* sstable_with_last_compacted_key = nullptr; std::optional<db_clock::time_point> max_creation_time; for (auto& sst : manifest.get_level(i + 1)) { auto wtime = sst->data_file_write_time(); if (!max_creation_time || wtime >= *max_creation_time) { sstable_with_last_compacted_key = &*sst; max_creation_time = wtime; } } last_compacted_keys[i] = sstable_with_last_compacted_key->get_last_decorated_key(); } _last_compacted_keys = std::move(last_compacted_keys); } int64_t leveled_compaction_strategy::estimated_pending_compactions(column_family& cf) const { std::vector<sstables::shared_sstable> sstables; sstables.reserve(cf.sstables_count()); for (auto& entry : *cf.get_sstables()) { sstables.push_back(entry); } leveled_manifest manifest = leveled_manifest::create(cf, sstables, _max_sstable_size_in_mb, _stcs_options); return manifest.get_estimated_tasks(); } compaction_descriptor leveled_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode) { std::array<std::vector<shared_sstable>, leveled_manifest::MAX_LEVELS> level_info; auto is_disjoint = [this, schema] (const std::vector<shared_sstable>& sstables, unsigned tolerance) { unsigned disjoint_sstables = 0; auto prev_last = dht::ring_position::min(); for (auto& sst : sstables) { if (dht::ring_position(sst->get_first_decorated_key()).less_compare(*schema, prev_last)) { disjoint_sstables++; } prev_last = dht::ring_position(sst->get_last_decorated_key()); } return disjoint_sstables > tolerance; }; for (auto& sst : input) { auto sst_level = sst->get_sstable_level(); if (sst_level > leveled_manifest::MAX_LEVELS) { leveled_manifest::logger.warn("Found SSTable with level {}, higher than the maximum {}. This is unexpected, but will fix", sst_level, leveled_manifest::MAX_LEVELS); // This is really unexpected, so we'll just compact it all to fix it compaction_descriptor desc(std::move(input), std::optional<sstables::sstable_set>(), iop, leveled_manifest::MAX_LEVELS - 1, _max_sstable_size_in_mb * 1024 * 1024); desc.options = compaction_options::make_reshape(); return desc; } level_info[sst_level].push_back(sst); } for (auto& level : level_info) { std::sort(level.begin(), level.end(), [this, schema] (shared_sstable a, shared_sstable b) { return dht::ring_position(a->get_first_decorated_key()).less_compare(*schema, dht::ring_position(b->get_first_decorated_key())); }); } unsigned max_filled_level = 0; size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4); size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold)); unsigned tolerance = mode == reshape_mode::strict ? 0 : leveled_manifest::leveled_fan_out * 2; if (level_info[0].size() > offstrategy_threshold) { level_info[0].resize(std::min(level_info[0].size(), max_sstables)); compaction_descriptor desc(std::move(level_info[0]), std::optional<sstables::sstable_set>(), iop); desc.options = compaction_options::make_reshape(); return desc; } for (unsigned level = leveled_manifest::MAX_LEVELS - 1; level > 0; --level) { if (level_info[level].empty()) { continue; } max_filled_level = std::max(max_filled_level, level); if (!is_disjoint(level_info[level], tolerance)) { // Unfortunately no good limit to limit input size to max_sstables for LCS major compaction_descriptor desc(std::move(input), std::optional<sstables::sstable_set>(), iop, max_filled_level, _max_sstable_size_in_mb * 1024 * 1024); desc.options = compaction_options::make_reshape(); return desc; } } return compaction_descriptor(); } } <commit_msg>reshape: Fix reshaping procedure for LCS<commit_after>/* * Copyright (C) 2019 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "leveled_compaction_strategy.hh" #include <algorithm> namespace sstables { compaction_descriptor leveled_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) { // NOTE: leveled_manifest creation may be slightly expensive, so later on, // we may want to store it in the strategy itself. However, the sstable // lists managed by the manifest may become outdated. For example, one // sstable in it may be marked for deletion after compacted. // Currently, we create a new manifest whenever it's time for compaction. leveled_manifest manifest = leveled_manifest::create(cfs, candidates, _max_sstable_size_in_mb, _stcs_options); if (!_last_compacted_keys) { generate_last_compacted_keys(manifest); } auto candidate = manifest.get_compaction_candidates(*_last_compacted_keys, _compaction_counter); if (!candidate.sstables.empty()) { leveled_manifest::logger.debug("leveled: Compacting {} out of {} sstables", candidate.sstables.size(), cfs.get_sstables()->size()); return candidate; } // if there is no sstable to compact in standard way, try compacting based on droppable tombstone ratio // unlike stcs, lcs can look for sstable with highest droppable tombstone ratio, so as not to choose // a sstable which droppable data shadow data in older sstable, by starting from highest levels which // theoretically contain oldest non-overlapping data. auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds(); for (auto level = int(manifest.get_level_count()); level >= 0; level--) { auto& sstables = manifest.get_level(level); // filter out sstables which droppable tombstone ratio isn't greater than the defined threshold. auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool { return !worth_dropping_tombstones(sst, gc_before); }); sstables.erase(e, sstables.end()); if (sstables.empty()) { continue; } auto& sst = *std::max_element(sstables.begin(), sstables.end(), [&] (auto& i, auto& j) { return i->estimate_droppable_tombstone_ratio(gc_before) < j->estimate_droppable_tombstone_ratio(gc_before); }); return sstables::compaction_descriptor({ sst }, cfs.get_sstable_set(), service::get_local_compaction_priority(), sst->get_sstable_level()); } return {}; } compaction_descriptor leveled_compaction_strategy::get_major_compaction_job(column_family& cf, std::vector<sstables::shared_sstable> candidates) { if (candidates.empty()) { return compaction_descriptor(); } auto& sst = *std::max_element(candidates.begin(), candidates.end(), [&] (sstables::shared_sstable& sst1, sstables::shared_sstable& sst2) { return sst1->get_sstable_level() < sst2->get_sstable_level(); }); return compaction_descriptor(std::move(candidates), cf.get_sstable_set(), service::get_local_compaction_priority(), sst->get_sstable_level(), _max_sstable_size_in_mb*1024*1024); } void leveled_compaction_strategy::notify_completion(const std::vector<shared_sstable>& removed, const std::vector<shared_sstable>& added) { if (removed.empty() || added.empty()) { return; } auto min_level = std::numeric_limits<uint32_t>::max(); for (auto& sstable : removed) { min_level = std::min(min_level, sstable->get_sstable_level()); } const sstables::sstable *last = nullptr; int target_level = 0; for (auto& candidate : added) { if (!last || last->compare_by_first_key(*candidate) < 0) { last = &*candidate; } target_level = std::max(target_level, int(candidate->get_sstable_level())); } _last_compacted_keys.value().at(min_level) = last->get_last_decorated_key(); for (int i = leveled_manifest::MAX_LEVELS - 1; i > 0; i--) { _compaction_counter[i]++; } _compaction_counter[target_level] = 0; if (leveled_manifest::logger.level() == logging::log_level::debug) { for (auto j = 0U; j < _compaction_counter.size(); j++) { leveled_manifest::logger.debug("CompactionCounter: {}: {}", j, _compaction_counter[j]); } } } void leveled_compaction_strategy::generate_last_compacted_keys(leveled_manifest& manifest) { std::vector<std::optional<dht::decorated_key>> last_compacted_keys(leveled_manifest::MAX_LEVELS); for (auto i = 0; i < leveled_manifest::MAX_LEVELS - 1; i++) { if (manifest.get_level(i + 1).empty()) { continue; } const sstables::sstable* sstable_with_last_compacted_key = nullptr; std::optional<db_clock::time_point> max_creation_time; for (auto& sst : manifest.get_level(i + 1)) { auto wtime = sst->data_file_write_time(); if (!max_creation_time || wtime >= *max_creation_time) { sstable_with_last_compacted_key = &*sst; max_creation_time = wtime; } } last_compacted_keys[i] = sstable_with_last_compacted_key->get_last_decorated_key(); } _last_compacted_keys = std::move(last_compacted_keys); } int64_t leveled_compaction_strategy::estimated_pending_compactions(column_family& cf) const { std::vector<sstables::shared_sstable> sstables; sstables.reserve(cf.sstables_count()); for (auto& entry : *cf.get_sstables()) { sstables.push_back(entry); } leveled_manifest manifest = leveled_manifest::create(cf, sstables, _max_sstable_size_in_mb, _stcs_options); return manifest.get_estimated_tasks(); } compaction_descriptor leveled_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode) { std::array<std::vector<shared_sstable>, leveled_manifest::MAX_LEVELS> level_info; auto is_disjoint = [this, schema] (const std::vector<shared_sstable>& sstables, unsigned tolerance) { unsigned overlapping_sstables = 0; auto prev_last = dht::ring_position::min(); for (auto& sst : sstables) { if (dht::ring_position(sst->get_first_decorated_key()).less_compare(*schema, prev_last)) { overlapping_sstables++; } prev_last = dht::ring_position(sst->get_last_decorated_key()); } return overlapping_sstables <= tolerance; }; for (auto& sst : input) { auto sst_level = sst->get_sstable_level(); if (sst_level > leveled_manifest::MAX_LEVELS) { leveled_manifest::logger.warn("Found SSTable with level {}, higher than the maximum {}. This is unexpected, but will fix", sst_level, leveled_manifest::MAX_LEVELS); // This is really unexpected, so we'll just compact it all to fix it compaction_descriptor desc(std::move(input), std::optional<sstables::sstable_set>(), iop, leveled_manifest::MAX_LEVELS - 1, _max_sstable_size_in_mb * 1024 * 1024); desc.options = compaction_options::make_reshape(); return desc; } level_info[sst_level].push_back(sst); } for (auto& level : level_info) { std::sort(level.begin(), level.end(), [this, schema] (shared_sstable a, shared_sstable b) { return dht::ring_position(a->get_first_decorated_key()).less_compare(*schema, dht::ring_position(b->get_first_decorated_key())); }); } unsigned max_filled_level = 0; size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4); size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold)); unsigned tolerance = mode == reshape_mode::strict ? 0 : leveled_manifest::leveled_fan_out * 2; if (level_info[0].size() > offstrategy_threshold) { level_info[0].resize(std::min(level_info[0].size(), max_sstables)); compaction_descriptor desc(std::move(level_info[0]), std::optional<sstables::sstable_set>(), iop); desc.options = compaction_options::make_reshape(); return desc; } for (unsigned level = leveled_manifest::MAX_LEVELS - 1; level > 0; --level) { if (level_info[level].empty()) { continue; } max_filled_level = std::max(max_filled_level, level); if (!is_disjoint(level_info[level], tolerance)) { leveled_manifest::logger.warn("Turns out that level {} is not disjoint, so compacting everything on behalf of {}.{}", level, schema->ks_name(), schema->cf_name()); // Unfortunately no good limit to limit input size to max_sstables for LCS major compaction_descriptor desc(std::move(input), std::optional<sstables::sstable_set>(), iop, max_filled_level, _max_sstable_size_in_mb * 1024 * 1024); desc.options = compaction_options::make_reshape(); return desc; } } return compaction_descriptor(); } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_NORMAL_ID_GLM_LPDF_HPP #define STAN_MATH_OPENCL_NORMAL_ID_GLM_LPDF_HPP #ifdef STAN_OPENCL #include <stan/math/prim/meta.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/scal/fun/size_zero.hpp> #include <stan/math/prim/scal/fun/sum.hpp> #include <stan/math/prim/arr/fun/value_of_rec.hpp> #include <stan/math/prim/mat/prob/normal_id_glm_lpdf.hpp> #include <stan/math/opencl/kernels/normal_id_glm_lpdf.hpp> #include <stan/math/opencl/matrix_cl.hpp> #include <stan/math/opencl/multiply.hpp> #include <cmath> namespace stan { namespace math { /** * Returns the log PDF of the Generalized Linear Model (GLM) * with Normal distribution and id link function. * If containers are supplied, returns the log sum of the probabilities. * This is an overload of the GLM in prim/mar/prob/normal_id_glm_lpdf.hpp * that is implemented in OpenCL. * @tparam T_alpha type of the intercept(s); * this can be a vector (of the same length as y) of intercepts or a single * value (for models with constant intercept); * @tparam T_beta type of the weight vector; * this can also be a single value; * @tparam T_scale type of the (positive) scale(s); * this can be a vector (of the same length as y, for heteroskedasticity) * or a scalar. * @param y_cl vector parameter on OpenCL device * @param x_cl design matrix on OpenCL device * @param alpha intercept (in log odds) * @param beta weight vector * @param sigma (Sequence of) scale parameters for the normal * distribution. * @return log probability or log sum of probabilities * @throw std::domain_error if x, beta or alpha is infinite. * @throw std::domain_error if the scale is not positive. * @throw std::invalid_argument if container sizes mismatch. */ template <bool propto, typename T_alpha, typename T_beta, typename T_scale> return_type_t<T_alpha, T_beta, T_scale> normal_id_glm_lpdf( const matrix_cl<double> &y_cl, const matrix_cl<double> &x_cl, const T_alpha &alpha, const T_beta &beta, const T_scale &sigma) { static const char *function = "normal_id_glm_lpdf(OpenCL)"; using T_partials_return = partials_return_t<T_alpha, T_beta, T_scale>; using T_scale_val = typename std::conditional_t< is_vector<T_scale>::value, Eigen::Array<partials_return_t<T_scale>, -1, 1>, partials_return_t<T_scale>>; using Eigen::Array; using Eigen::Dynamic; using Eigen::Matrix; using Eigen::VectorXd; const size_t N = x_cl.rows(); const size_t M = x_cl.cols(); check_positive_finite(function, "Scale vector", sigma); check_size_match(function, "Rows of ", "x_cl", N, "rows of ", "y_cl", y_cl.rows()); check_consistent_size(function, "Weight vector", beta, M); if (is_vector<T_scale>::value) { check_size_match(function, "Rows of ", "y_cl", N, "size of ", "sigma", length(sigma)); } if (is_vector<T_alpha>::value) { check_size_match(function, "Rows of ", "y_cl", N, "size of ", "alpha", length(alpha)); } if (!include_summand<propto, T_alpha, T_beta, T_scale>::value) { return 0; } if (N == 0 || M == 0) { return 0; } const auto &beta_val = value_of_rec(beta); const auto &alpha_val = value_of_rec(alpha); const auto &sigma_val = value_of_rec(sigma); const auto &beta_val_vec = as_column_vector_or_scalar(beta_val); const auto &alpha_val_vec = as_column_vector_or_scalar(alpha_val); const auto &sigma_val_vec = as_column_vector_or_scalar(sigma_val); T_scale_val inv_sigma = 1 / as_array_or_scalar(sigma_val_vec); Matrix<T_partials_return, Dynamic, 1> y_minus_mu_over_sigma_mat(N); auto y_scaled = y_minus_mu_over_sigma_mat.array(); const int local_size = opencl_kernels::normal_id_glm.get_option("LOCAL_SIZE_"); const int wgs = (N + local_size - 1) / local_size; matrix_cl<double> beta_cl(beta_val_vec); matrix_cl<double> alpha_cl(alpha_val_vec); matrix_cl<double> sigma_cl(sigma_val_vec); const bool need_mu_derivative = !is_constant_all<T_beta, T_alpha>::value; matrix_cl<double> mu_derivative_cl(need_mu_derivative ? N : 0, 1); const bool need_mu_derivative_sum = !is_constant_all<T_alpha>::value && !is_vector<T_alpha>::value; matrix_cl<double> mu_derivative_sum_cl(need_mu_derivative_sum ? wgs : 0, 1); matrix_cl<double> y_minus_mu_over_sigma_squared_sum_cl(wgs, 1); const bool need_sigma_derivative = !is_constant_all<T_scale>::value && is_vector<T_scale>::value; matrix_cl<double> sigma_derivative_cl(need_sigma_derivative ? N : 0, 1); const bool need_log_sigma_sum = include_summand<propto, T_scale>::value && is_vector<T_scale>::value; matrix_cl<double> log_sigma_sum_cl(need_log_sigma_sum ? wgs : 0, 1); try { opencl_kernels::normal_id_glm( cl::NDRange(local_size * wgs), cl::NDRange(local_size), mu_derivative_cl, mu_derivative_sum_cl, y_minus_mu_over_sigma_squared_sum_cl, sigma_derivative_cl, log_sigma_sum_cl, y_cl, x_cl, alpha_cl, beta_cl, sigma_cl, N, M, length(alpha) != 1, length(sigma) != 1, need_mu_derivative, need_mu_derivative_sum, need_sigma_derivative, need_log_sigma_sum); } catch (const cl::Error &e) { check_opencl_error(function, e); } double y_scaled_sq_sum = sum(from_matrix_cl(y_minus_mu_over_sigma_squared_sum_cl)); operands_and_partials<T_alpha, T_beta, T_scale> ops_partials(alpha, beta, sigma); if (!is_constant_all<T_alpha>::value && is_vector<T_alpha>::value) { ops_partials.edge1_.partials_ = from_matrix_cl<Dynamic, 1>(mu_derivative_cl); } if (need_mu_derivative_sum) { ops_partials.edge1_.partials_[0] = sum(from_matrix_cl(mu_derivative_sum_cl)); } if (!is_constant_all<T_beta>::value) { const matrix_cl<double> mu_derivative_transpose_cl( mu_derivative_cl.buffer(), 1, mu_derivative_cl.rows()); // transposition of a vector can be done // without copying ops_partials.edge2_.partials_ = from_matrix_cl<1, Dynamic>(mu_derivative_transpose_cl * x_cl); } if (!is_constant_all<T_scale>::value) { if (is_vector<T_scale>::value) { ops_partials.edge3_.partials_ = from_matrix_cl<Dynamic, 1>(sigma_derivative_cl); } else { ops_partials.edge3_.partials_[0] = (y_scaled_sq_sum - N) * as_scalar(inv_sigma); } } if (!std::isfinite(y_scaled_sq_sum)) { check_finite(function, "Vector of dependent variables", from_matrix_cl(y_cl)); check_finite(function, "Weight vector", beta); check_finite(function, "Intercept", alpha); // if all other checks passed, next will only fail if x is not finite check_finite(function, "Matrix of independent variables", y_scaled_sq_sum); } // Compute log probability. T_partials_return logp(0.0); if (include_summand<propto>::value) { logp += NEG_LOG_SQRT_TWO_PI * N; } if (include_summand<propto, T_scale>::value) { if (is_vector<T_scale>::value) { logp -= sum(from_matrix_cl(log_sigma_sum_cl)); } else { logp -= N * log(as_scalar(sigma_val)); } } if (include_summand<propto, T_alpha, T_beta, T_scale>::value) { logp -= 0.5 * y_scaled_sq_sum; } return ops_partials.build(logp); } template <typename T_alpha, typename T_beta, typename T_scale> inline return_type_t<T_alpha, T_beta, T_scale> normal_id_glm_lpdf( const matrix_cl<double> &y, const matrix_cl<double> &x, const T_alpha &alpha, const T_beta &beta, const T_scale &sigma) { return normal_id_glm_lpdf<false>(y, x, alpha, beta, sigma); } } // namespace math } // namespace stan #endif #endif <commit_msg>fix header path<commit_after>#ifndef STAN_MATH_OPENCL_NORMAL_ID_GLM_LPDF_HPP #define STAN_MATH_OPENCL_NORMAL_ID_GLM_LPDF_HPP #ifdef STAN_OPENCL #include <stan/math/prim/meta.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/fun/constants.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/scal/fun/size_zero.hpp> #include <stan/math/prim/scal/fun/sum.hpp> #include <stan/math/prim/arr/fun/value_of_rec.hpp> #include <stan/math/prim/mat/prob/normal_id_glm_lpdf.hpp> #include <stan/math/opencl/kernels/normal_id_glm_lpdf.hpp> #include <stan/math/opencl/matrix_cl.hpp> #include <stan/math/opencl/prim/multiply.hpp> #include <cmath> namespace stan { namespace math { /** * Returns the log PDF of the Generalized Linear Model (GLM) * with Normal distribution and id link function. * If containers are supplied, returns the log sum of the probabilities. * This is an overload of the GLM in prim/mar/prob/normal_id_glm_lpdf.hpp * that is implemented in OpenCL. * @tparam T_alpha type of the intercept(s); * this can be a vector (of the same length as y) of intercepts or a single * value (for models with constant intercept); * @tparam T_beta type of the weight vector; * this can also be a single value; * @tparam T_scale type of the (positive) scale(s); * this can be a vector (of the same length as y, for heteroskedasticity) * or a scalar. * @param y_cl vector parameter on OpenCL device * @param x_cl design matrix on OpenCL device * @param alpha intercept (in log odds) * @param beta weight vector * @param sigma (Sequence of) scale parameters for the normal * distribution. * @return log probability or log sum of probabilities * @throw std::domain_error if x, beta or alpha is infinite. * @throw std::domain_error if the scale is not positive. * @throw std::invalid_argument if container sizes mismatch. */ template <bool propto, typename T_alpha, typename T_beta, typename T_scale> return_type_t<T_alpha, T_beta, T_scale> normal_id_glm_lpdf( const matrix_cl<double> &y_cl, const matrix_cl<double> &x_cl, const T_alpha &alpha, const T_beta &beta, const T_scale &sigma) { static const char *function = "normal_id_glm_lpdf(OpenCL)"; using T_partials_return = partials_return_t<T_alpha, T_beta, T_scale>; using T_scale_val = typename std::conditional_t< is_vector<T_scale>::value, Eigen::Array<partials_return_t<T_scale>, -1, 1>, partials_return_t<T_scale>>; using Eigen::Array; using Eigen::Dynamic; using Eigen::Matrix; using Eigen::VectorXd; const size_t N = x_cl.rows(); const size_t M = x_cl.cols(); check_positive_finite(function, "Scale vector", sigma); check_size_match(function, "Rows of ", "x_cl", N, "rows of ", "y_cl", y_cl.rows()); check_consistent_size(function, "Weight vector", beta, M); if (is_vector<T_scale>::value) { check_size_match(function, "Rows of ", "y_cl", N, "size of ", "sigma", length(sigma)); } if (is_vector<T_alpha>::value) { check_size_match(function, "Rows of ", "y_cl", N, "size of ", "alpha", length(alpha)); } if (!include_summand<propto, T_alpha, T_beta, T_scale>::value) { return 0; } if (N == 0 || M == 0) { return 0; } const auto &beta_val = value_of_rec(beta); const auto &alpha_val = value_of_rec(alpha); const auto &sigma_val = value_of_rec(sigma); const auto &beta_val_vec = as_column_vector_or_scalar(beta_val); const auto &alpha_val_vec = as_column_vector_or_scalar(alpha_val); const auto &sigma_val_vec = as_column_vector_or_scalar(sigma_val); T_scale_val inv_sigma = 1 / as_array_or_scalar(sigma_val_vec); Matrix<T_partials_return, Dynamic, 1> y_minus_mu_over_sigma_mat(N); auto y_scaled = y_minus_mu_over_sigma_mat.array(); const int local_size = opencl_kernels::normal_id_glm.get_option("LOCAL_SIZE_"); const int wgs = (N + local_size - 1) / local_size; matrix_cl<double> beta_cl(beta_val_vec); matrix_cl<double> alpha_cl(alpha_val_vec); matrix_cl<double> sigma_cl(sigma_val_vec); const bool need_mu_derivative = !is_constant_all<T_beta, T_alpha>::value; matrix_cl<double> mu_derivative_cl(need_mu_derivative ? N : 0, 1); const bool need_mu_derivative_sum = !is_constant_all<T_alpha>::value && !is_vector<T_alpha>::value; matrix_cl<double> mu_derivative_sum_cl(need_mu_derivative_sum ? wgs : 0, 1); matrix_cl<double> y_minus_mu_over_sigma_squared_sum_cl(wgs, 1); const bool need_sigma_derivative = !is_constant_all<T_scale>::value && is_vector<T_scale>::value; matrix_cl<double> sigma_derivative_cl(need_sigma_derivative ? N : 0, 1); const bool need_log_sigma_sum = include_summand<propto, T_scale>::value && is_vector<T_scale>::value; matrix_cl<double> log_sigma_sum_cl(need_log_sigma_sum ? wgs : 0, 1); try { opencl_kernels::normal_id_glm( cl::NDRange(local_size * wgs), cl::NDRange(local_size), mu_derivative_cl, mu_derivative_sum_cl, y_minus_mu_over_sigma_squared_sum_cl, sigma_derivative_cl, log_sigma_sum_cl, y_cl, x_cl, alpha_cl, beta_cl, sigma_cl, N, M, length(alpha) != 1, length(sigma) != 1, need_mu_derivative, need_mu_derivative_sum, need_sigma_derivative, need_log_sigma_sum); } catch (const cl::Error &e) { check_opencl_error(function, e); } double y_scaled_sq_sum = sum(from_matrix_cl(y_minus_mu_over_sigma_squared_sum_cl)); operands_and_partials<T_alpha, T_beta, T_scale> ops_partials(alpha, beta, sigma); if (!is_constant_all<T_alpha>::value && is_vector<T_alpha>::value) { ops_partials.edge1_.partials_ = from_matrix_cl<Dynamic, 1>(mu_derivative_cl); } if (need_mu_derivative_sum) { ops_partials.edge1_.partials_[0] = sum(from_matrix_cl(mu_derivative_sum_cl)); } if (!is_constant_all<T_beta>::value) { const matrix_cl<double> mu_derivative_transpose_cl( mu_derivative_cl.buffer(), 1, mu_derivative_cl.rows()); // transposition of a vector can be done // without copying ops_partials.edge2_.partials_ = from_matrix_cl<1, Dynamic>(mu_derivative_transpose_cl * x_cl); } if (!is_constant_all<T_scale>::value) { if (is_vector<T_scale>::value) { ops_partials.edge3_.partials_ = from_matrix_cl<Dynamic, 1>(sigma_derivative_cl); } else { ops_partials.edge3_.partials_[0] = (y_scaled_sq_sum - N) * as_scalar(inv_sigma); } } if (!std::isfinite(y_scaled_sq_sum)) { check_finite(function, "Vector of dependent variables", from_matrix_cl(y_cl)); check_finite(function, "Weight vector", beta); check_finite(function, "Intercept", alpha); // if all other checks passed, next will only fail if x is not finite check_finite(function, "Matrix of independent variables", y_scaled_sq_sum); } // Compute log probability. T_partials_return logp(0.0); if (include_summand<propto>::value) { logp += NEG_LOG_SQRT_TWO_PI * N; } if (include_summand<propto, T_scale>::value) { if (is_vector<T_scale>::value) { logp -= sum(from_matrix_cl(log_sigma_sum_cl)); } else { logp -= N * log(as_scalar(sigma_val)); } } if (include_summand<propto, T_alpha, T_beta, T_scale>::value) { logp -= 0.5 * y_scaled_sq_sum; } return ops_partials.build(logp); } template <typename T_alpha, typename T_beta, typename T_scale> inline return_type_t<T_alpha, T_beta, T_scale> normal_id_glm_lpdf( const matrix_cl<double> &y, const matrix_cl<double> &x, const T_alpha &alpha, const T_beta &beta, const T_scale &sigma) { return normal_id_glm_lpdf<false>(y, x, alpha, beta, sigma); } } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>/** * Copyright (C) 2018 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "geometry_collector.h" #include <assimp/scene.h> #include <assimp/postprocess.h> using namespace repo::manipulator::modelconvertor::odaHelper; GeometryCollector::GeometryCollector() { } GeometryCollector::~GeometryCollector() { } repo::core::model::CameraNode generateCameraNode(camera_t camera, repo::lib::RepoUUID parentID) { auto node = repo::core::model::RepoBSONFactory::makeCameraNode(camera.aspectRatio, camera.farClipPlane, camera.nearClipPlane, camera.FOV, camera.eye, camera.pos, camera.up, camera.name); node = node.cloneAndAddParent(parentID); return node; } void GeometryCollector::addCameraNode(camera_t node) { cameras.push_back(node); } repo::core::model::RepoNodeSet GeometryCollector::getCameraNodes(repo::lib::RepoUUID parentID) { repo::core::model::RepoNodeSet camerasNodeSet; for (auto& camera : cameras) camerasNodeSet.insert(new repo::core::model::CameraNode(generateCameraNode(camera, parentID))); return camerasNodeSet; } bool GeometryCollector::hasCemaraNodes() { return cameras.size(); } repo::core::model::TransformationNode GeometryCollector::createRootNode() { return repo::core::model::RepoBSONFactory::makeTransformationNode(rootMatrix, "rootNode"); } void GeometryCollector::setCurrentMaterial(const repo_material_t &material, bool missingTexture) { auto checkSum = material.checksum(); if(idxToMat.find(checkSum) == idxToMat.end()) { idxToMat[checkSum] = { repo::core::model::RepoBSONFactory::makeMaterialNode(material), createTextureNode(material.texturePath) }; if (missingTexture) this->missingTextures = true; } currMat = checkSum; } void repo::manipulator::modelconvertor::odaHelper::GeometryCollector::setCurrentMeta(const std::pair<std::vector<std::string>, std::vector<std::string>>& meta) { currentMeta = meta; } repo::core::model::RepoNodeSet repo::manipulator::modelconvertor::odaHelper::GeometryCollector::getMetaNodes() { return metaSet; } mesh_data_t GeometryCollector::createMeshEntry() { mesh_data_t entry; entry.matIdx = currMat; entry.name = nextMeshName; entry.groupName = nextGroupName; entry.layerName = nextLayer.empty() ? "UnknownLayer" : nextLayer; entry.metaValues = currentMeta; return entry; } void GeometryCollector::startMeshEntry() { nextMeshName = nextMeshName.empty() ? std::to_string(std::time(0)) : nextMeshName; nextGroupName = nextGroupName.empty() ? nextMeshName : nextGroupName; nextLayer = nextLayer.empty() ? nextMeshName : nextLayer; if (meshData.find(nextGroupName) == meshData.end()) { meshData[nextGroupName] = std::unordered_map<std::string, std::unordered_map<int, mesh_data_t>>(); } if (meshData[nextGroupName].find(nextLayer) == meshData[nextGroupName].end()) { meshData[nextGroupName][nextLayer] = std::unordered_map<int, mesh_data_t>(); } if (meshData[nextGroupName][nextLayer].find(currMat) == meshData[nextGroupName][nextLayer].end()) { meshData[nextGroupName][nextLayer][currMat] = createMeshEntry(); } currentEntry = &meshData[nextGroupName][nextLayer][currMat]; } void GeometryCollector::stopMeshEntry() { if(currentEntry) currentEntry->vToVIndex.clear(); nextMeshName = ""; } void GeometryCollector::addFace( const std::vector<repo::lib::RepoVector3D64> &vertices, const std::vector<repo::lib::RepoVector2D>& uvCoords) { if (!meshData.size()) startMeshEntry(); repo_face_t face; for (auto i = 0; i < vertices.size(); ++i) { auto& v = vertices[i]; if (currentEntry->vToVIndex.find(v) == currentEntry->vToVIndex.end()) { currentEntry->vToVIndex[v] = currentEntry->rawVertices.size(); currentEntry->rawVertices.push_back(v); if (i < uvCoords.size()) currentEntry->uvCoords.push_back(uvCoords[i]); if (currentEntry->boundingBox.size()) { currentEntry->boundingBox[0][0] = currentEntry->boundingBox[0][0] > v.x ? (float) v.x : currentEntry->boundingBox[0][0]; currentEntry->boundingBox[0][1] = currentEntry->boundingBox[0][1] > v.y ? (float) v.y : currentEntry->boundingBox[0][1]; currentEntry->boundingBox[0][2] = currentEntry->boundingBox[0][2] > v.z ? (float) v.z : currentEntry->boundingBox[0][2]; currentEntry->boundingBox[1][0] = currentEntry->boundingBox[1][0] < v.x ? (float) v.x : currentEntry->boundingBox[1][0]; currentEntry->boundingBox[1][1] = currentEntry->boundingBox[1][1] < v.y ? (float) v.y : currentEntry->boundingBox[1][1]; currentEntry->boundingBox[1][2] = currentEntry->boundingBox[1][2] < v.z ? (float) v.z : currentEntry->boundingBox[1][2]; } else { currentEntry->boundingBox.push_back({ (float)v.x, (float)v.y, (float)v.z }); currentEntry->boundingBox.push_back({ (float)v.x, (float)v.y, (float)v.z }); } if (minMeshBox.size()) { minMeshBox[0] = v.x < minMeshBox[0] ? v.x : minMeshBox[0]; minMeshBox[1] = v.y < minMeshBox[1] ? v.y : minMeshBox[1]; minMeshBox[2] = v.z < minMeshBox[2] ? v.z : minMeshBox[2]; } else { minMeshBox = { v.x, v.y, v.z }; } } face.push_back(currentEntry->vToVIndex[v]); } currentEntry->faces.push_back(face); } repo::core::model::RepoNodeSet GeometryCollector::getMeshNodes(const repo::core::model::TransformationNode& root) { repo::core::model::RepoNodeSet res; auto dummyCol = std::vector<repo_color4d_t>(); auto dummyOutline = std::vector<std::vector<float>>(); std::unordered_map<std::string, repo::core::model::TransformationNode*> layerToTrans; auto rootId = root.getSharedID(); repoDebug << "Mesh data: " << meshData.size(); for (const auto &meshGroupEntry : meshData) { for (const auto &meshLayerEntry : meshGroupEntry.second) { for (const auto &meshMatEntry : meshLayerEntry.second) { if (!meshMatEntry.second.rawVertices.size()) continue; auto uvChannels = meshMatEntry.second.uvCoords.size() ? std::vector<std::vector<repo::lib::RepoVector2D>>{meshMatEntry.second.uvCoords} : std::vector<std::vector<repo::lib::RepoVector2D>>(); if (layerToTrans.find(meshLayerEntry.first) == layerToTrans.end()) { layerToTrans[meshLayerEntry.first] = createTransNode(meshLayerEntry.first, rootId); transNodes.insert(layerToTrans[meshLayerEntry.first]); } std::vector<repo::lib::RepoVector3D> vertices32; vertices32.reserve(meshMatEntry.second.rawVertices.size()); for (const auto &v : meshMatEntry.second.rawVertices) { vertices32.push_back({ (float)(v.x - minMeshBox[0]), (float)(v.y - minMeshBox[1]), (float)(v.z - minMeshBox[2]) }); } auto meshNode = repo::core::model::RepoBSONFactory::makeMeshNode( vertices32, meshMatEntry.second.faces, std::vector<repo::lib::RepoVector3D>(), meshMatEntry.second.boundingBox, uvChannels, dummyCol, dummyOutline, meshGroupEntry.first, { layerToTrans[meshLayerEntry.first]->getSharedID() } ); auto& metaValues = meshMatEntry.second.metaValues; if (!metaValues.first.empty()) { metaSet.insert(new repo::core::model::MetadataNode(repo::core::model::RepoBSONFactory::makeMetaDataNode(metaValues.first, metaValues.second, meshMatEntry.second.name, { meshNode.getSharedID() }))); } if (matToMeshes.find(meshMatEntry.second.matIdx) == matToMeshes.end()) { matToMeshes[meshMatEntry.second.matIdx] = std::vector<repo::lib::RepoUUID>(); } matToMeshes[meshMatEntry.second.matIdx].push_back(meshNode.getSharedID()); res.insert(new repo::core::model::MeshNode(meshNode)); } } } transNodes.insert(new repo::core::model::TransformationNode(root)); return res; } repo::core::model::TransformationNode* GeometryCollector::createTransNode( const std::string &name, const repo::lib::RepoUUID &parentId) { return new repo::core::model::TransformationNode(repo::core::model::RepoBSONFactory::makeTransformationNode(repo::lib::RepoMatrix(), name, { parentId })); } void repo::manipulator::modelconvertor::odaHelper::GeometryCollector::setRootMatrix(repo::lib::RepoMatrix matrix) { rootMatrix = matrix; } bool GeometryCollector::hasMissingTextures() { return missingTextures; } void GeometryCollector::getMaterialAndTextureNodes(repo::core::model::RepoNodeSet& materials, repo::core::model::RepoNodeSet& textures) { materials.clear(); textures.clear(); for (const auto &matPair : idxToMat) { auto matIdx = matPair.first; if (matToMeshes.find(matIdx) != matToMeshes.end()) { auto& materialNode = matPair.second.first; auto& textureNode = matPair.second.second; auto matNode = new repo::core::model::MaterialNode(materialNode.cloneAndAddParent(matToMeshes[matIdx])); materials.insert(matNode); if (!textureNode.isEmpty()) { auto texNode = new repo::core::model::TextureNode(textureNode.cloneAndAddParent(matNode->getSharedID())); textures.insert(texNode); } } else { repoDebug << "Did not find matTo Meshes: " << matIdx; } } } repo::core::model::TextureNode GeometryCollector::createTextureNode(const std::string& texturePath) { std::ifstream::pos_type size; std::ifstream file(texturePath, std::ios::in | std::ios::binary | std::ios::ate); char *memblock = nullptr; if (!file.is_open()) return repo::core::model::TextureNode(); size = file.tellg(); memblock = new char[size]; file.seekg(0, std::ios::beg); file.read(memblock, size); file.close(); auto texnode = repo::core::model::RepoBSONFactory::makeTextureNode( texturePath, (const char*)memblock, size, 1, 0, REPO_NODE_API_LEVEL_1 ); delete[] memblock; return texnode; }<commit_msg>ISSUE #291 - test: remove positioning to origin<commit_after>/** * Copyright (C) 2018 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "geometry_collector.h" #include <assimp/scene.h> #include <assimp/postprocess.h> using namespace repo::manipulator::modelconvertor::odaHelper; GeometryCollector::GeometryCollector() { } GeometryCollector::~GeometryCollector() { } repo::core::model::CameraNode generateCameraNode(camera_t camera, repo::lib::RepoUUID parentID) { auto node = repo::core::model::RepoBSONFactory::makeCameraNode(camera.aspectRatio, camera.farClipPlane, camera.nearClipPlane, camera.FOV, camera.eye, camera.pos, camera.up, camera.name); node = node.cloneAndAddParent(parentID); return node; } void GeometryCollector::addCameraNode(camera_t node) { cameras.push_back(node); } repo::core::model::RepoNodeSet GeometryCollector::getCameraNodes(repo::lib::RepoUUID parentID) { repo::core::model::RepoNodeSet camerasNodeSet; for (auto& camera : cameras) camerasNodeSet.insert(new repo::core::model::CameraNode(generateCameraNode(camera, parentID))); return camerasNodeSet; } bool GeometryCollector::hasCemaraNodes() { return cameras.size(); } repo::core::model::TransformationNode GeometryCollector::createRootNode() { return repo::core::model::RepoBSONFactory::makeTransformationNode(rootMatrix, "rootNode"); } void GeometryCollector::setCurrentMaterial(const repo_material_t &material, bool missingTexture) { auto checkSum = material.checksum(); if(idxToMat.find(checkSum) == idxToMat.end()) { idxToMat[checkSum] = { repo::core::model::RepoBSONFactory::makeMaterialNode(material), createTextureNode(material.texturePath) }; if (missingTexture) this->missingTextures = true; } currMat = checkSum; } void repo::manipulator::modelconvertor::odaHelper::GeometryCollector::setCurrentMeta(const std::pair<std::vector<std::string>, std::vector<std::string>>& meta) { currentMeta = meta; } repo::core::model::RepoNodeSet repo::manipulator::modelconvertor::odaHelper::GeometryCollector::getMetaNodes() { return metaSet; } mesh_data_t GeometryCollector::createMeshEntry() { mesh_data_t entry; entry.matIdx = currMat; entry.name = nextMeshName; entry.groupName = nextGroupName; entry.layerName = nextLayer.empty() ? "UnknownLayer" : nextLayer; entry.metaValues = currentMeta; return entry; } void GeometryCollector::startMeshEntry() { nextMeshName = nextMeshName.empty() ? std::to_string(std::time(0)) : nextMeshName; nextGroupName = nextGroupName.empty() ? nextMeshName : nextGroupName; nextLayer = nextLayer.empty() ? nextMeshName : nextLayer; if (meshData.find(nextGroupName) == meshData.end()) { meshData[nextGroupName] = std::unordered_map<std::string, std::unordered_map<int, mesh_data_t>>(); } if (meshData[nextGroupName].find(nextLayer) == meshData[nextGroupName].end()) { meshData[nextGroupName][nextLayer] = std::unordered_map<int, mesh_data_t>(); } if (meshData[nextGroupName][nextLayer].find(currMat) == meshData[nextGroupName][nextLayer].end()) { meshData[nextGroupName][nextLayer][currMat] = createMeshEntry(); } currentEntry = &meshData[nextGroupName][nextLayer][currMat]; } void GeometryCollector::stopMeshEntry() { if(currentEntry) currentEntry->vToVIndex.clear(); nextMeshName = ""; } void GeometryCollector::addFace( const std::vector<repo::lib::RepoVector3D64> &vertices, const std::vector<repo::lib::RepoVector2D>& uvCoords) { if (!meshData.size()) startMeshEntry(); repo_face_t face; for (auto i = 0; i < vertices.size(); ++i) { auto& v = vertices[i]; if (currentEntry->vToVIndex.find(v) == currentEntry->vToVIndex.end()) { currentEntry->vToVIndex[v] = currentEntry->rawVertices.size(); currentEntry->rawVertices.push_back(v); if (i < uvCoords.size()) currentEntry->uvCoords.push_back(uvCoords[i]); if (currentEntry->boundingBox.size()) { currentEntry->boundingBox[0][0] = currentEntry->boundingBox[0][0] > v.x ? (float) v.x : currentEntry->boundingBox[0][0]; currentEntry->boundingBox[0][1] = currentEntry->boundingBox[0][1] > v.y ? (float) v.y : currentEntry->boundingBox[0][1]; currentEntry->boundingBox[0][2] = currentEntry->boundingBox[0][2] > v.z ? (float) v.z : currentEntry->boundingBox[0][2]; currentEntry->boundingBox[1][0] = currentEntry->boundingBox[1][0] < v.x ? (float) v.x : currentEntry->boundingBox[1][0]; currentEntry->boundingBox[1][1] = currentEntry->boundingBox[1][1] < v.y ? (float) v.y : currentEntry->boundingBox[1][1]; currentEntry->boundingBox[1][2] = currentEntry->boundingBox[1][2] < v.z ? (float) v.z : currentEntry->boundingBox[1][2]; } else { currentEntry->boundingBox.push_back({ (float)v.x, (float)v.y, (float)v.z }); currentEntry->boundingBox.push_back({ (float)v.x, (float)v.y, (float)v.z }); } if (minMeshBox.size()) { minMeshBox[0] = v.x < minMeshBox[0] ? v.x : minMeshBox[0]; minMeshBox[1] = v.y < minMeshBox[1] ? v.y : minMeshBox[1]; minMeshBox[2] = v.z < minMeshBox[2] ? v.z : minMeshBox[2]; } else { minMeshBox = { v.x, v.y, v.z }; } } face.push_back(currentEntry->vToVIndex[v]); } currentEntry->faces.push_back(face); } repo::core::model::RepoNodeSet GeometryCollector::getMeshNodes(const repo::core::model::TransformationNode& root) { repo::core::model::RepoNodeSet res; auto dummyCol = std::vector<repo_color4d_t>(); auto dummyOutline = std::vector<std::vector<float>>(); std::unordered_map<std::string, repo::core::model::TransformationNode*> layerToTrans; auto rootId = root.getSharedID(); repoDebug << "Mesh data: " << meshData.size(); for (const auto &meshGroupEntry : meshData) { for (const auto &meshLayerEntry : meshGroupEntry.second) { for (const auto &meshMatEntry : meshLayerEntry.second) { if (!meshMatEntry.second.rawVertices.size()) continue; auto uvChannels = meshMatEntry.second.uvCoords.size() ? std::vector<std::vector<repo::lib::RepoVector2D>>{meshMatEntry.second.uvCoords} : std::vector<std::vector<repo::lib::RepoVector2D>>(); if (layerToTrans.find(meshLayerEntry.first) == layerToTrans.end()) { layerToTrans[meshLayerEntry.first] = createTransNode(meshLayerEntry.first, rootId); transNodes.insert(layerToTrans[meshLayerEntry.first]); } std::vector<repo::lib::RepoVector3D> vertices32; vertices32.reserve(meshMatEntry.second.rawVertices.size()); for (const auto &v : meshMatEntry.second.rawVertices) { vertices32.push_back({ (float)(v.x), (float)(v.y), (float)(v.z) }); } auto meshNode = repo::core::model::RepoBSONFactory::makeMeshNode( vertices32, meshMatEntry.second.faces, std::vector<repo::lib::RepoVector3D>(), meshMatEntry.second.boundingBox, uvChannels, dummyCol, dummyOutline, meshGroupEntry.first, { layerToTrans[meshLayerEntry.first]->getSharedID() } ); auto& metaValues = meshMatEntry.second.metaValues; if (!metaValues.first.empty()) { metaSet.insert(new repo::core::model::MetadataNode(repo::core::model::RepoBSONFactory::makeMetaDataNode(metaValues.first, metaValues.second, meshMatEntry.second.name, { meshNode.getSharedID() }))); } if (matToMeshes.find(meshMatEntry.second.matIdx) == matToMeshes.end()) { matToMeshes[meshMatEntry.second.matIdx] = std::vector<repo::lib::RepoUUID>(); } matToMeshes[meshMatEntry.second.matIdx].push_back(meshNode.getSharedID()); res.insert(new repo::core::model::MeshNode(meshNode)); } } } transNodes.insert(new repo::core::model::TransformationNode(root)); return res; } repo::core::model::TransformationNode* GeometryCollector::createTransNode( const std::string &name, const repo::lib::RepoUUID &parentId) { return new repo::core::model::TransformationNode(repo::core::model::RepoBSONFactory::makeTransformationNode(repo::lib::RepoMatrix(), name, { parentId })); } void repo::manipulator::modelconvertor::odaHelper::GeometryCollector::setRootMatrix(repo::lib::RepoMatrix matrix) { rootMatrix = matrix; } bool GeometryCollector::hasMissingTextures() { return missingTextures; } void GeometryCollector::getMaterialAndTextureNodes(repo::core::model::RepoNodeSet& materials, repo::core::model::RepoNodeSet& textures) { materials.clear(); textures.clear(); for (const auto &matPair : idxToMat) { auto matIdx = matPair.first; if (matToMeshes.find(matIdx) != matToMeshes.end()) { auto& materialNode = matPair.second.first; auto& textureNode = matPair.second.second; auto matNode = new repo::core::model::MaterialNode(materialNode.cloneAndAddParent(matToMeshes[matIdx])); materials.insert(matNode); if (!textureNode.isEmpty()) { auto texNode = new repo::core::model::TextureNode(textureNode.cloneAndAddParent(matNode->getSharedID())); textures.insert(texNode); } } else { repoDebug << "Did not find matTo Meshes: " << matIdx; } } } repo::core::model::TextureNode GeometryCollector::createTextureNode(const std::string& texturePath) { std::ifstream::pos_type size; std::ifstream file(texturePath, std::ios::in | std::ios::binary | std::ios::ate); char *memblock = nullptr; if (!file.is_open()) return repo::core::model::TextureNode(); size = file.tellg(); memblock = new char[size]; file.seekg(0, std::ios::beg); file.read(memblock, size); file.close(); auto texnode = repo::core::model::RepoBSONFactory::makeTextureNode( texturePath, (const char*)memblock, size, 1, 0, REPO_NODE_API_LEVEL_1 ); delete[] memblock; return texnode; }<|endoftext|>
<commit_before>/* * RudeSkinnedMesh.cpp * * Bork3D Game Engine * Copyright (c) 2009 Bork 3D LLC. All rights reserved. * */ #include "RudeSkinnedMesh.h" #include "RudeDebug.h" #include "RudeGL.h" #include "RudeFile.h" #include "RudePerf.h" #include "RudeTextureManager.h" #include "RudeTweaker.h" bool gDebugAnim = false; RUDE_TWEAK(DebugAnim, kBool, gDebugAnim); float gDebugAnimFrame = 0; RUDE_TWEAK(DebugAnimFrame, kFloat, gDebugAnimFrame); RudeSkinnedMesh::RudeSkinnedMesh(RudeObject *owner) : RudeMesh(owner) , m_frame(0.0f) , m_fps(24.0f) , m_toFrame(0.0f) , m_animateTo(false) { } RudeSkinnedMesh::~RudeSkinnedMesh() { } int RudeSkinnedMesh::Load(const char *name) { RUDE_REPORT("RudeSkinnedMesh::Load %s\n", name); if(RudeMesh::Load(name)) return -1; for(unsigned int i = 0; i < m_model.nNumMesh; i++) { SPODMesh *mesh = &m_model.pMesh[i]; for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++) { int offset = mesh->sBoneBatches.pnBatchOffset[b]; int end = mesh->sBoneBatches.pnBatchOffset[b+1]; if(b == (mesh->sBoneBatches.nBatchCnt - 1)) end = mesh->nNumFaces; int numfaces = (end - offset); RUDE_REPORT(" Mesh %d-%d: %d tris\n", i, b, numfaces); } RUDE_ASSERT(mesh->sBoneIdx.eType == EPODDataUnsignedByte, "Bone indices must be unsigned byte"); RUDE_ASSERT(mesh->sBoneWeight.eType == EPODDataFloat, "Bone weight must be float"); RUDE_ASSERT(mesh->sVertex.eType == EPODDataFloat, "Mesh verts should be float"); } return 0; } void RudeSkinnedMesh::SetFrame(float f) { m_animateTo = false; m_frame = f; } void RudeSkinnedMesh::AnimateTo(float f) { m_animateTo = true; m_toFrame = f; } void RudeSkinnedMesh::NextFrame(float delta) { if(m_animateTo) { if(m_toFrame > m_frame) { m_frame += delta * m_fps; if(m_frame > m_toFrame) { m_frame = m_toFrame; m_animateTo = false; } } else { m_frame -= delta * m_fps; if(m_frame < m_toFrame) { m_frame = m_toFrame; m_animateTo = false; } } } m_model.SetFrame(m_frame); if(gDebugAnim) m_model.SetFrame(gDebugAnimFrame); } void RudeSkinnedMesh::Render() { #ifdef RUDE_OGLES RUDE_PERF_START(kPerfRudeSkinMeshRender); //int numbonemats; //glGetIntegerv(GL_MAX_PALETTE_MATRICES_OES, &numbonemats); //printf("bonemats %d\n", numbonemats); glMatrixMode(GL_MODELVIEW); PVRTMATRIX viewmat; glGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f); RGL.Enable(kBackfaceCull, true); glCullFace(GL_FRONT); glFrontFace(GL_CW); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); RGL.EnableClient(kVertexArray, true); RGL.EnableClient(kTextureCoordArray, true); //glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); if(m_animate) { glEnable(GL_MATRIX_PALETTE_OES); glEnableClientState(GL_MATRIX_INDEX_ARRAY_OES); glEnableClientState(GL_WEIGHT_ARRAY_OES); } //glScalef(m_scale.x(), m_scale.y(), m_scale.z()); for(int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'M') continue; SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial]; SPODMesh *mesh = &m_model.pMesh[node->nIdx]; if(m_animate) { glMatrixIndexPointerOES(mesh->sBoneIdx.n, GL_UNSIGNED_BYTE, mesh->sBoneIdx.nStride, mesh->pInterleaved + (long) mesh->sBoneIdx.pData); glWeightPointerOES(mesh->sBoneWeight.n, GL_FLOAT, mesh->sBoneWeight.nStride, mesh->pInterleaved + (long) mesh->sBoneWeight.pData); } int textureid = material->nIdxTexDiffuse; if(textureid >= 0) RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]); unsigned short *indices = (unsigned short*) mesh->sFaces.pData; glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData); if((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA)) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData); } else RGL.EnableClient(kColorArray, false); int totalbatchcnt = 0; for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++) { int batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b]; if(m_animate) { glMatrixMode(GL_MATRIX_PALETTE_OES); for(int j = 0; j < batchcnt; ++j) { glCurrentPaletteMatrixOES(j); // Generates the world matrix for the given bone in this batch. PVRTMATRIX mBoneWorld; int i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt]; m_model.GetBoneWorldMatrix(mBoneWorld, *node, m_model.pNode[i32NodeID]); // Multiply the bone's world matrix by the view matrix to put it in view space PVRTMatrixMultiply(mBoneWorld, mBoneWorld, viewmat); // Load the bone matrix into the current palette matrix. glLoadMatrixf(mBoneWorld.f); } } totalbatchcnt += batchcnt; int offset = mesh->sBoneBatches.pnBatchOffset[b] * 3; int end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3; if(b == (mesh->sBoneBatches.nBatchCnt - 1)) end = mesh->nNumFaces*3; int numidx = (end - offset); glDrawElements(GL_TRIANGLES, numidx, GL_UNSIGNED_SHORT, &indices[offset]); } } glDisable(GL_MATRIX_PALETTE_OES); glDisableClientState(GL_MATRIX_INDEX_ARRAY_OES); glDisableClientState(GL_WEIGHT_ARRAY_OES); RUDE_PERF_STOP(kPerfRudeSkinMeshRender); #endif } <commit_msg>first pass on software skinned mesh renderer<commit_after>/* * RudeSkinnedMesh.cpp * * Bork3D Game Engine * Copyright (c) 2009 Bork 3D LLC. All rights reserved. * */ #include "RudeSkinnedMesh.h" #include "RudeDebug.h" #include "RudeGL.h" #include "RudeFile.h" #include "RudePerf.h" #include "RudeTextureManager.h" #include "RudeTweaker.h" bool gDebugAnim = false; RUDE_TWEAK(DebugAnim, kBool, gDebugAnim); float gDebugAnimFrame = 0; RUDE_TWEAK(DebugAnimFrame, kFloat, gDebugAnimFrame); RudeSkinnedMesh::RudeSkinnedMesh(RudeObject *owner) : RudeMesh(owner) , m_frame(0.0f) , m_fps(24.0f) , m_toFrame(0.0f) , m_animateTo(false) { } RudeSkinnedMesh::~RudeSkinnedMesh() { } int RudeSkinnedMesh::Load(const char *name) { RUDE_REPORT("RudeSkinnedMesh::Load %s\n", name); if(RudeMesh::Load(name)) return -1; for(unsigned int i = 0; i < m_model.nNumMesh; i++) { SPODMesh *mesh = &m_model.pMesh[i]; for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++) { int offset = mesh->sBoneBatches.pnBatchOffset[b]; int end = mesh->sBoneBatches.pnBatchOffset[b+1]; if(b == (mesh->sBoneBatches.nBatchCnt - 1)) end = mesh->nNumFaces; int numfaces = (end - offset); RUDE_REPORT(" Mesh %d-%d: %d tris\n", i, b, numfaces); } RUDE_ASSERT(mesh->sBoneIdx.eType == EPODDataUnsignedByte, "Bone indices must be unsigned byte"); RUDE_ASSERT(mesh->sBoneWeight.eType == EPODDataFloat, "Bone weight must be float"); RUDE_ASSERT(mesh->sVertex.eType == EPODDataFloat, "Mesh verts should be float"); } //GLhandleARB g_vertexShader = glCreateShaderObjectARB( GL_VERTEX_SHADER_ARB ); return 0; } void RudeSkinnedMesh::SetFrame(float f) { m_animateTo = false; m_frame = f; } void RudeSkinnedMesh::AnimateTo(float f) { m_animateTo = true; m_toFrame = f; } void RudeSkinnedMesh::NextFrame(float delta) { if(m_animateTo) { if(m_toFrame > m_frame) { m_frame += delta * m_fps; if(m_frame > m_toFrame) { m_frame = m_toFrame; m_animateTo = false; } } else { m_frame -= delta * m_fps; if(m_frame < m_toFrame) { m_frame = m_toFrame; m_animateTo = false; } } } m_model.SetFrame(m_frame); if(gDebugAnim) m_model.SetFrame(gDebugAnimFrame); } void RudeSkinnedMesh::Render() { #ifdef RUDE_OGLES RUDE_PERF_START(kPerfRudeSkinMeshRender); //int numbonemats; //glGetIntegerv(GL_MAX_PALETTE_MATRICES_OES, &numbonemats); //printf("bonemats %d\n", numbonemats); glMatrixMode(GL_MODELVIEW); PVRTMATRIX viewmat; glGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f); RGL.Enable(kBackfaceCull, true); glCullFace(GL_FRONT); glFrontFace(GL_CW); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); RGL.EnableClient(kVertexArray, true); RGL.EnableClient(kTextureCoordArray, true); //glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); if(m_animate) { glEnable(GL_MATRIX_PALETTE_OES); glEnableClientState(GL_MATRIX_INDEX_ARRAY_OES); glEnableClientState(GL_WEIGHT_ARRAY_OES); } //glScalef(m_scale.x(), m_scale.y(), m_scale.z()); for(int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'M') continue; SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial]; SPODMesh *mesh = &m_model.pMesh[node->nIdx]; if(m_animate) { glMatrixIndexPointerOES(mesh->sBoneIdx.n, GL_UNSIGNED_BYTE, mesh->sBoneIdx.nStride, mesh->pInterleaved + (long) mesh->sBoneIdx.pData); glWeightPointerOES(mesh->sBoneWeight.n, GL_FLOAT, mesh->sBoneWeight.nStride, mesh->pInterleaved + (long) mesh->sBoneWeight.pData); } int textureid = material->nIdxTexDiffuse; if(textureid >= 0) RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]); unsigned short *indices = (unsigned short*) mesh->sFaces.pData; glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData); if((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA)) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData); } else RGL.EnableClient(kColorArray, false); int totalbatchcnt = 0; for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++) { int batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b]; if(m_animate) { glMatrixMode(GL_MATRIX_PALETTE_OES); for(int j = 0; j < batchcnt; ++j) { glCurrentPaletteMatrixOES(j); // Generates the world matrix for the given bone in this batch. PVRTMATRIX mBoneWorld; int i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt]; m_model.GetBoneWorldMatrix(mBoneWorld, *node, m_model.pNode[i32NodeID]); // Multiply the bone's world matrix by the view matrix to put it in view space PVRTMatrixMultiply(mBoneWorld, mBoneWorld, viewmat); // Load the bone matrix into the current palette matrix. glLoadMatrixf(mBoneWorld.f); } } totalbatchcnt += batchcnt; int offset = mesh->sBoneBatches.pnBatchOffset[b] * 3; int end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3; if(b == (mesh->sBoneBatches.nBatchCnt - 1)) end = mesh->nNumFaces*3; int numidx = (end - offset); glDrawElements(GL_TRIANGLES, numidx, GL_UNSIGNED_SHORT, &indices[offset]); } } glDisable(GL_MATRIX_PALETTE_OES); glDisableClientState(GL_MATRIX_INDEX_ARRAY_OES); glDisableClientState(GL_WEIGHT_ARRAY_OES); RUDE_PERF_STOP(kPerfRudeSkinMeshRender); #else glMatrixMode(GL_MODELVIEW); PVRTMATRIX viewmat; glGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f); RGL.Enable(kBackfaceCull, true); glCullFace(GL_FRONT); glFrontFace(GL_CW); RGL.EnableClient(kVertexArray, true); RGL.EnableClient(kTextureCoordArray, true); for(unsigned int i = 0; i < m_model.nNumNode; i++) { SPODNode *node = &m_model.pNode[i]; if(!node->pszName) continue; if(node->pszName[0] != 'M') continue; SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial]; SPODMesh *mesh = &m_model.pMesh[node->nIdx]; int textureid = material->nIdxTexDiffuse; if(textureid >= 0) RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]); unsigned short *indices = (unsigned short*) mesh->sFaces.pData; glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData); glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData); if((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA)) { RGL.EnableClient(kColorArray, true); glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData); } else { RGL.EnableClient(kColorArray, false); glColor4f(1.0, 1.0, 1.0, 1.0); } int totalbatchcnt = 0; for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++) { int batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b]; btTransform boneworldbt[9]; if(m_animate) { for(int j = 0; j < batchcnt; ++j) { // Generates the world matrix for the given bone in this batch. PVRTMATRIX boneworld; int i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt]; m_model.GetBoneWorldMatrix(boneworld, *node, m_model.pNode[i32NodeID]); boneworldbt[j].setFromOpenGLMatrix(boneworld.f); } } totalbatchcnt += batchcnt; int offset = mesh->sBoneBatches.pnBatchOffset[b] * 3; int end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3; if(b == (mesh->sBoneBatches.nBatchCnt - 1)) end = mesh->nNumFaces*3; int numidx = (end - offset); for(int v = offset; v < end; v += 3) { unsigned short *idx = &indices[v]; float verts[3][3] = { 0.0 }; float uvs[3][2] = { 0.0 }; float weights[3][9] = { 0.0 }; unsigned char bones[3][9] = { 0 }; for(int a = 0; a < 3; a++) { float *meshverts = (float*) (mesh->pInterleaved + (long)mesh->sVertex.pData + mesh->sVertex.nStride * indices[v+a]); float *meshuvs = (float*) (mesh->pInterleaved + (long)mesh->psUVW->pData + mesh->psUVW->nStride * indices[v+a]); float *meshweights = (float *) (mesh->pInterleaved + (long)mesh->sBoneWeight.pData + mesh->sBoneWeight.nStride * indices[v+a]); unsigned char *meshbones = (unsigned char *) (mesh->pInterleaved + (long)mesh->sBoneIdx.pData + mesh->sBoneIdx.nStride * indices[v+a]); btVector3 temppos(0,0,0); uvs[a][0] = meshuvs[0]; uvs[a][1] = meshuvs[1]; for(unsigned int b = 0; b < mesh->sBoneIdx.n; b++) bones[a][b] = meshbones[b]; for(unsigned int w = 0; w < mesh->sBoneWeight.n; w++) { float weight = meshweights[w]; unsigned char boneidx = meshbones[w]; if(weight < 0.00001f) continue; btVector3 p(meshverts[0], meshverts[1], meshverts[2]); p = boneworldbt[boneidx] * p; p = p * weight; temppos += p; } verts[a][0] = temppos[0]; verts[a][1] = temppos[1]; verts[a][2] = temppos[2]; } glVertexPointer(3, GL_FLOAT, 0, verts); glTexCoordPointer(2, GL_FLOAT, 0, uvs); //glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, 0); glDrawArrays(GL_TRIANGLES, 0, 3); } } } #endif } <|endoftext|>
<commit_before>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "DispatchQueue.h" #include "at_exit.h" DispatchQueue::DispatchQueue(void): m_aborted(false), m_dispatchCap(1024) { m_waitPredicate = [this] { if(m_aborted) throw dispatch_aborted_exception(); return !m_dispatchQueue.empty() && m_dispatchQueue.front()->IsCommited(); }; } DispatchQueue::~DispatchQueue(void) { // Teardown: for(auto q = m_dispatchQueue.begin(); q != m_dispatchQueue.end(); q++) delete *q; } void DispatchQueue::Abort(void) { boost::lock_guard<boost::mutex> lk(m_dispatchLock); m_aborted = true; // Rip apart: for(auto q = m_dispatchQueue.begin(); q != m_dispatchQueue.end(); q++) delete *q; m_dispatchQueue.clear(); // Wake up anyone who is still waiting: m_queueUpdated.notify_all(); } void DispatchQueue::DispatchEventUnsafe(boost::unique_lock<boost::mutex>& lk) { DispatchThunkBase* thunk = m_dispatchQueue.front(); m_dispatchQueue.pop_front(); bool wasEmpty = m_dispatchQueue.empty(); lk.unlock(); auto generalCleanup = MakeAtExit( [this, thunk, wasEmpty] { delete thunk; // If we emptied the queue, we'd like to reobtain the lock and tell everyone // that the queue is now empty. if(wasEmpty) m_queueUpdated.notify_all(); } ); (*thunk)(); } void DispatchQueue::WaitForEvent(void) { boost::unique_lock<boost::mutex> lk(m_dispatchLock); if(m_aborted) throw dispatch_aborted_exception(); m_queueUpdated.wait(lk, m_waitPredicate); DispatchEventUnsafe(lk); } bool DispatchQueue::WaitForEvent(boost::chrono::duration<double, boost::milli> milliseconds) { boost::unique_lock<boost::mutex> lk(m_dispatchLock); if(m_aborted) throw dispatch_aborted_exception(); m_queueUpdated.wait_for(lk, milliseconds, m_waitPredicate); if(m_dispatchQueue.empty()) return false; DispatchEventUnsafe(lk); return true; } bool DispatchQueue::WaitForEvent(boost::chrono::steady_clock::time_point wakeTime) { if(wakeTime == boost::chrono::steady_clock::time_point::max()) // Maximal wait--we can optimize by using the zero-arguments version return WaitForEvent(), true; boost::unique_lock<boost::mutex> lk(m_dispatchLock); if(m_aborted) throw dispatch_aborted_exception(); m_queueUpdated.wait_until(lk, wakeTime, m_waitPredicate); if(m_dispatchQueue.empty()) return false; DispatchEventUnsafe(lk); return true; } bool DispatchQueue::DispatchEvent(void) { boost::unique_lock<boost::mutex> lk(m_dispatchLock); if(m_dispatchQueue.empty()) return false; DispatchEventUnsafe(lk); return true; } <commit_msg>Fixed failing autowiring test<commit_after>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "DispatchQueue.h" #include "at_exit.h" DispatchQueue::DispatchQueue(void): m_aborted(false), m_dispatchCap(1024) { m_waitPredicate = [this] { if(m_aborted) throw dispatch_aborted_exception(); return !m_dispatchQueue.empty() && m_dispatchQueue.front()->IsCommited(); }; } DispatchQueue::~DispatchQueue(void) { // Teardown: for(auto q = m_dispatchQueue.begin(); q != m_dispatchQueue.end(); q++) delete *q; } void DispatchQueue::Abort(void) { boost::lock_guard<boost::mutex> lk(m_dispatchLock); m_aborted = true; // Rip apart: for(auto q = m_dispatchQueue.begin(); q != m_dispatchQueue.end(); q++) delete *q; m_dispatchQueue.clear(); // Wake up anyone who is still waiting: m_queueUpdated.notify_all(); } void DispatchQueue::DispatchEventUnsafe(boost::unique_lock<boost::mutex>& lk) { DispatchThunkBase* thunk = m_dispatchQueue.front(); m_dispatchQueue.pop_front(); bool wasEmpty = m_dispatchQueue.empty(); lk.unlock(); auto generalCleanup = MakeAtExit( [this, thunk, wasEmpty] { delete thunk; // If we emptied the queue, we'd like to reobtain the lock and tell everyone // that the queue is now empty. if(wasEmpty) m_queueUpdated.notify_all(); } ); (*thunk)(); } void DispatchQueue::WaitForEvent(void) { boost::unique_lock<boost::mutex> lk(m_dispatchLock); if(m_aborted) throw dispatch_aborted_exception(); m_queueUpdated.wait(lk, m_waitPredicate); DispatchEventUnsafe(lk); } bool DispatchQueue::WaitForEvent(boost::chrono::duration<double, boost::milli> milliseconds) { boost::unique_lock<boost::mutex> lk(m_dispatchLock); if(m_aborted) throw dispatch_aborted_exception(); m_queueUpdated.wait_for(lk, milliseconds, m_waitPredicate); if(m_dispatchQueue.empty()) return false; DispatchEventUnsafe(lk); return true; } bool DispatchQueue::WaitForEvent(boost::chrono::steady_clock::time_point wakeTime) { if(wakeTime == boost::chrono::steady_clock::time_point::max()) // Maximal wait--we can optimize by using the zero-arguments version return WaitForEvent(), true; boost::unique_lock<boost::mutex> lk(m_dispatchLock); if(m_aborted) throw dispatch_aborted_exception(); m_queueUpdated.wait_until(lk, wakeTime, m_waitPredicate); if(m_dispatchQueue.empty()) return false; DispatchEventUnsafe(lk); return true; } bool DispatchQueue::DispatchEvent(void) { boost::unique_lock<boost::mutex> lk(m_dispatchLock); if(m_dispatchQueue.empty() || !m_dispatchQueue.front()->IsCommited()) return false; DispatchEventUnsafe(lk); return true; } <|endoftext|>
<commit_before>#include "LIBGPU.H" #include "EMULATOR.H" #define GL_GLEXT_PROTOTYPES 1 #include <SDL.h> #include <SDL_opengl.h> #include <SDL_opengl_glext.h> #include <stdio.h> #include <cstring> #include <cassert> #include <LIBETC.H> unsigned short vram[1024 * 512]; DISPENV word_33BC; int dword_3410 = 0; char byte_3352 = 0; void* off_3348[]= { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; int ClearImage(RECT16* rect, u_char r, u_char g, u_char b) { for (int y = rect->y; y < 512; y++) { for (int x = rect->x; x < 1024; x++) { unsigned short* pixel = vram + (y * 1024 + x); if (x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h) { pixel[0] = ((r >> 3) << 11) | ((g >> 3) << 6) | ((b >> 3) << 1) | 0; } } } return 0; } int DrawSync(int mode) { return 0; } int LoadImagePSX(RECT16* rect, u_long* p) { unsigned short* dst = (unsigned short*)p; for (int y = rect->y; y < 512; y++) { for (int x = rect->x; x < 1024; x++) { unsigned short* src = vram + (y * 1024 + x); if (x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h) { src[0] = *dst++; } } } #if _DEBUG FILE* f = fopen("VRAM.BIN", "wb"); fwrite(&vram[0], 1, 1024 * 512 * 2, f); fclose(f); #endif return 0; } int ResetGraph(int mode) { return 0; } int SetGraphDebug(int level) { return 0; } int StoreImage(RECT16 * RECT16, u_long * p) { return 0; } u_long * ClearOTag(u_long * ot, int n) { assert(0); return 0; } u_long* ClearOTagR(u_long* ot, int n) { //v0 = byte_3352; //s0 = ot //s1 = n //v0 = v0 < 2 ? 1 : 0 if (byte_3352 > 1) { ///GPU_printf("ClearOTagR(%08x,%d)...\n", ot, n); } //loc_CB0 // ((void*)off_3348[11])(); return 0; } void SetDispMask(int mask) { } DISPENV* GetDispEnv(DISPENV* env)//(F) { memcpy(env, &word_33BC, sizeof(DISPENV)); return env; } DISPENV* PutDispEnv(DISPENV* env)//To Finish { memcpy((char*)&word_33BC, env, sizeof(DISPENV)); return 0; } DISPENV* SetDefDispEnv(DISPENV* env, int x, int y, int w, int h)//(F) { env->disp.x = x; env->disp.y = y; env->disp.w = w; env->screen.x = 0; env->screen.y = 0; env->screen.w = 0; env->screen.h = 0; env->isrgb24 = 0; env->isinter = 0; env->pad1 = 0; env->pad0 = 0; env->disp.h = h; return 0; } DRAWENV* PutDrawEnv(DRAWENV* env) { return NULL; } DRAWENV* SetDefDrawEnv(DRAWENV* env, int x, int y, int w, int h)//(F) { env->clip.x = x; env->clip.y = y; env->clip.w = w; env->tw.x = 0; env->tw.y = 0; env->tw.w = 0; env->tw.h = 0; env->r0 = 0; env->g0 = 0; env->b0 = 0; env->dtd = 1; env->clip.h = h; if (GetVideoMode() == 0) { env->dfe = h < 0x121 ? 1 : 0; } else { env->dfe = h < 0x101 ? 1 : 0; } env->ofs[0] = x; env->ofs[1] = y; env->tpage = 10; env->isbg = 0; return env; } u_long DrawSyncCallback(void(*func)(void)) { return u_long(); } void DrawOTagEnv(u_long* p, DRAWENV* env) { printf("Debug"); } <commit_msg>ClearImage correct argb values. Fixes transparency.<commit_after>#include "LIBGPU.H" #include "EMULATOR.H" #define GL_GLEXT_PROTOTYPES 1 #include <SDL.h> #include <SDL_opengl.h> #include <SDL_opengl_glext.h> #include <stdio.h> #include <cstring> #include <cassert> #include <LIBETC.H> unsigned short vram[1024 * 512]; DISPENV word_33BC; int dword_3410 = 0; char byte_3352 = 0; void* off_3348[]= { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; int ClearImage(RECT16* rect, u_char r, u_char g, u_char b) { for (int y = rect->y; y < 512; y++) { for (int x = rect->x; x < 1024; x++) { unsigned short* pixel = vram + (y * 1024 + x); if (x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h) { pixel[0] = 1 << 15 | ((r >> 3) << 10) | ((g >> 3) << 5) | ((b >> 3)); } } } return 0; } int DrawSync(int mode) { return 0; } int LoadImagePSX(RECT16* rect, u_long* p) { unsigned short* dst = (unsigned short*)p; for (int y = rect->y; y < 512; y++) { for (int x = rect->x; x < 1024; x++) { unsigned short* src = vram + (y * 1024 + x); if (x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h) { src[0] = *dst++; //pixel[0] = 1 << 15 | ((r >> 3) << 10) | ((g >> 3) << 5) | ((b >> 3)); } } } #if _DEBUG FILE* f = fopen("VRAM.BIN", "wb"); fwrite(&vram[0], 1, 1024 * 512 * 2, f); fclose(f); #endif return 0; } int ResetGraph(int mode) { return 0; } int SetGraphDebug(int level) { return 0; } int StoreImage(RECT16 * RECT16, u_long * p) { return 0; } u_long * ClearOTag(u_long * ot, int n) { assert(0); return 0; } u_long* ClearOTagR(u_long* ot, int n) { //v0 = byte_3352; //s0 = ot //s1 = n //v0 = v0 < 2 ? 1 : 0 if (byte_3352 > 1) { ///GPU_printf("ClearOTagR(%08x,%d)...\n", ot, n); } //loc_CB0 // ((void*)off_3348[11])(); return 0; } void SetDispMask(int mask) { } DISPENV* GetDispEnv(DISPENV* env)//(F) { memcpy(env, &word_33BC, sizeof(DISPENV)); return env; } DISPENV* PutDispEnv(DISPENV* env)//To Finish { memcpy((char*)&word_33BC, env, sizeof(DISPENV)); return 0; } DISPENV* SetDefDispEnv(DISPENV* env, int x, int y, int w, int h)//(F) { env->disp.x = x; env->disp.y = y; env->disp.w = w; env->screen.x = 0; env->screen.y = 0; env->screen.w = 0; env->screen.h = 0; env->isrgb24 = 0; env->isinter = 0; env->pad1 = 0; env->pad0 = 0; env->disp.h = h; return 0; } DRAWENV* PutDrawEnv(DRAWENV* env) { return NULL; } DRAWENV* SetDefDrawEnv(DRAWENV* env, int x, int y, int w, int h)//(F) { env->clip.x = x; env->clip.y = y; env->clip.w = w; env->tw.x = 0; env->tw.y = 0; env->tw.w = 0; env->tw.h = 0; env->r0 = 0; env->g0 = 0; env->b0 = 0; env->dtd = 1; env->clip.h = h; if (GetVideoMode() == 0) { env->dfe = h < 0x121 ? 1 : 0; } else { env->dfe = h < 0x101 ? 1 : 0; } env->ofs[0] = x; env->ofs[1] = y; env->tpage = 10; env->isbg = 0; return env; } u_long DrawSyncCallback(void(*func)(void)) { return u_long(); } void DrawOTagEnv(u_long* p, DRAWENV* env) { printf("Debug"); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 * */ #include <QtTest/QtTest> #include <QtCore> #include "contextpropertyinfo.h" #include "infobackend.h" QMap <QString, QString> constructionStringMap; QMap <QString, QString> typeMap; QMap <QString, QString> docMap; QMap <QString, QString> pluginMap; QMap <QString, bool> providedMap; /* Mocked infobackend */ InfoBackend* currentBackend = NULL; InfoBackend* InfoBackend::instance(const QString &backendName) { if (currentBackend) return currentBackend; else { currentBackend = new InfoBackend(); return currentBackend; } } QString InfoBackend::constructionStringForKey(QString key) const { if (constructionStringMap.contains(key)) return constructionStringMap.value(key); else return QString(); } QString InfoBackend::typeForKey(QString key) const { if (typeMap.contains(key)) return typeMap.value(key); else return QString(); } QString InfoBackend::docForKey(QString key) const { if (docMap.contains(key)) return docMap.value(key); else return QString(); } QString InfoBackend::pluginForKey(QString key) const { if (pluginMap.contains(key)) return pluginMap.value(key); else return QString(); } bool InfoBackend::keyExists(QString key) const { if (typeMap.contains(key)) return true; else return false; } bool InfoBackend::keyProvided(QString key) const { if (providedMap.contains(key)) return providedMap.value(key); else return false; } void InfoBackend::connectNotify(const char *signal) { } void InfoBackend::disconnectNotify(const char *signal) { } void InfoBackend::fireKeysChanged(const QStringList& keys) { emit keysChanged(keys); } void InfoBackend::fireKeysAdded(const QStringList& keys) { emit keysAdded(keys); } void InfoBackend::fireKeysRemoved(const QStringList& keys) { emit keysRemoved(keys); } void InfoBackend::fireKeyDataChanged(const QString& key) { emit keyDataChanged(key); } /* ContextRegistryInfoUnitTest */ class ContextPropertyInfoUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void key(); void doc(); void type(); void exists(); void provided(); void providerDBusName(); void providerDBusType(); void plugin(); void constructionString(); void typeChanged(); }; void ContextPropertyInfoUnitTest::initTestCase() { constructionStringMap.clear(); constructionStringMap.insert("Battery.Charging", "system:org.freedesktop.ContextKit.contextd"); constructionStringMap.insert("Media.NowPlaying", "session:com.nokia.musicplayer"); typeMap.clear(); typeMap.insert("Battery.Charging", "TRUTH"); typeMap.insert("Media.NowPlaying", "STRING"); docMap.clear(); docMap.insert("Battery.Charging", "Battery.Charging doc"); docMap.insert("Media.NowPlaying", "Media.NowPlaying doc"); pluginMap.clear(); pluginMap.insert("Battery.Charging", "contextkit-dbus"); pluginMap.insert("Media.NowPlaying", "contextkit-dbus"); providedMap.clear(); providedMap.insert("Battery.Charging", true); providedMap.insert("Media.NowPlaying", true); } void ContextPropertyInfoUnitTest::key() { ContextPropertyInfo p("Battery.Charging"); QCOMPARE(p.key(), QString("Battery.Charging")); } void ContextPropertyInfoUnitTest::doc() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.doc(), QString("Battery.Charging doc")); QCOMPARE(p2.doc(), QString("Media.NowPlaying doc")); QCOMPARE(p3.doc(), QString()); } void ContextPropertyInfoUnitTest::type() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.type(), QString("TRUTH")); QCOMPARE(p2.type(), QString("STRING")); QCOMPARE(p3.type(), QString()); } void ContextPropertyInfoUnitTest::exists() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.exists(), true); QCOMPARE(p2.exists(), true); QCOMPARE(p3.exists(), false); } void ContextPropertyInfoUnitTest::provided() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.provided(), true); QCOMPARE(p2.provided(), true); QCOMPARE(p3.provided(), false); } void ContextPropertyInfoUnitTest::providerDBusName() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.providerDBusName(), QString("org.freedesktop.ContextKit.contextd")); QCOMPARE(p2.providerDBusName(), QString("com.nokia.musicplayer")); QCOMPARE(p3.providerDBusName(), QString()); } void ContextPropertyInfoUnitTest::providerDBusType() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.providerDBusType(), QDBusConnection::SystemBus); QCOMPARE(p2.providerDBusType(), QDBusConnection::SessionBus); QCOMPARE(p3.providerDBusType(), QDBusConnection::SessionBus); } void ContextPropertyInfoUnitTest::plugin() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.plugin(), QString("contextkit-dbus")); QCOMPARE(p2.plugin(), QString("contextkit-dbus")); QCOMPARE(p3.plugin(), QString()); } void ContextPropertyInfoUnitTest::constructionString() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.constructionString(), QString("system:org.freedesktop.ContextKit.contextd")); QCOMPARE(p2.constructionString(), QString("session:com.nokia.musicplayer")); QCOMPARE(p3.constructionString(), QString()); } void ContextPropertyInfoUnitTest::typeChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(typeChanged(QString))); currentBackend->fireKeyDataChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 0); typeMap.insert("Battery.Charging", "INT"); currentBackend->fireKeyDataChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), QString("INT")); } #include "contextpropertyinfounittest.moc" QTEST_MAIN(ContextPropertyInfoUnitTest); <commit_msg>providerChanged.<commit_after>/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 * */ #include <QtTest/QtTest> #include <QtCore> #include "contextpropertyinfo.h" #include "infobackend.h" QMap <QString, QString> constructionStringMap; QMap <QString, QString> typeMap; QMap <QString, QString> docMap; QMap <QString, QString> pluginMap; QMap <QString, bool> providedMap; /* Mocked infobackend */ InfoBackend* currentBackend = NULL; InfoBackend* InfoBackend::instance(const QString &backendName) { if (currentBackend) return currentBackend; else { currentBackend = new InfoBackend(); return currentBackend; } } QString InfoBackend::constructionStringForKey(QString key) const { if (constructionStringMap.contains(key)) return constructionStringMap.value(key); else return QString(); } QString InfoBackend::typeForKey(QString key) const { if (typeMap.contains(key)) return typeMap.value(key); else return QString(); } QString InfoBackend::docForKey(QString key) const { if (docMap.contains(key)) return docMap.value(key); else return QString(); } QString InfoBackend::pluginForKey(QString key) const { if (pluginMap.contains(key)) return pluginMap.value(key); else return QString(); } bool InfoBackend::keyExists(QString key) const { if (typeMap.contains(key)) return true; else return false; } bool InfoBackend::keyProvided(QString key) const { if (providedMap.contains(key)) return providedMap.value(key); else return false; } void InfoBackend::connectNotify(const char *signal) { } void InfoBackend::disconnectNotify(const char *signal) { } void InfoBackend::fireKeysChanged(const QStringList& keys) { emit keysChanged(keys); } void InfoBackend::fireKeysAdded(const QStringList& keys) { emit keysAdded(keys); } void InfoBackend::fireKeysRemoved(const QStringList& keys) { emit keysRemoved(keys); } void InfoBackend::fireKeyDataChanged(const QString& key) { emit keyDataChanged(key); } /* ContextRegistryInfoUnitTest */ class ContextPropertyInfoUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void key(); void doc(); void type(); void exists(); void provided(); void providerDBusName(); void providerDBusType(); void plugin(); void constructionString(); void typeChanged(); void providerChanged(); }; void ContextPropertyInfoUnitTest::initTestCase() { constructionStringMap.clear(); constructionStringMap.insert("Battery.Charging", "system:org.freedesktop.ContextKit.contextd"); constructionStringMap.insert("Media.NowPlaying", "session:com.nokia.musicplayer"); typeMap.clear(); typeMap.insert("Battery.Charging", "TRUTH"); typeMap.insert("Media.NowPlaying", "STRING"); docMap.clear(); docMap.insert("Battery.Charging", "Battery.Charging doc"); docMap.insert("Media.NowPlaying", "Media.NowPlaying doc"); pluginMap.clear(); pluginMap.insert("Battery.Charging", "contextkit-dbus"); pluginMap.insert("Media.NowPlaying", "contextkit-dbus"); providedMap.clear(); providedMap.insert("Battery.Charging", true); providedMap.insert("Media.NowPlaying", true); } void ContextPropertyInfoUnitTest::key() { ContextPropertyInfo p("Battery.Charging"); QCOMPARE(p.key(), QString("Battery.Charging")); } void ContextPropertyInfoUnitTest::doc() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.doc(), QString("Battery.Charging doc")); QCOMPARE(p2.doc(), QString("Media.NowPlaying doc")); QCOMPARE(p3.doc(), QString()); } void ContextPropertyInfoUnitTest::type() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.type(), QString("TRUTH")); QCOMPARE(p2.type(), QString("STRING")); QCOMPARE(p3.type(), QString()); } void ContextPropertyInfoUnitTest::exists() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.exists(), true); QCOMPARE(p2.exists(), true); QCOMPARE(p3.exists(), false); } void ContextPropertyInfoUnitTest::provided() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.provided(), true); QCOMPARE(p2.provided(), true); QCOMPARE(p3.provided(), false); } void ContextPropertyInfoUnitTest::providerDBusName() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.providerDBusName(), QString("org.freedesktop.ContextKit.contextd")); QCOMPARE(p2.providerDBusName(), QString("com.nokia.musicplayer")); QCOMPARE(p3.providerDBusName(), QString()); } void ContextPropertyInfoUnitTest::providerDBusType() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.providerDBusType(), QDBusConnection::SystemBus); QCOMPARE(p2.providerDBusType(), QDBusConnection::SessionBus); QCOMPARE(p3.providerDBusType(), QDBusConnection::SessionBus); } void ContextPropertyInfoUnitTest::plugin() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.plugin(), QString("contextkit-dbus")); QCOMPARE(p2.plugin(), QString("contextkit-dbus")); QCOMPARE(p3.plugin(), QString()); } void ContextPropertyInfoUnitTest::constructionString() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.constructionString(), QString("system:org.freedesktop.ContextKit.contextd")); QCOMPARE(p2.constructionString(), QString("session:com.nokia.musicplayer")); QCOMPARE(p3.constructionString(), QString()); } void ContextPropertyInfoUnitTest::typeChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(typeChanged(QString))); currentBackend->fireKeyDataChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 0); typeMap.insert("Battery.Charging", "INT"); currentBackend->fireKeyDataChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), QString("INT")); } void ContextPropertyInfoUnitTest::providerChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(providerChanged(QString))); currentBackend->fireKeyDataChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 0); constructionStringMap.insert("Battery.Charging", "system:org.freedesktop.ContextKit.robot"); currentBackend->fireKeyDataChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), QString("org.freedesktop.ContextKit.robot")); } #include "contextpropertyinfounittest.moc" QTEST_MAIN(ContextPropertyInfoUnitTest); <|endoftext|>
<commit_before>#pragma once #include <string> #include <iostream> #include <sstream> #include <tuple> /* TODO All char types to be handled correctly. More succint dispatch for char types, possibly SFINAE-based. Principled, typeclass-like way to extend show. */ namespace show{ template<typename T> std::string show(const T& t); namespace _dtl { template<typename T> constexpr bool expand_to_false(){return false;} template<std::size_t> struct Nat{}; template<typename...> struct TypeList{}; template<typename T> using IsIterable = TypeList<decltype(std::begin(T{})), decltype(std::end(T{})), decltype(++std::begin(T{})), decltype(*std::begin(T{})), decltype(std::begin(T{}) != std::end(T{}))>; template<typename T> using IsTrivial = decltype(std::stringstream{}.operator<<(T{})); struct Iterable; struct Trivial; struct Undefined; struct Tuple; struct Pair; struct String; struct Char; template<typename T> struct GetFormat{ template<typename, typename = IsTrivial<T>> static Trivial check(void*); template<typename, typename = IsIterable<T>> static Iterable check(void*); template<typename> static Undefined check(...); using type = decltype(check<T>(nullptr)); }; template<typename A, typename B> struct GetFormat<std::pair<A, B>> {using type = Pair;}; template<typename... TS> struct GetFormat<std::tuple<TS...>> {using type = Tuple;}; template<typename C, typename T, typename A> struct GetFormat<std::basic_string<C, T, A>> {using type = String;}; template<typename T, size_t N> struct GetFormat<T[N]> {using type = Iterable;}; template<size_t N> struct GetFormat<char[N]> {using type = String;}; template<> struct GetFormat<const char*> {using type = String;}; template<> struct GetFormat<char*> {using type = String;}; template<> struct GetFormat<char> {using type = Char;}; struct Iterable{ template<typename T> std::string operator()(const T& t){ std::string res{}; auto it = std::begin(t); auto finish = std::end(t); res += "["; if (it != finish){ res += show(*it); ++it; for (;it != finish; ++it){ res += ", "; res += show(*it); } } res += "]"; return res; } }; struct Trivial{ template<typename T> std::string operator()(const T& t){ std::stringstream fmt{}; fmt.operator<<(t); return fmt.str(); } }; struct String{ template<typename T> std::string operator()(const T& t){ return "\"" + std::string(t) + "\""; } }; struct Pair{ template<typename A, typename B> std::string operator()(const std::pair<A, B>& p){ return "(" + show(p.first) + ", " + show(p.second) + ")"; } }; struct Tuple{ template <typename... TS> std::string operator()(const std::tuple<TS...>& tpl) { std::string res{}; res += "("; helper(res, tpl, Nat<sizeof...(TS) - 1>{}); res += ")"; return res; } template<typename T, std::size_t N> void helper(std::string& res, const T &tpl, Nat<N>){ helper(res, tpl, Nat<N-1>{}); res += ", "; res += show(std::get<N>(tpl)); } template<typename T> void helper(std::string& res, const T &tpl, Nat<0>){ res += show(std::get<0>(tpl)); } }; struct Char{ template<typename T> std::string operator()(const T& t){ return std::string("'") + t + '\''; } }; struct Undefined{ template<typename T> std::string operator()(const T&){ static_assert(expand_to_false<T>(), "Show undefined for type."); return ""; } }; } // namespace _dtl template<typename T> std::string show(const T& t){ return typename _dtl::GetFormat<T>::type{}(t); } void print(){ std::cout << std::endl; } template<typename T, typename... TS> void print(const T& t, const TS&... ts){ std::cout << show(t) << ' '; print(ts...); } } // namespace show <commit_msg>fixed sfinae on dispatch<commit_after>#pragma once #include <string> #include <iostream> #include <sstream> #include <tuple> /* TODO All char types to be handled correctly. More succint dispatch for char types, probably SFINAE-based. */ namespace show{ template<typename T> std::string show(const T& t); namespace _dtl { template<typename T> constexpr bool expand_to_false(){return false;} template<std::size_t> struct Nat{}; template<typename...> struct TypeList{}; template<typename T> using IsIterable = TypeList<decltype(std::begin(T{})), decltype(std::end(T{})), decltype(++std::begin(T{})), decltype(*std::begin(T{})), decltype(std::begin(T{}) != std::end(T{}))>; template<typename T> using IsTrivial = decltype(std::stringstream{}.operator<<(T{})); struct Iterable; struct Trivial; struct Undefined; struct Tuple; struct Pair; struct String; struct Char; template<typename T> struct GetFormat{ template<typename U, typename = IsTrivial<U>> static Trivial check(void*); template<typename U, typename = IsIterable<U>> static Iterable check(void*); template<typename> static Undefined check(...); using type = decltype(check<T>(nullptr)); }; template<typename A, typename B> struct GetFormat<std::pair<A, B>> {using type = Pair;}; template<typename... TS> struct GetFormat<std::tuple<TS...>> {using type = Tuple;}; template<typename C, typename T, typename A> struct GetFormat<std::basic_string<C, T, A>> {using type = String;}; template<typename T, size_t N> struct GetFormat<T[N]> {using type = Iterable;}; template<size_t N> struct GetFormat<char[N]> {using type = String;}; template<> struct GetFormat<const char*> {using type = String;}; template<> struct GetFormat<char*> {using type = String;}; template<> struct GetFormat<char> {using type = Char;}; struct Iterable{ template<typename T> std::string operator()(const T& t){ std::string res{}; auto it = std::begin(t); auto finish = std::end(t); res += "["; if (it != finish){ res += show(*it); ++it; for (;it != finish; ++it){ res += ", "; res += show(*it); } } res += "]"; return res; } }; struct Trivial{ template<typename T> std::string operator()(const T& t){ std::stringstream fmt{}; fmt.operator<<(t); return fmt.str(); } }; struct String{ template<typename T> std::string operator()(const T& t){ return "\"" + std::string(t) + "\""; } }; struct Pair{ template<typename A, typename B> std::string operator()(const std::pair<A, B>& p){ return "(" + show(p.first) + ", " + show(p.second) + ")"; } }; struct Tuple{ template <typename... TS> std::string operator()(const std::tuple<TS...>& tpl) { std::string res{}; res += "("; helper(res, tpl, Nat<sizeof...(TS) - 1>{}); res += ")"; return res; } template<typename T, std::size_t N> void helper(std::string& res, const T &tpl, Nat<N>){ helper(res, tpl, Nat<N-1>{}); res += ", "; res += show(std::get<N>(tpl)); } template<typename T> void helper(std::string& res, const T &tpl, Nat<0>){ res += show(std::get<0>(tpl)); } }; struct Char{ template<typename T> std::string operator()(const T& t){ return std::string("'") + t + '\''; } }; struct Undefined{ template<typename T> std::string operator()(const T&){ static_assert(expand_to_false<T>(), "Show undefined for type."); return ""; } }; } // namespace _dtl template<typename T> std::string show(const T& t){ return typename _dtl::GetFormat<T>::type{}(t); } void print(){ std::cout << std::endl; } template<typename T, typename... TS> void print(const T& t, const TS&... ts){ std::cout << show(t) << ' '; print(ts...); } } // namespace show <|endoftext|>
<commit_before>/* Copyright 2017 QReal Research Group * * 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 "pioneerLuaMasterGenerator.h" #include <QtCore/QDir> #include <qrkernel/logging.h> #include <qrkernel/exception/exception.h> #include <qrtext/languageToolboxInterface.h> #include <qrutils/stringUtils.h> #include <generatorBase/parts/initTerminateCodeGenerator.h> #include <generatorBase/gotoControlFlowGenerator.h> #include <generatorBase/parts/subprograms.h> #include <generatorBase/parts/threads.h> #include <generatorBase/parts/variables.h> #include "pioneerLuaGeneratorCustomizer.h" #include "pioneerLuaGeneratorFactory.h" #include "generators/pioneerStateMachineGenerator.h" #include "generators/gotoLabelManager.h" #include "generators/randomFunctionChecker.h" using namespace pioneer::lua; using namespace generatorBase; using namespace qReal; PioneerLuaMasterGenerator::PioneerLuaMasterGenerator(const qrRepo::RepoApi &repo , qReal::ErrorReporterInterface &errorReporter , const utils::ParserErrorReporter &parserErrorReporter , const kitBase::robotModel::RobotModelManagerInterface &robotModelManager , qrtext::LanguageToolboxInterface &textLanguage , const qReal::Id &diagramId , const QString &generatorName , const qReal::EditorManagerInterface &metamodel) : MasterGeneratorBase(repo, errorReporter, robotModelManager, textLanguage, parserErrorReporter, diagramId) , mGeneratorName(generatorName) , mMetamodel(metamodel) , mGotoLabelManager(new GotoLabelManager()) { } PioneerLuaMasterGenerator::~PioneerLuaMasterGenerator() { // Empty destructor to keep QScopedPointer happy. } void PioneerLuaMasterGenerator::initialize() { MasterGeneratorBase::initialize(); mControlFlowGenerator.reset( new PioneerStateMachineGenerator(mRepo, mErrorReporter, *mCustomizer, *mValidator, mDiagram) ); auto factory = dynamic_cast<PioneerLuaGeneratorFactory *>(mCustomizer->factory()); if (!factory) { throw qReal::Exception("PioneerLuaMasterGenerator shall work only with PioneerLuaGeneratorFactory"); } mRandomFunctionChecker.reset( new RandomFunctionChecker(mRepo, mMetamodel, mTextLanguage, factory->randomGeneratorPart())); mControlFlowGenerator->registerNodeHook([this](const qReal::Id &id){ mRandomFunctionChecker->checkNode(id); }); } generatorBase::GeneratorCustomizer *PioneerLuaMasterGenerator::createCustomizer() { return new PioneerLuaGeneratorCustomizer( mRepo , mErrorReporter , mRobotModelManager , *createLuaProcessor() , mGeneratorName , *mGotoLabelManager); } QString PioneerLuaMasterGenerator::targetPath() { return QString("%1/%2.lua").arg(mProjectDir, mProjectName); } bool PioneerLuaMasterGenerator::supportsGotoGeneration() const { return true; } void PioneerLuaMasterGenerator::beforeGeneration() { QDir().mkpath(mProjectDir + "/ap/"); QDir().mkpath(mProjectDir + "/Ev/"); QFile::copy(":/pioneer/lua/templates/testStub/ap/lua.lua", mProjectDir + "/ap/lua.lua"); QFile::copy(":/pioneer/lua/templates/testStub/Ev/lua.lua", mProjectDir + "/Ev/lua.lua"); } QString PioneerLuaMasterGenerator::generate(const QString &indentString) { if (mDiagram.isNull()) { mErrorReporter.addCritical(QObject::tr("There is no opened diagram")); return QString(); } QLOG_INFO() << "Starting Pioneer program generation to " << mProjectDir; mGotoLabelManager->reinit(); beforeGeneration(); if (!QDir(mProjectDir).exists()) { QDir().mkpath(mProjectDir); } mTextLanguage.clear(); mCustomizer->factory()->setMainDiagramId(mDiagram); for (parts::InitTerminateCodeGenerator *generator : mCustomizer->factory()->initTerminateGenerators()) { generator->reinit(); } QString mainCode; const semantics::SemanticTree *mainControlFlow = mControlFlowGenerator->generate(); if (mainControlFlow) { mainCode = mainControlFlow->toString(0, indentString); const parts::Subprograms::GenerationResult subprogramsResult = mCustomizer->factory() ->subprograms()->generate(mControlFlowGenerator.data(), indentString); if (subprogramsResult != parts::Subprograms::GenerationResult::success) { mainCode = QString(); } } if (mainCode.isEmpty()) { const QString errorMessage = tr("Generation failed. Possible causes are internal error in generator or too " "complex program structure."); mErrorReporter.addError(errorMessage); return QString(); } QString resultCode = readTemplate("main.t"); replaceWithAutoIndent(resultCode, "@@SUBPROGRAMS_FORWARDING@@" , mCustomizer->factory()->subprograms()->forwardDeclarations()); replaceWithAutoIndent(resultCode, "@@SUBPROGRAMS@@" , mCustomizer->factory()->subprograms()->implementations()); replaceWithAutoIndent(resultCode, "@@THREADS_FORWARDING@@" , mCustomizer->factory()->threads().generateDeclarations()); replaceWithAutoIndent(resultCode, "@@THREADS@@" , mCustomizer->factory()->threads().generateImplementations(indentString)); replaceWithAutoIndent(resultCode, "@@MAIN_CODE@@", mainCode); replaceWithAutoIndent(resultCode, "@@INITHOOKS@@", mCustomizer->factory()->initCode()); replaceWithAutoIndent(resultCode, "@@TERMINATEHOOKS@@", utils::StringUtils::addIndent( mCustomizer->factory()->terminateCode(), 1, indentString)); replaceWithAutoIndent(resultCode, "@@USERISRHOOKS@@", utils::StringUtils::addIndent( mCustomizer->factory()->isrHooksCode(), 1, indentString)); const QString constantsString = mCustomizer->factory()->variables()->generateConstantsString(); const QString variablesString = mCustomizer->factory()->variables()->generateVariableString(); if (resultCode.contains("@@CONSTANTS@@")) { replaceWithAutoIndent(resultCode, "@@CONSTANTS@@", constantsString); replaceWithAutoIndent(resultCode, "@@VARIABLES@@", variablesString); } else { replaceWithAutoIndent(resultCode, "@@VARIABLES@@", constantsString + "\n" + variablesString); } // This will remove too many empty lines resultCode.replace(QRegExp("\n(\n)+"), "\n\n"); processGeneratedCode(resultCode); generateLinkingInfo(resultCode); const QString pathToOutput = targetPath(); outputCode(pathToOutput, resultCode); afterGeneration(); return pathToOutput; } <commit_msg>Removed leading line breaks<commit_after>/* Copyright 2017 QReal Research Group * * 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 "pioneerLuaMasterGenerator.h" #include <QtCore/QDir> #include <qrkernel/logging.h> #include <qrkernel/exception/exception.h> #include <qrtext/languageToolboxInterface.h> #include <qrutils/stringUtils.h> #include <generatorBase/parts/initTerminateCodeGenerator.h> #include <generatorBase/gotoControlFlowGenerator.h> #include <generatorBase/parts/subprograms.h> #include <generatorBase/parts/threads.h> #include <generatorBase/parts/variables.h> #include "pioneerLuaGeneratorCustomizer.h" #include "pioneerLuaGeneratorFactory.h" #include "generators/pioneerStateMachineGenerator.h" #include "generators/gotoLabelManager.h" #include "generators/randomFunctionChecker.h" using namespace pioneer::lua; using namespace generatorBase; using namespace qReal; PioneerLuaMasterGenerator::PioneerLuaMasterGenerator(const qrRepo::RepoApi &repo , qReal::ErrorReporterInterface &errorReporter , const utils::ParserErrorReporter &parserErrorReporter , const kitBase::robotModel::RobotModelManagerInterface &robotModelManager , qrtext::LanguageToolboxInterface &textLanguage , const qReal::Id &diagramId , const QString &generatorName , const qReal::EditorManagerInterface &metamodel) : MasterGeneratorBase(repo, errorReporter, robotModelManager, textLanguage, parserErrorReporter, diagramId) , mGeneratorName(generatorName) , mMetamodel(metamodel) , mGotoLabelManager(new GotoLabelManager()) { } PioneerLuaMasterGenerator::~PioneerLuaMasterGenerator() { // Empty destructor to keep QScopedPointer happy. } void PioneerLuaMasterGenerator::initialize() { MasterGeneratorBase::initialize(); mControlFlowGenerator.reset( new PioneerStateMachineGenerator(mRepo, mErrorReporter, *mCustomizer, *mValidator, mDiagram) ); auto factory = dynamic_cast<PioneerLuaGeneratorFactory *>(mCustomizer->factory()); if (!factory) { throw qReal::Exception("PioneerLuaMasterGenerator shall work only with PioneerLuaGeneratorFactory"); } mRandomFunctionChecker.reset( new RandomFunctionChecker(mRepo, mMetamodel, mTextLanguage, factory->randomGeneratorPart())); mControlFlowGenerator->registerNodeHook([this](const qReal::Id &id){ mRandomFunctionChecker->checkNode(id); }); } generatorBase::GeneratorCustomizer *PioneerLuaMasterGenerator::createCustomizer() { return new PioneerLuaGeneratorCustomizer( mRepo , mErrorReporter , mRobotModelManager , *createLuaProcessor() , mGeneratorName , *mGotoLabelManager); } QString PioneerLuaMasterGenerator::targetPath() { return QString("%1/%2.lua").arg(mProjectDir, mProjectName); } bool PioneerLuaMasterGenerator::supportsGotoGeneration() const { return true; } void PioneerLuaMasterGenerator::beforeGeneration() { QDir().mkpath(mProjectDir + "/ap/"); QDir().mkpath(mProjectDir + "/Ev/"); QFile::copy(":/pioneer/lua/templates/testStub/ap/lua.lua", mProjectDir + "/ap/lua.lua"); QFile::copy(":/pioneer/lua/templates/testStub/Ev/lua.lua", mProjectDir + "/Ev/lua.lua"); } QString PioneerLuaMasterGenerator::generate(const QString &indentString) { if (mDiagram.isNull()) { mErrorReporter.addCritical(QObject::tr("There is no opened diagram")); return QString(); } QLOG_INFO() << "Starting Pioneer program generation to " << mProjectDir; mGotoLabelManager->reinit(); beforeGeneration(); if (!QDir(mProjectDir).exists()) { QDir().mkpath(mProjectDir); } mTextLanguage.clear(); mCustomizer->factory()->setMainDiagramId(mDiagram); for (parts::InitTerminateCodeGenerator *generator : mCustomizer->factory()->initTerminateGenerators()) { generator->reinit(); } QString mainCode; const semantics::SemanticTree *mainControlFlow = mControlFlowGenerator->generate(); if (mainControlFlow) { mainCode = mainControlFlow->toString(0, indentString); const parts::Subprograms::GenerationResult subprogramsResult = mCustomizer->factory() ->subprograms()->generate(mControlFlowGenerator.data(), indentString); if (subprogramsResult != parts::Subprograms::GenerationResult::success) { mainCode = QString(); } } if (mainCode.isEmpty()) { const QString errorMessage = tr("Generation failed. Possible causes are internal error in generator or too " "complex program structure."); mErrorReporter.addError(errorMessage); return QString(); } QString resultCode = readTemplate("main.t"); replaceWithAutoIndent(resultCode, "@@SUBPROGRAMS_FORWARDING@@" , mCustomizer->factory()->subprograms()->forwardDeclarations()); replaceWithAutoIndent(resultCode, "@@SUBPROGRAMS@@" , mCustomizer->factory()->subprograms()->implementations()); replaceWithAutoIndent(resultCode, "@@THREADS_FORWARDING@@" , mCustomizer->factory()->threads().generateDeclarations()); replaceWithAutoIndent(resultCode, "@@THREADS@@" , mCustomizer->factory()->threads().generateImplementations(indentString)); replaceWithAutoIndent(resultCode, "@@MAIN_CODE@@", mainCode); replaceWithAutoIndent(resultCode, "@@INITHOOKS@@", mCustomizer->factory()->initCode()); replaceWithAutoIndent(resultCode, "@@TERMINATEHOOKS@@", utils::StringUtils::addIndent( mCustomizer->factory()->terminateCode(), 1, indentString)); replaceWithAutoIndent(resultCode, "@@USERISRHOOKS@@", utils::StringUtils::addIndent( mCustomizer->factory()->isrHooksCode(), 1, indentString)); const QString constantsString = mCustomizer->factory()->variables()->generateConstantsString(); const QString variablesString = mCustomizer->factory()->variables()->generateVariableString(); if (resultCode.contains("@@CONSTANTS@@")) { replaceWithAutoIndent(resultCode, "@@CONSTANTS@@", constantsString); replaceWithAutoIndent(resultCode, "@@VARIABLES@@", variablesString); } else { replaceWithAutoIndent(resultCode, "@@VARIABLES@@", constantsString + "\n" + variablesString); } // This will remove too many empty lines resultCode.replace(QRegExp("\n(\n)+"), "\n\n"); // This will remove leading and trailing whitespaces, line breaks and other unneeded stuff. resultCode = resultCode.trimmed(); processGeneratedCode(resultCode); generateLinkingInfo(resultCode); const QString pathToOutput = targetPath(); outputCode(pathToOutput, resultCode); afterGeneration(); return pathToOutput; } <|endoftext|>
<commit_before>#include <TF3.h> #include <TTree.h> #include <TStyle.h> #include <TStopwatch.h> #include "X.h" #include "Units.h" using namespace GeFiCa; X::X(int nx, const char *name, const char *title) : TNamed(name,title), V0(0), V1(2e3*volt), MaxIterations(5000), Nsor(0), Csor(1.95), Precision(1e-7*volt), fN(nx), fN1(nx), fN2(0), fN3(0) { if (fN<10) { Warning("X","fN<10, set it to 11"); fN=11; fN1=11; } fV=new double[fN]; fE1=new double[fN]; fE2=new double[fN]; fE3=new double[fN]; fC1=new double[fN]; fC2=new double[fN]; fC3=new double[fN]; fdC1p=new double[fN]; fdC1m=new double[fN]; fdC2p=new double[fN]; fdC2m=new double[fN]; fdC3p=new double[fN]; fdC3m=new double[fN]; fIsFixed=new bool[fN]; fIsDepleted=new bool[fN]; fImpurity=new double[fN]; for (int i=0;i<fN;i++) { fV[i]=0; fE1[i]=0; fE2[i]=0; fE3[i]=0; fC1[i]=0; fC2[i]=0; fC3[i]=0; fdC1m[i]=0; fdC1p[i]=0; fdC2m[i]=0; fdC2p[i]=0; fdC3m[i]=0; fdC3p[i]=0; fIsFixed[i]=false; fIsDepleted[i]=true; fImpurity[i]=0; } fTree=NULL; fImpDist=NULL; // pick up a good style to modify gROOT->SetStyle("Plain"); gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(132); gStyle->SetLabelFont(132,"XYZ"); gStyle->SetTitleFont(132,"XYZ"); gStyle->SetLabelSize(0.05,"XYZ"); gStyle->SetTitleSize(0.05,"XYZ"); gStyle->SetTitleOffset(-0.4,"Z"); gStyle->SetPadTopMargin(0.02); // create a smoother palette than the default one const int nRGBs = 5; const int nCont = 255; double stops[nRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 }; double red[nRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 }; double green[nRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 }; double blue[nRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; TColor::CreateGradientColorTable(nRGBs, stops, red, green, blue, nCont); gStyle->SetNumberContours(nCont); } //_____________________________________________________________________________ // X::~X() { if (fV) delete[] fV; if (fE1) delete[] fE1; if (fC1) delete[] fC1; if (fdC1p) delete[] fdC1p; if (fdC1m) delete[] fdC1m; if (fIsFixed) delete[] fIsFixed; if (fImpurity) delete[] fImpurity; if (fIsDepleted) delete[] fIsDepleted; } //_____________________________________________________________________________ // bool X::Analytic() { Info("Analytic", "There is no analytic solution for this setup"); return false; } //_____________________________________________________________________________ // X& X::operator+=(GeFiCa::X *other) { if (fN!=other->fN) { Warning("+=", "Only same type of detector can be added together! Do nothing."); return *this; } for (int i=0; i<fN; i++) { fV[i]=fV[i]+other->fV[i]; fImpurity[i]+=other->fImpurity[i]; } V0+=other->V0; V1+=other->V1; return *this; } //_____________________________________________________________________________ // X& X::operator*=(double p) { for (int i=0; i<fN; i++) fV[i]=fV[i]*p; V0*=p; V1*=p; return *this; } //_____________________________________________________________________________ // int X::GetIdxOfMaxV() { double max=fV[0]; int maxn=0; for(int i=1;i<fN;i++) { if(fV[i]>max) { maxn=i; max=fV[i]; } } return maxn; } //_____________________________________________________________________________ // int X::GetIdxOfMinV() { double min=fV[0]; int minn=0; for(int i=1;i<fN;i++) { if(fV[i]<min) { minn=i; min=fV[i]; } } return minn; } //_____________________________________________________________________________ // bool X::IsDepleted() { for(int i=0;i<fN;i++) { DoSOR2(i); // calculate one more time in case of //adding two fields together, one is depleted, the other is not if (!fIsDepleted[i]) return false; } return true; } //_____________________________________________________________________________ // void X::SetStepLength(double stepLength) { for (int i=fN;i-->0;) { fIsFixed[i]=false; fC1[i]=i*stepLength; fdC1p[i]=stepLength; fdC1m[i]=stepLength; } } //_____________________________________________________________________________ // int* X::FindSurroundingMatrix(int idx) { int *tmp=new int[3]; tmp[0]=idx; if(idx-1<0)tmp[1]=1; else tmp[1]=idx-1; if(idx+1>=fN)tmp[2]=fN-2; else tmp[2]=idx+1; return tmp; } //_____________________________________________________________________________ // bool X::CalculatePotential(EMethod method) { if (fdC1p[0]==0) Initialize(); // setup and initialize grid if it's not done if (method==kAnalytic) return Analytic(); Info("CalculatePotential","Start SOR..."); TStopwatch watch; watch.Start(); double cp=1; // current presision while (Nsor<MaxIterations) { if (Nsor%100==0) Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision); double XUpSum=0; double XDownSum=0; for (int i=fN-1;i>=0;i--) { double old=fV[i]; DoSOR2(i); if(old>0)XDownSum+=old; else XDownSum-=old; double diff=fV[i]-old; if(diff>0)XUpSum+=(diff); else XUpSum-=(diff); } cp = XUpSum/XDownSum; Nsor++; if (cp<Precision) break; } for (int i=0; i<fN; i++) if (!CalculateField(i)) return false; Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision); Info("CalculatePotential", "CPU time: %.1f s", watch.CpuTime()); return true; } //_____________________________________________________________________________ // void X::DoSOR2(int idx) { // 2nd-order Runge-Kutta Successive Over-Relaxation if (fIsFixed[idx])return ; double rho=-fImpurity[idx]*Qe; double h2=fdC1m[idx]; double h3=fdC1p[idx]; double p2=fV[idx-1]; double p3=fV[idx+1]; double tmp=-rho/epsilon*h2*h3/2 + (h3*fV[idx-1]+h2*fV[idx+1])/(h2+h3); //find minmium and maxnium of all five grid, the new one should not go overthem. //find min double min=p2; double max=p2; if(min>p3)min=p3; //find max if(max<p3)max=p3; //if tmp is greater or smaller than max and min, set tmp to it. //fV[idx]=Csor*(tmp-fV[idx])+fV[idx]; double oldP=fV[idx]; tmp=Csor*(tmp-oldP)+oldP; if(tmp<min) { fV[idx]=min; fIsDepleted[idx]=false; } else if(tmp>max) { fV[idx]=max; fIsDepleted[idx]=false; } else fIsDepleted[idx]=true; if(fIsDepleted[idx]||V0==V1) fV[idx]=tmp; } //_____________________________________________________________________________ // int X::FindIdx(double tarx,int begin,int end) { //search using binary search if (begin>=end)return end; int mid=(begin+end)/2; if(fC1[mid]>=tarx)return FindIdx(tarx,begin,mid); else return FindIdx(tarx,mid+1,end); } //_____________________________________________________________________________ // double X::GetData(double x, double y, double z, double *data) { int idx=FindIdx(x,0,fN-1); if (idx==fN) return data[idx]; double ab=(-x+fC1[idx])/fdC1p[idx]; double aa=1-ab; return data[idx]*ab+data[idx-1]*aa; } //_____________________________________________________________________________ // bool X::CalculateField(int idx) { if (fdC1p[idx]==0 || fdC1m[idx]==0) return false; if (idx%fN1==0) // C1 lower boundary fE1[idx]=(fV[idx]-fV[idx+1])/fdC1p[idx]; else if (idx%fN1==fN1-1) // C1 upper boundary fE1[idx]=(fV[idx]-fV[idx-1])/fdC1m[idx]; else // bulk fE1[idx]=(fV[idx-1]-fV[idx+1])/(fdC1m[idx]+fdC1p[idx]); return true; } //_____________________________________________________________________________ // double X::GetC() { Info("GetC","Start..."); // set impurity to zero double *tmpImpurity=fImpurity; for (int i=0;i<fN;i++) { if (fImpurity[i]!=0) { fImpurity=new double[fN]; for (int j=0;j<fN;j++) { fImpurity[j]=0; if (!fIsFixed[j] && !fIsDepleted[j]) fIsFixed[j]=true; } break; } } // calculate potential without impurity CalculatePotential(GeFiCa::kSOR2); // set impurity back if(fImpurity!=tmpImpurity) delete []fImpurity; fImpurity=tmpImpurity; // calculate C based on CV^2/2 = epsilon int E^2 dx^3 / 2 double dV=V0-V1; if(dV<0)dV=-dV; double SumofElectricField=0; for(int i=0;i<fN;i++) { SumofElectricField+=fE1[i]*fE1[i]*fdC1p[i]*cm*cm; if (!fIsDepleted[i]) fIsFixed[i]=false; } double c=SumofElectricField*epsilon/dV/dV; Info("GetC",Form("%.1f pF",c/pF)); return c; } //_____________________________________________________________________________ // TTree* X::GetTree(bool createNew) { if (fTree) { if (createNew) delete fTree; else return fTree; } // define tree bool b,d; double v,te,e1,e2,e3,c1,c2,c3; fTree = new TTree("t","field data"); fTree->Branch("potential",&v,"v/D"); fTree->Branch("total E ",&te,"e/D"); // 1D data fTree->Branch("E1 ",&e1,"e1/D"); fTree->Branch("1st coordinate",&c1,"c1/D"); // initialize values if (fdC1p[0]==0) Initialize(); // setup & initialize grid if (fdC2p[0]!=0) { // if it is a 2D grid fTree->Branch("E2 ",&e2,"e2/D"); fTree->Branch("2nd coordinate",&c2,"c2/D"); } if (fdC3p[0]!=0) { // if it is a 3D grid fTree->Branch("E3 ",&e3,"e3/D"); fTree->Branch("3rd coordinate",&c3,"c3/D"); } fTree->Branch("boundary flag",&b,"b/O"); // boundary flag fTree->Branch("depletion flag",&d,"d/O"); // depletion flag // fill tree Info("GetTree","%d entries",fN); for (int i=0; i<fN; i++) { e1= fE1[i]; c1= fC1[i]; // 1D data if (fdC2p[i]!=0) { e2=fE2[i]; c2=fC2[i]; } // 2D data if (fdC3p[i]!=0) { e3=fE3[i]; c3=fC3[i]; } // 3D data v = fV[i]; b = fIsFixed[i]; d = fIsDepleted[i]; // common data if (fdC3p[i]!=0) te=TMath::Sqrt(e1*e1 + e2*e2 + e3*e3); else { if (fdC2p[i]!=0) te=TMath::Sqrt(e1*e1+e2*e2); else te=e1; } fTree->Fill(); } fTree->GetListOfBranches()->ls(); gDirectory->ls(); fTree->ResetBranchAddresses(); // disconnect from local variables return fTree; } //_____________________________________________________________________________ // void X::SetGridImpurity() { if (fImpDist && fImpurity[0]==0) // set impurity values if it's not done yet for (int i=fN;i-->0;) fImpurity[i]=fImpDist->Eval(fC1[i], fC2[i], fC3[i]); } <commit_msg>removed unnecessary Form from Info<commit_after>#include <TF3.h> #include <TTree.h> #include <TStyle.h> #include <TStopwatch.h> #include "X.h" #include "Units.h" using namespace GeFiCa; X::X(int nx, const char *name, const char *title) : TNamed(name,title), V0(0), V1(2e3*volt), MaxIterations(5000), Nsor(0), Csor(1.95), Precision(1e-7*volt), fN(nx), fN1(nx), fN2(0), fN3(0) { if (fN<10) { Warning("X","fN<10, set it to 11"); fN=11; fN1=11; } fV=new double[fN]; fE1=new double[fN]; fE2=new double[fN]; fE3=new double[fN]; fC1=new double[fN]; fC2=new double[fN]; fC3=new double[fN]; fdC1p=new double[fN]; fdC1m=new double[fN]; fdC2p=new double[fN]; fdC2m=new double[fN]; fdC3p=new double[fN]; fdC3m=new double[fN]; fIsFixed=new bool[fN]; fIsDepleted=new bool[fN]; fImpurity=new double[fN]; for (int i=0;i<fN;i++) { fV[i]=0; fE1[i]=0; fE2[i]=0; fE3[i]=0; fC1[i]=0; fC2[i]=0; fC3[i]=0; fdC1m[i]=0; fdC1p[i]=0; fdC2m[i]=0; fdC2p[i]=0; fdC3m[i]=0; fdC3p[i]=0; fIsFixed[i]=false; fIsDepleted[i]=true; fImpurity[i]=0; } fTree=NULL; fImpDist=NULL; // pick up a good style to modify gROOT->SetStyle("Plain"); gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(132); gStyle->SetLabelFont(132,"XYZ"); gStyle->SetTitleFont(132,"XYZ"); gStyle->SetLabelSize(0.05,"XYZ"); gStyle->SetTitleSize(0.05,"XYZ"); gStyle->SetTitleOffset(-0.4,"Z"); gStyle->SetPadTopMargin(0.02); // create a smoother palette than the default one const int nRGBs = 5; const int nCont = 255; double stops[nRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 }; double red[nRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 }; double green[nRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 }; double blue[nRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; TColor::CreateGradientColorTable(nRGBs, stops, red, green, blue, nCont); gStyle->SetNumberContours(nCont); } //_____________________________________________________________________________ // X::~X() { if (fV) delete[] fV; if (fE1) delete[] fE1; if (fC1) delete[] fC1; if (fdC1p) delete[] fdC1p; if (fdC1m) delete[] fdC1m; if (fIsFixed) delete[] fIsFixed; if (fImpurity) delete[] fImpurity; if (fIsDepleted) delete[] fIsDepleted; } //_____________________________________________________________________________ // bool X::Analytic() { Info("Analytic", "There is no analytic solution for this setup"); return false; } //_____________________________________________________________________________ // X& X::operator+=(GeFiCa::X *other) { if (fN!=other->fN) { Warning("+=", "Only same type of detector can be added together! Do nothing."); return *this; } for (int i=0; i<fN; i++) { fV[i]=fV[i]+other->fV[i]; fImpurity[i]+=other->fImpurity[i]; } V0+=other->V0; V1+=other->V1; return *this; } //_____________________________________________________________________________ // X& X::operator*=(double p) { for (int i=0; i<fN; i++) fV[i]=fV[i]*p; V0*=p; V1*=p; return *this; } //_____________________________________________________________________________ // int X::GetIdxOfMaxV() { double max=fV[0]; int maxn=0; for(int i=1;i<fN;i++) { if(fV[i]>max) { maxn=i; max=fV[i]; } } return maxn; } //_____________________________________________________________________________ // int X::GetIdxOfMinV() { double min=fV[0]; int minn=0; for(int i=1;i<fN;i++) { if(fV[i]<min) { minn=i; min=fV[i]; } } return minn; } //_____________________________________________________________________________ // bool X::IsDepleted() { for(int i=0;i<fN;i++) { DoSOR2(i); // calculate one more time in case of //adding two fields together, one is depleted, the other is not if (!fIsDepleted[i]) return false; } return true; } //_____________________________________________________________________________ // void X::SetStepLength(double stepLength) { for (int i=fN;i-->0;) { fIsFixed[i]=false; fC1[i]=i*stepLength; fdC1p[i]=stepLength; fdC1m[i]=stepLength; } } //_____________________________________________________________________________ // int* X::FindSurroundingMatrix(int idx) { int *tmp=new int[3]; tmp[0]=idx; if(idx-1<0)tmp[1]=1; else tmp[1]=idx-1; if(idx+1>=fN)tmp[2]=fN-2; else tmp[2]=idx+1; return tmp; } //_____________________________________________________________________________ // bool X::CalculatePotential(EMethod method) { if (fdC1p[0]==0) Initialize(); // setup and initialize grid if it's not done if (method==kAnalytic) return Analytic(); Info("CalculatePotential","Start SOR..."); TStopwatch watch; watch.Start(); double cp=1; // current presision while (Nsor<MaxIterations) { if (Nsor%100==0) Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision); double XUpSum=0; double XDownSum=0; for (int i=fN-1;i>=0;i--) { double old=fV[i]; DoSOR2(i); if(old>0)XDownSum+=old; else XDownSum-=old; double diff=fV[i]-old; if(diff>0)XUpSum+=(diff); else XUpSum-=(diff); } cp = XUpSum/XDownSum; Nsor++; if (cp<Precision) break; } for (int i=0; i<fN; i++) if (!CalculateField(i)) return false; Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision); Info("CalculatePotential", "CPU time: %.1f s", watch.CpuTime()); return true; } //_____________________________________________________________________________ // void X::DoSOR2(int idx) { // 2nd-order Runge-Kutta Successive Over-Relaxation if (fIsFixed[idx])return ; double rho=-fImpurity[idx]*Qe; double h2=fdC1m[idx]; double h3=fdC1p[idx]; double p2=fV[idx-1]; double p3=fV[idx+1]; double tmp=-rho/epsilon*h2*h3/2 + (h3*fV[idx-1]+h2*fV[idx+1])/(h2+h3); //find minmium and maxnium of all five grid, the new one should not go overthem. //find min double min=p2; double max=p2; if(min>p3)min=p3; //find max if(max<p3)max=p3; //if tmp is greater or smaller than max and min, set tmp to it. //fV[idx]=Csor*(tmp-fV[idx])+fV[idx]; double oldP=fV[idx]; tmp=Csor*(tmp-oldP)+oldP; if(tmp<min) { fV[idx]=min; fIsDepleted[idx]=false; } else if(tmp>max) { fV[idx]=max; fIsDepleted[idx]=false; } else fIsDepleted[idx]=true; if(fIsDepleted[idx]||V0==V1) fV[idx]=tmp; } //_____________________________________________________________________________ // int X::FindIdx(double tarx,int begin,int end) { //search using binary search if (begin>=end)return end; int mid=(begin+end)/2; if(fC1[mid]>=tarx)return FindIdx(tarx,begin,mid); else return FindIdx(tarx,mid+1,end); } //_____________________________________________________________________________ // double X::GetData(double x, double y, double z, double *data) { int idx=FindIdx(x,0,fN-1); if (idx==fN) return data[idx]; double ab=(-x+fC1[idx])/fdC1p[idx]; double aa=1-ab; return data[idx]*ab+data[idx-1]*aa; } //_____________________________________________________________________________ // bool X::CalculateField(int idx) { if (fdC1p[idx]==0 || fdC1m[idx]==0) return false; if (idx%fN1==0) // C1 lower boundary fE1[idx]=(fV[idx]-fV[idx+1])/fdC1p[idx]; else if (idx%fN1==fN1-1) // C1 upper boundary fE1[idx]=(fV[idx]-fV[idx-1])/fdC1m[idx]; else // bulk fE1[idx]=(fV[idx-1]-fV[idx+1])/(fdC1m[idx]+fdC1p[idx]); return true; } //_____________________________________________________________________________ // double X::GetC() { Info("GetC","Start..."); // set impurity to zero double *tmpImpurity=fImpurity; for (int i=0;i<fN;i++) { if (fImpurity[i]!=0) { fImpurity=new double[fN]; for (int j=0;j<fN;j++) { fImpurity[j]=0; if (!fIsFixed[j] && !fIsDepleted[j]) fIsFixed[j]=true; } break; } } // calculate potential without impurity CalculatePotential(GeFiCa::kSOR2); // set impurity back if(fImpurity!=tmpImpurity) delete []fImpurity; fImpurity=tmpImpurity; // calculate C based on CV^2/2 = epsilon int E^2 dx^3 / 2 double dV=V0-V1; if(dV<0)dV=-dV; double SumofElectricField=0; for(int i=0;i<fN;i++) { SumofElectricField+=fE1[i]*fE1[i]*fdC1p[i]*cm*cm; if (!fIsDepleted[i]) fIsFixed[i]=false; } double c=SumofElectricField*epsilon/dV/dV; Info("GetC","%.1f pF",c/pF); return c; } //_____________________________________________________________________________ // TTree* X::GetTree(bool createNew) { if (fTree) { if (createNew) delete fTree; else return fTree; } // define tree bool b,d; double v,te,e1,e2,e3,c1,c2,c3; fTree = new TTree("t","field data"); fTree->Branch("potential",&v,"v/D"); fTree->Branch("total E ",&te,"e/D"); // 1D data fTree->Branch("E1 ",&e1,"e1/D"); fTree->Branch("1st coordinate",&c1,"c1/D"); // initialize values if (fdC1p[0]==0) Initialize(); // setup & initialize grid if (fdC2p[0]!=0) { // if it is a 2D grid fTree->Branch("E2 ",&e2,"e2/D"); fTree->Branch("2nd coordinate",&c2,"c2/D"); } if (fdC3p[0]!=0) { // if it is a 3D grid fTree->Branch("E3 ",&e3,"e3/D"); fTree->Branch("3rd coordinate",&c3,"c3/D"); } fTree->Branch("boundary flag",&b,"b/O"); // boundary flag fTree->Branch("depletion flag",&d,"d/O"); // depletion flag // fill tree Info("GetTree","%d entries",fN); for (int i=0; i<fN; i++) { e1= fE1[i]; c1= fC1[i]; // 1D data if (fdC2p[i]!=0) { e2=fE2[i]; c2=fC2[i]; } // 2D data if (fdC3p[i]!=0) { e3=fE3[i]; c3=fC3[i]; } // 3D data v = fV[i]; b = fIsFixed[i]; d = fIsDepleted[i]; // common data if (fdC3p[i]!=0) te=TMath::Sqrt(e1*e1 + e2*e2 + e3*e3); else { if (fdC2p[i]!=0) te=TMath::Sqrt(e1*e1+e2*e2); else te=e1; } fTree->Fill(); } fTree->GetListOfBranches()->ls(); gDirectory->ls(); fTree->ResetBranchAddresses(); // disconnect from local variables return fTree; } //_____________________________________________________________________________ // void X::SetGridImpurity() { if (fImpDist && fImpurity[0]==0) // set impurity values if it's not done yet for (int i=fN;i-->0;) fImpurity[i]=fImpDist->Eval(fC1[i], fC2[i], fC3[i]); } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // $Id$ #include <qcolor.h> #include <kconfig.h> #include <kstandarddirs.h> #include <kglobal.h> #include <kdebug.h> #include "kprefs.h" class KPrefsItemBool : public KPrefsItem { public: KPrefsItemBool(const QString &group,const QString &name,bool *,bool defaultValue=true); virtual ~KPrefsItemBool() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: bool *mReference; bool mDefault; }; class KPrefsItemInt : public KPrefsItem { public: KPrefsItemInt(const QString &group,const QString &name,int *,int defaultValue=0); virtual ~KPrefsItemInt() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: int *mReference; int mDefault; }; class KPrefsItemColor : public KPrefsItem { public: KPrefsItemColor(const QString &group,const QString &name,QColor *, const QColor &defaultValue=QColor(128,128,128)); virtual ~KPrefsItemColor() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QColor *mReference; QColor mDefault; }; class KPrefsItemFont : public KPrefsItem { public: KPrefsItemFont(const QString &group,const QString &name,QFont *, const QFont &defaultValue=QFont("helvetica",12)); virtual ~KPrefsItemFont() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QFont *mReference; QFont mDefault; }; class KPrefsItemString : public KPrefsItem { public: KPrefsItemString(const QString &group,const QString &name,QString *, const QString &defaultValue="", bool isPassword=false); virtual ~KPrefsItemString() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QString *mReference; QString mDefault; bool mPassword; }; class KPrefsItemStringList : public KPrefsItem { public: KPrefsItemStringList(const QString &group,const QString &name,QStringList *, const QStringList &defaultValue=QStringList()); virtual ~KPrefsItemStringList() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QStringList *mReference; QStringList mDefault; }; class KPrefsItemIntList : public KPrefsItem { public: KPrefsItemIntList(const QString &group,const QString &name,QValueList<int> *, const QValueList<int> &defaultValue=QValueList<int>()); virtual ~KPrefsItemIntList() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QValueList<int> *mReference; QValueList<int> mDefault; }; KPrefsItemBool::KPrefsItemBool(const QString &group,const QString &name, bool *reference,bool defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemBool::setDefault() { *mReference = mDefault; } void KPrefsItemBool::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemBool::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readBoolEntry(mName,mDefault); } KPrefsItemInt::KPrefsItemInt(const QString &group,const QString &name, int *reference,int defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemInt::setDefault() { *mReference = mDefault; } void KPrefsItemInt::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemInt::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readNumEntry(mName,mDefault); } KPrefsItemColor::KPrefsItemColor(const QString &group,const QString &name, QColor *reference,const QColor &defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemColor::setDefault() { *mReference = mDefault; } void KPrefsItemColor::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemColor::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readColorEntry(mName,&mDefault); } KPrefsItemFont::KPrefsItemFont(const QString &group,const QString &name, QFont *reference,const QFont &defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemFont::setDefault() { *mReference = mDefault; } void KPrefsItemFont::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemFont::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readFontEntry(mName,&mDefault); } QString endecryptStr( const QString &aStr ) { QString result; for (uint i = 0; i < aStr.length(); i++) result += (aStr[i].unicode() < 0x20) ? aStr[i] : QChar(0x1001F - aStr[i].unicode()); return result; } KPrefsItemString::KPrefsItemString(const QString &group,const QString &name, QString *reference,const QString &defaultValue, bool isPassword) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; mPassword = isPassword; } void KPrefsItemString::setDefault() { *mReference = mDefault; } void KPrefsItemString::writeConfig(KConfig *config) { config->setGroup(mGroup); if ( mPassword ) config->writeEntry(mName, endecryptStr( *mReference ) ); else config->writeEntry(mName,*mReference); } void KPrefsItemString::readConfig(KConfig *config) { config->setGroup(mGroup); if ( mPassword ) if ( config->hasKey( mName ) ) *mReference = endecryptStr( config->readEntry( mName ) ); else *mReference = mDefault; else *mReference = config->readEntry(mName,mDefault); } KPrefsItemStringList::KPrefsItemStringList(const QString &group,const QString &name, QStringList *reference,const QStringList &defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemStringList::setDefault() { *mReference = mDefault; } void KPrefsItemStringList::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemStringList::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readListEntry(mName); } KPrefsItemIntList::KPrefsItemIntList(const QString &group,const QString &name, QValueList<int> *reference,const QValueList<int> &defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemIntList::setDefault() { *mReference = mDefault; } void KPrefsItemIntList::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemIntList::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readIntListEntry(mName); } QString *KPrefs::mCurrentGroup = 0; KPrefs::KPrefs(const QString &configname) { if (!configname.isEmpty()) { mConfig = new KConfig(locateLocal("config",configname)); } else { mConfig = KGlobal::config(); } mItems.setAutoDelete(true); // Set default group if (mCurrentGroup == 0) mCurrentGroup = new QString("No Group"); } KPrefs::~KPrefs() { if (mConfig != KGlobal::config()) { delete mConfig; } } void KPrefs::setCurrentGroup(const QString &group) { if (mCurrentGroup) delete mCurrentGroup; mCurrentGroup = new QString(group); } KConfig *KPrefs::config() const { return mConfig; } void KPrefs::setDefaults() { KPrefsItem *item; for(item = mItems.first();item;item = mItems.next()) { item->setDefault(); } usrSetDefaults(); } void KPrefs::readConfig() { KPrefsItem *item; for(item = mItems.first();item;item = mItems.next()) { item->readConfig(mConfig); } usrReadConfig(); } void KPrefs::writeConfig() { KPrefsItem *item; for(item = mItems.first();item;item = mItems.next()) { item->writeConfig(mConfig); } usrWriteConfig(); mConfig->sync(); } void KPrefs::addItem(KPrefsItem *item) { mItems.append(item); } void KPrefs::addItemBool(const QString &key,bool *reference,bool defaultValue) { addItem(new KPrefsItemBool(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemInt(const QString &key,int *reference,int defaultValue) { addItem(new KPrefsItemInt(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemColor(const QString &key,QColor *reference,const QColor &defaultValue) { addItem(new KPrefsItemColor(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemFont(const QString &key,QFont *reference,const QFont &defaultValue) { addItem(new KPrefsItemFont(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemString(const QString &key,QString *reference,const QString &defaultValue) { addItem(new KPrefsItemString(*mCurrentGroup,key,reference,defaultValue,false)); } void KPrefs::addItemPassword(const QString &key,QString *reference,const QString &defaultValue) { addItem(new KPrefsItemString(*mCurrentGroup,key,reference,defaultValue,true)); } void KPrefs::addItemStringList(const QString &key,QStringList *reference, const QStringList &defaultValue) { addItem(new KPrefsItemStringList(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemIntList(const QString &key,QValueList<int> *reference, const QValueList<int> &defaultValue) { addItem(new KPrefsItemIntList(*mCurrentGroup,key,reference,defaultValue)); } <commit_msg>Get rid of KConfig::hasKey().<commit_after>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // $Id$ #include <qcolor.h> #include <kconfig.h> #include <kstandarddirs.h> #include <kglobal.h> #include <kdebug.h> #include "kprefs.h" class KPrefsItemBool : public KPrefsItem { public: KPrefsItemBool(const QString &group,const QString &name,bool *,bool defaultValue=true); virtual ~KPrefsItemBool() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: bool *mReference; bool mDefault; }; class KPrefsItemInt : public KPrefsItem { public: KPrefsItemInt(const QString &group,const QString &name,int *,int defaultValue=0); virtual ~KPrefsItemInt() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: int *mReference; int mDefault; }; class KPrefsItemColor : public KPrefsItem { public: KPrefsItemColor(const QString &group,const QString &name,QColor *, const QColor &defaultValue=QColor(128,128,128)); virtual ~KPrefsItemColor() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QColor *mReference; QColor mDefault; }; class KPrefsItemFont : public KPrefsItem { public: KPrefsItemFont(const QString &group,const QString &name,QFont *, const QFont &defaultValue=QFont("helvetica",12)); virtual ~KPrefsItemFont() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QFont *mReference; QFont mDefault; }; class KPrefsItemString : public KPrefsItem { public: KPrefsItemString(const QString &group,const QString &name,QString *, const QString &defaultValue="", bool isPassword=false); virtual ~KPrefsItemString() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QString *mReference; QString mDefault; bool mPassword; }; class KPrefsItemStringList : public KPrefsItem { public: KPrefsItemStringList(const QString &group,const QString &name,QStringList *, const QStringList &defaultValue=QStringList()); virtual ~KPrefsItemStringList() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QStringList *mReference; QStringList mDefault; }; class KPrefsItemIntList : public KPrefsItem { public: KPrefsItemIntList(const QString &group,const QString &name,QValueList<int> *, const QValueList<int> &defaultValue=QValueList<int>()); virtual ~KPrefsItemIntList() {} void setDefault(); void readConfig(KConfig *); void writeConfig(KConfig *); private: QValueList<int> *mReference; QValueList<int> mDefault; }; KPrefsItemBool::KPrefsItemBool(const QString &group,const QString &name, bool *reference,bool defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemBool::setDefault() { *mReference = mDefault; } void KPrefsItemBool::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemBool::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readBoolEntry(mName,mDefault); } KPrefsItemInt::KPrefsItemInt(const QString &group,const QString &name, int *reference,int defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemInt::setDefault() { *mReference = mDefault; } void KPrefsItemInt::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemInt::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readNumEntry(mName,mDefault); } KPrefsItemColor::KPrefsItemColor(const QString &group,const QString &name, QColor *reference,const QColor &defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemColor::setDefault() { *mReference = mDefault; } void KPrefsItemColor::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemColor::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readColorEntry(mName,&mDefault); } KPrefsItemFont::KPrefsItemFont(const QString &group,const QString &name, QFont *reference,const QFont &defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemFont::setDefault() { *mReference = mDefault; } void KPrefsItemFont::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemFont::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readFontEntry(mName,&mDefault); } QString endecryptStr( const QString &aStr ) { QString result; for (uint i = 0; i < aStr.length(); i++) result += (aStr[i].unicode() < 0x20) ? aStr[i] : QChar(0x1001F - aStr[i].unicode()); return result; } KPrefsItemString::KPrefsItemString(const QString &group,const QString &name, QString *reference,const QString &defaultValue, bool isPassword) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; mPassword = isPassword; } void KPrefsItemString::setDefault() { *mReference = mDefault; } void KPrefsItemString::writeConfig(KConfig *config) { config->setGroup(mGroup); if ( mPassword ) config->writeEntry(mName, endecryptStr( *mReference ) ); else config->writeEntry(mName,*mReference); } void KPrefsItemString::readConfig(KConfig *config) { config->setGroup(mGroup); QString value; if ( mPassword ) { value = config->readEntry( mName, endecryptStr( mDefault ) ); *mReference = endecryptStr( value ); } else { *mReference = config->readEntry( mName, mDefault ); } } KPrefsItemStringList::KPrefsItemStringList(const QString &group,const QString &name, QStringList *reference,const QStringList &defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemStringList::setDefault() { *mReference = mDefault; } void KPrefsItemStringList::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemStringList::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readListEntry(mName); } KPrefsItemIntList::KPrefsItemIntList(const QString &group,const QString &name, QValueList<int> *reference,const QValueList<int> &defaultValue) : KPrefsItem(group,name) { mReference = reference; mDefault = defaultValue; } void KPrefsItemIntList::setDefault() { *mReference = mDefault; } void KPrefsItemIntList::writeConfig(KConfig *config) { config->setGroup(mGroup); config->writeEntry(mName,*mReference); } void KPrefsItemIntList::readConfig(KConfig *config) { config->setGroup(mGroup); *mReference = config->readIntListEntry(mName); } QString *KPrefs::mCurrentGroup = 0; KPrefs::KPrefs(const QString &configname) { if (!configname.isEmpty()) { mConfig = new KConfig(locateLocal("config",configname)); } else { mConfig = KGlobal::config(); } mItems.setAutoDelete(true); // Set default group if (mCurrentGroup == 0) mCurrentGroup = new QString("No Group"); } KPrefs::~KPrefs() { if (mConfig != KGlobal::config()) { delete mConfig; } } void KPrefs::setCurrentGroup(const QString &group) { if (mCurrentGroup) delete mCurrentGroup; mCurrentGroup = new QString(group); } KConfig *KPrefs::config() const { return mConfig; } void KPrefs::setDefaults() { KPrefsItem *item; for(item = mItems.first();item;item = mItems.next()) { item->setDefault(); } usrSetDefaults(); } void KPrefs::readConfig() { KPrefsItem *item; for(item = mItems.first();item;item = mItems.next()) { item->readConfig(mConfig); } usrReadConfig(); } void KPrefs::writeConfig() { KPrefsItem *item; for(item = mItems.first();item;item = mItems.next()) { item->writeConfig(mConfig); } usrWriteConfig(); mConfig->sync(); } void KPrefs::addItem(KPrefsItem *item) { mItems.append(item); } void KPrefs::addItemBool(const QString &key,bool *reference,bool defaultValue) { addItem(new KPrefsItemBool(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemInt(const QString &key,int *reference,int defaultValue) { addItem(new KPrefsItemInt(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemColor(const QString &key,QColor *reference,const QColor &defaultValue) { addItem(new KPrefsItemColor(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemFont(const QString &key,QFont *reference,const QFont &defaultValue) { addItem(new KPrefsItemFont(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemString(const QString &key,QString *reference,const QString &defaultValue) { addItem(new KPrefsItemString(*mCurrentGroup,key,reference,defaultValue,false)); } void KPrefs::addItemPassword(const QString &key,QString *reference,const QString &defaultValue) { addItem(new KPrefsItemString(*mCurrentGroup,key,reference,defaultValue,true)); } void KPrefs::addItemStringList(const QString &key,QStringList *reference, const QStringList &defaultValue) { addItem(new KPrefsItemStringList(*mCurrentGroup,key,reference,defaultValue)); } void KPrefs::addItemIntList(const QString &key,QValueList<int> *reference, const QValueList<int> &defaultValue) { addItem(new KPrefsItemIntList(*mCurrentGroup,key,reference,defaultValue)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #define _WITH_DPRINTF #include <cstdlib> #include <cstdio> #include <cassert> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include "httpclient.h" #include "httprepo.h" #include "util.h" #define D_READ 0 #define D_WRITE 1 using namespace std; /* * HttpClient */ HttpClient::HttpClient(const std::string &remotePath) { string tmp; size_t portPos, pathPos; if (remotePath.substr(0, 7) == "http://") { tmp = remotePath.substr(7); } else { assert(false); } portPos = tmp.find(':'); pathPos = tmp.find('/'); if (portPos != -1) { assert(portPos < pathPos); remotePort = tmp.substr(portPos + 1, pathPos - portPos); } else { portPos = pathPos; } assert(pathPos != -1); remoteHost = tmp.substr(0, portPos); remoteRepo = tmp.substr(pathPos + 1); } HttpClient::~HttpClient() { // Close } int HttpClient::connect() { // Wait for READY from server std::string ready; recvResponse(ready); if (ready != "READY\n") { return -1; } return 0; } bool HttpClient::connected() { return false; } void HttpClient::sendCommand(const std::string &command) { } void HttpClient::recvResponse(std::string &out) { } int cmd_httpclient(int argc, const char *argv[]) { if (argc < 2) { printf("Usage: ori httpclient http://hostname:port/path\n"); exit(1); } HttpClient client = HttpClient(std::string(argv[1])); if (client.connect() < 0) { printf("Error connecting to %s\n", argv[1]); exit(1); } dprintf(STDOUT_FILENO, "Connected\n"); HttpRepo repo(&client); std::set<ObjectInfo> objs = repo.listObjects(); for (std::set<ObjectInfo>::iterator it = objs.begin(); it != objs.end(); it++) { printf("%s\n", (*it).hash.c_str()); } printf("Terminating HTTP connection...\n"); return 0; } <commit_msg>Fixing HTTP client parsing.<commit_after>/* * Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #define _WITH_DPRINTF #include <cstdlib> #include <cstdio> #include <cassert> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <iostream> #include "httpclient.h" #include "httprepo.h" #include "util.h" #define D_READ 0 #define D_WRITE 1 using namespace std; /* * HttpClient */ HttpClient::HttpClient(const std::string &remotePath) { string tmp; size_t portPos, pathPos; if (remotePath.substr(0, 7) == "http://") { tmp = remotePath.substr(7); } else { assert(false); } portPos = tmp.find(':'); pathPos = tmp.find('/'); if (portPos != -1) { assert(portPos < pathPos); remotePort = tmp.substr(portPos + 1, pathPos - portPos - 1); } else { portPos = pathPos; remotePort = "80"; } assert(pathPos != -1); remoteHost = tmp.substr(0, portPos); remoteRepo = tmp.substr(pathPos + 1); } HttpClient::~HttpClient() { // Close } int HttpClient::connect() { // Wait for READY from server std::string ready; recvResponse(ready); if (ready != "READY\n") { return -1; } return 0; } bool HttpClient::connected() { return false; } void HttpClient::sendCommand(const std::string &command) { } void HttpClient::recvResponse(std::string &out) { } int cmd_httpclient(int argc, const char *argv[]) { if (argc < 2) { printf("Usage: ori httpclient http://hostname:port/path\n"); exit(1); } HttpClient client = HttpClient(std::string(argv[1])); if (client.connect() < 0) { printf("Error connecting to %s\n", argv[1]); exit(1); } dprintf(STDOUT_FILENO, "Connected\n"); HttpRepo repo(&client); std::set<ObjectInfo> objs = repo.listObjects(); for (std::set<ObjectInfo>::iterator it = objs.begin(); it != objs.end(); it++) { printf("%s\n", (*it).hash.c_str()); } printf("Terminating HTTP connection...\n"); return 0; } <|endoftext|>
<commit_before>/* * This file is part of the PySide project. * * Copyright (C) 2009-2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: PySide team <contact@pyside.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pyside.h" #include "signalmanager.h" #include "pysideproperty_p.h" #include "pysideproperty.h" #include "pysidesignal.h" #include "pysidesignal_p.h" #include "pysideslot_p.h" #include "pysidemetafunction_p.h" #include <basewrapper.h> #include <conversions.h> #include <typeresolver.h> #include <algorithm> #include <cctype> #include <QStack> #include <QCoreApplication> static QStack<PySide::CleanupFunction> cleanupFunctionList; namespace PySide { void init(PyObject *module) { Signal::init(module); Slot::init(module); Property::init(module); MetaFunction::init(module); // Init signal manager, so it will register some meta types used by QVariant. SignalManager::instance(); } bool fillQtProperties(PyObject* qObj, const QMetaObject* metaObj, PyObject* kwds, const char** blackList, unsigned int blackListSize) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(kwds, &pos, &key, &value)) { if (!blackListSize || !std::binary_search(blackList, blackList + blackListSize, std::string(PyString_AS_STRING(key)))) { QByteArray propName(PyString_AS_STRING(key)); if (metaObj->indexOfProperty(propName) != -1) { propName[0] = std::toupper(propName[0]); propName.prepend("set"); Shiboken::AutoDecRef propSetter(PyObject_GetAttrString(qObj, propName.constData())); if (!propSetter.isNull()) { Shiboken::AutoDecRef args(PyTuple_Pack(1, value)); Shiboken::AutoDecRef retval(PyObject_CallObject(propSetter, args)); } else { PyObject* attr = PyObject_GenericGetAttr(qObj, key); if (PySide::Property::isPropertyType(attr)) PySide::Property::setValue(reinterpret_cast<PySideProperty*>(attr), qObj, value); } } else { propName.append("()"); if (metaObj->indexOfSignal(propName) != -1) { propName.prepend('2'); PySide::Signal::connect(qObj, propName, value); } else { PyErr_Format(PyExc_AttributeError, "'%s' is not a Qt property or a signal", propName.constData()); return false; }; } } } return true; } void registerCleanupFunction(CleanupFunction func) { cleanupFunctionList.push(func); } void runCleanupFunctions() { while (!cleanupFunctionList.isEmpty()) { CleanupFunction f = cleanupFunctionList.pop(); f(); } } void destroyQCoreApplication() { SignalManager::instance().clear(); QCoreApplication* app = QCoreApplication::instance(); if (!app) return; Shiboken::BindingManager& bm = Shiboken::BindingManager::instance(); SbkObject* pyQApp = bm.retrieveWrapper(app); PyTypeObject* pyQObjectType = Shiboken::TypeResolver::get("QObject*")->pythonType(); assert(pyQObjectType); QList<SbkObject*> objects; //filter only QObjects which we have ownership, this will avoid list changes during the destruction of some parent object foreach (SbkObject* pyObj, bm.getAllPyObjects()) { if (pyObj != pyQApp && PyObject_TypeCheck(pyObj, pyQObjectType)) { if (Shiboken::Object::hasOwnership(pyObj)) objects << pyObj; } } //Now we can destroy all object in the list foreach (SbkObject* pyObj, objects) Shiboken::callCppDestructor<QObject>(Shiboken::Object::cppPointer(pyObj, Shiboken::SbkType<QObject*>())); // in the end destroy app delete app; } } //namespace PySide <commit_msg>Fix crash at exit when there's a chain of referenced objects.<commit_after>/* * This file is part of the PySide project. * * Copyright (C) 2009-2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: PySide team <contact@pyside.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pyside.h" #include "signalmanager.h" #include "pysideproperty_p.h" #include "pysideproperty.h" #include "pysidesignal.h" #include "pysidesignal_p.h" #include "pysideslot_p.h" #include "pysidemetafunction_p.h" #include <basewrapper.h> #include <conversions.h> #include <typeresolver.h> #include <bindingmanager.h> #include <algorithm> #include <cctype> #include <QStack> #include <QCoreApplication> static QStack<PySide::CleanupFunction> cleanupFunctionList; namespace PySide { void init(PyObject *module) { Signal::init(module); Slot::init(module); Property::init(module); MetaFunction::init(module); // Init signal manager, so it will register some meta types used by QVariant. SignalManager::instance(); } bool fillQtProperties(PyObject* qObj, const QMetaObject* metaObj, PyObject* kwds, const char** blackList, unsigned int blackListSize) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(kwds, &pos, &key, &value)) { if (!blackListSize || !std::binary_search(blackList, blackList + blackListSize, std::string(PyString_AS_STRING(key)))) { QByteArray propName(PyString_AS_STRING(key)); if (metaObj->indexOfProperty(propName) != -1) { propName[0] = std::toupper(propName[0]); propName.prepend("set"); Shiboken::AutoDecRef propSetter(PyObject_GetAttrString(qObj, propName.constData())); if (!propSetter.isNull()) { Shiboken::AutoDecRef args(PyTuple_Pack(1, value)); Shiboken::AutoDecRef retval(PyObject_CallObject(propSetter, args)); } else { PyObject* attr = PyObject_GenericGetAttr(qObj, key); if (PySide::Property::isPropertyType(attr)) PySide::Property::setValue(reinterpret_cast<PySideProperty*>(attr), qObj, value); } } else { propName.append("()"); if (metaObj->indexOfSignal(propName) != -1) { propName.prepend('2'); PySide::Signal::connect(qObj, propName, value); } else { PyErr_Format(PyExc_AttributeError, "'%s' is not a Qt property or a signal", propName.constData()); return false; }; } } } return true; } void registerCleanupFunction(CleanupFunction func) { cleanupFunctionList.push(func); } void runCleanupFunctions() { while (!cleanupFunctionList.isEmpty()) { CleanupFunction f = cleanupFunctionList.pop(); f(); } } static void destructionVisitor(SbkObject* pyObj, void* data) { void** realData = reinterpret_cast<void**>(data); SbkObject* pyQApp = reinterpret_cast<SbkObject*>(realData[0]); PyTypeObject* pyQObjectType = reinterpret_cast<PyTypeObject*>(realData[1]); if (pyObj != pyQApp && PyObject_TypeCheck(pyObj, pyQObjectType)) { if (Shiboken::Object::hasOwnership(pyObj)) Shiboken::callCppDestructor<QObject>(Shiboken::Object::cppPointer(pyObj, Shiboken::SbkType<QObject*>())); } }; void destroyQCoreApplication() { SignalManager::instance().clear(); QCoreApplication* app = QCoreApplication::instance(); if (!app) return; Shiboken::BindingManager& bm = Shiboken::BindingManager::instance(); SbkObject* pyQApp = bm.retrieveWrapper(app); PyTypeObject* pyQObjectType = Shiboken::TypeResolver::get("QObject*")->pythonType(); assert(pyQObjectType); void* data[2] = {pyQApp, pyQObjectType}; bm.visitAllPyObjects(&destructionVisitor, &data); // in the end destroy app delete app; } } //namespace PySide <|endoftext|>
<commit_before>//Hallo, test<commit_msg>Gute Idee<commit_after>//Hallo, test //leider falsch<|endoftext|>
<commit_before>#include<iostream> #include "qd.hpp" struct myInt { int* i; myInt() : i(new int(42)) {} myInt(int i) : i(new int(i)) {} myInt(const myInt& i) : i(new int(*i.i)) {} myInt(const myInt&& i) : i(new int(*i.i)) {} ~myInt() { delete i; } void inc(myInt amount) { *i += *amount.i; std::cout << "ADDITION: " << *i << " =added= " << *amount.i << '\n'; } }; struct Fun { myInt operator()(myInt a, myInt b) { auto r = myInt(*a.i + *b.i); std::cout << *a.i << "+" << *b.i << " = " << *r.i << '\n'; return r; } }; int shared; int foo(myInt i) { shared += 2; // std::cout << "Hello World! " << i << "\n"; return 23; } void bar(myInt i) { shared++; // std::cout << "Hello World! " << i << "\n"; } void wait() { } qdlock qdl; void f1() { typedef std::future<int> future; std::array<future, 1024*128> fs; for(future& f : fs) { //f = qdl.delegate<decltype(foo), foo>(myInt(42)); myInt m(42); f = qdl.DELEGATE_FUTURE(foo, m); //f = qdl.DELEGATE_FUTURE(foo, myInt(42)); } } void f2() { typedef std::future<void> future; std::array<std::pair<myInt,Fun>, 1024*128> ms; Fun f; for(auto& m : ms) { qdl.DELEGATE_NOFUTURE(&myInt::inc, myInt(m.first), myInt(23)); qdl.delegate_n(&myInt::inc, myInt(m.first), myInt(23)); //qdl.delegate_nofuture(&foo, m.first); //qdl.DELEGATE_NOFUTURE(&foo, m.first); } for(auto& m : ms) { qdl.delegate_n(f, myInt(m.first), myInt(23)); } auto bar = qdl.DELEGATE_FUTURE(wait); bar.wait(); for(auto& m : ms) { std::cout << *m.first.i << '\n'; } bar = qdl.DELEGATE_FUTURE(wait); bar.wait(); } int main() { shared = 0; std::array<std::thread, 1> t1; std::array<std::thread, 1> t2; for(std::thread& t : t1) { t = std::thread(f1); } for(std::thread& t : t2) { t = std::thread(f2); } for(std::thread& t : t1) { t.join(); } for(std::thread& t : t2) { t.join(); } return 0; } <commit_msg>remove non-library file<commit_after><|endoftext|>
<commit_before>#include "twoDDisplay.h" #include <QtCore/QDebug> using namespace trikKitInterpreter::robotModel::twoD::parts; using namespace interpreterBase::robotModel; /// @todo: This constant adjusts screen coordinates shift. It must be 0. int const yDisplayShift = 8; Display::Display(DeviceInfo const &info , PortInfo const &port , twoDModel::engine::TwoDModelEngineInterface &engine) : robotModel::parts::TrikDisplay(info, port) , mEngine(engine) , mBackground(Qt::transparent) , mCurrentPenWidth(0) , mCurrentPenColor(Qt::black) { mEngine.display()->setPainter(this); } void Display::setPainterColor(QColor const &color) { mCurrentPenColor = color; } void Display::setPainterWidth(int penWidth) { mCurrentPenWidth = penWidth; } void Display::drawPixel(int x, int y) { mPixels << PixelCoordinates(x, y, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawLine(int x1, int y1, int x2, int y2) { mLines << LineCoordinates(x1, y1, x2, y2, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawRect(int x, int y, int width, int height) { mRects << RectCoordinates(x, y, width, height, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawEllipse(int x, int y, int width, int height) { mEllipses << EllipseCoordinates(x, y, width, height, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawArc(int x, int y, int width, int height, int startAngle, int spanAngle) { mArcs << ArcCoordinates(x, y, width, height, startAngle, spanAngle, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawSmile(bool sad) { mCurrentImage = QImage(sad ? ":/icons/sadSmile.png" : ":/icons/smile.png"); mEngine.display()->repaintDisplay(); } void Display::setBackground(QColor const &color) { mBackground = color; mEngine.display()->repaintDisplay(); } void Display::printText(int x, int y, QString const &text) { mLabels[qMakePair(x, y + yDisplayShift)] = {text, mCurrentPenColor}; mEngine.display()->repaintDisplay(); } void Display::clearScreen() { mCurrentImage = QImage(); mBackground = Qt::transparent; mLabels.clear(); mPixels.clear(); mLines.clear(); mRects.clear(); mEllipses.clear(); mArcs.clear(); mCurrentPenWidth = 0; mCurrentPenColor = Qt::black; if (mEngine.display()) { mEngine.display()->repaintDisplay(); } } void Display::paint(QPainter *painter) { QRect const displayRect(0, 0, mEngine.display()->displayWidth(), mEngine.display()->displayHeight()); painter->save(); painter->setPen(mBackground); painter->setBrush(mBackground); painter->drawRect(displayRect); painter->drawImage(displayRect, mCurrentImage); painter->restore(); painter->save(); painter->setPen(Qt::black); for (QPair<int, int> const &point : mLabels.keys()) { /// @todo: Honest labels must be here, without text overlapping. painter->setPen(QPen(mLabels[point].second, 0, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawText(QPoint(point.first, point.second), mLabels[point].first); } for (int i = 0; i < mPixels.length(); ++i) { painter->setPen(QPen(mPixels.at(i).color, mPixels.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawPoint(mPixels.at(i).coord.x(), mPixels.at(i).coord.y()); } for (int i = 0; i < mLines.length(); ++i) { painter->setPen(QPen(mLines.at(i).color, mLines.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawLine(mLines.at(i).line.x1(), mLines.at(i).line.y1() , mLines.at(i).line.x2(), mLines.at(i).line.y2()); } for (int i = 0; i < mRects.length(); ++i) { painter->setPen(QPen(mRects.at(i).color, mRects.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawRect(mRects.at(i).rect.x(), mRects.at(i).rect.y() , mRects.at(i).rect.width(), mRects.at(i).rect.height()); } for (int i = 0; i < mEllipses.length(); ++i) { painter->setPen(QPen(mEllipses.at(i).color, mEllipses.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawEllipse(mEllipses.at(i).ellipse.x(), mEllipses.at(i).ellipse.y() , mEllipses.at(i).ellipse.width(), mEllipses.at(i).ellipse.height()); } for (int i = 0; i < mArcs.length(); ++i) { painter->setPen(QPen(mArcs.at(i).color, mArcs.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawArc(mArcs.at(i).arc.x(), mArcs.at(i).arc.y() , mArcs.at(i).arc.width(), mArcs.at(i).arc.height() , mArcs.at(i).startAngle, mArcs.at(i).spanAngle); } painter->restore(); } void Display::clear() { clearScreen(); } <commit_msg>Debug output removed<commit_after>#include "twoDDisplay.h" using namespace trikKitInterpreter::robotModel::twoD::parts; using namespace interpreterBase::robotModel; /// @todo: This constant adjusts screen coordinates shift. It must be 0. int const yDisplayShift = 8; Display::Display(DeviceInfo const &info , PortInfo const &port , twoDModel::engine::TwoDModelEngineInterface &engine) : robotModel::parts::TrikDisplay(info, port) , mEngine(engine) , mBackground(Qt::transparent) , mCurrentPenWidth(0) , mCurrentPenColor(Qt::black) { mEngine.display()->setPainter(this); } void Display::setPainterColor(QColor const &color) { mCurrentPenColor = color; } void Display::setPainterWidth(int penWidth) { mCurrentPenWidth = penWidth; } void Display::drawPixel(int x, int y) { mPixels << PixelCoordinates(x, y, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawLine(int x1, int y1, int x2, int y2) { mLines << LineCoordinates(x1, y1, x2, y2, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawRect(int x, int y, int width, int height) { mRects << RectCoordinates(x, y, width, height, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawEllipse(int x, int y, int width, int height) { mEllipses << EllipseCoordinates(x, y, width, height, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawArc(int x, int y, int width, int height, int startAngle, int spanAngle) { mArcs << ArcCoordinates(x, y, width, height, startAngle, spanAngle, mCurrentPenColor, mCurrentPenWidth); mEngine.display()->repaintDisplay(); } void Display::drawSmile(bool sad) { mCurrentImage = QImage(sad ? ":/icons/sadSmile.png" : ":/icons/smile.png"); mEngine.display()->repaintDisplay(); } void Display::setBackground(QColor const &color) { mBackground = color; mEngine.display()->repaintDisplay(); } void Display::printText(int x, int y, QString const &text) { mLabels[qMakePair(x, y + yDisplayShift)] = {text, mCurrentPenColor}; mEngine.display()->repaintDisplay(); } void Display::clearScreen() { mCurrentImage = QImage(); mBackground = Qt::transparent; mLabels.clear(); mPixels.clear(); mLines.clear(); mRects.clear(); mEllipses.clear(); mArcs.clear(); mCurrentPenWidth = 0; mCurrentPenColor = Qt::black; if (mEngine.display()) { mEngine.display()->repaintDisplay(); } } void Display::paint(QPainter *painter) { QRect const displayRect(0, 0, mEngine.display()->displayWidth(), mEngine.display()->displayHeight()); painter->save(); painter->setPen(mBackground); painter->setBrush(mBackground); painter->drawRect(displayRect); painter->drawImage(displayRect, mCurrentImage); painter->restore(); painter->save(); painter->setPen(Qt::black); for (QPair<int, int> const &point : mLabels.keys()) { /// @todo: Honest labels must be here, without text overlapping. painter->setPen(QPen(mLabels[point].second, 0, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawText(QPoint(point.first, point.second), mLabels[point].first); } for (int i = 0; i < mPixels.length(); ++i) { painter->setPen(QPen(mPixels.at(i).color, mPixels.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawPoint(mPixels.at(i).coord.x(), mPixels.at(i).coord.y()); } for (int i = 0; i < mLines.length(); ++i) { painter->setPen(QPen(mLines.at(i).color, mLines.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawLine(mLines.at(i).line.x1(), mLines.at(i).line.y1() , mLines.at(i).line.x2(), mLines.at(i).line.y2()); } for (int i = 0; i < mRects.length(); ++i) { painter->setPen(QPen(mRects.at(i).color, mRects.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawRect(mRects.at(i).rect.x(), mRects.at(i).rect.y() , mRects.at(i).rect.width(), mRects.at(i).rect.height()); } for (int i = 0; i < mEllipses.length(); ++i) { painter->setPen(QPen(mEllipses.at(i).color, mEllipses.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawEllipse(mEllipses.at(i).ellipse.x(), mEllipses.at(i).ellipse.y() , mEllipses.at(i).ellipse.width(), mEllipses.at(i).ellipse.height()); } for (int i = 0; i < mArcs.length(); ++i) { painter->setPen(QPen(mArcs.at(i).color, mArcs.at(i).penWidth, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin)); painter->drawArc(mArcs.at(i).arc.x(), mArcs.at(i).arc.y() , mArcs.at(i).arc.width(), mArcs.at(i).arc.height() , mArcs.at(i).startAngle, mArcs.at(i).spanAngle); } painter->restore(); } void Display::clear() { clearScreen(); } <|endoftext|>
<commit_before>/** * \file * \brief SpiPeripheral class header for SPIv1 in STM32 * * \author Copyright (C) 2016-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef SOURCE_CHIP_STM32_PERIPHERALS_SPIV1_INCLUDE_DISTORTOS_CHIP_STM32_SPIV1_SPIPERIPHERAL_HPP_ #define SOURCE_CHIP_STM32_PERIPHERALS_SPIV1_INCLUDE_DISTORTOS_CHIP_STM32_SPIV1_SPIPERIPHERAL_HPP_ #include "distortos/chip/getBusFrequency.hpp" namespace distortos { namespace chip { /// SpiPeripheral class is a raw SPI peripheral for SPIv1 in STM32 class SpiPeripheral { public: /** * \brief SpiPeripheral's constructor * * \param [in] spiBase is a base address of SPI peripheral */ constexpr explicit SpiPeripheral(const uintptr_t spiBase) : spiBase_{spiBase}, peripheralFrequency_{getBusFrequency(spiBase)} { } /** * \return peripheral clock frequency, Hz */ uint32_t getPeripheralFrequency() const { return peripheralFrequency_; } /** * \return reference to SPI_TypeDef object */ SPI_TypeDef& getSpi() const { return *reinterpret_cast<SPI_TypeDef*>(spiBase_); } /** * \return current value of CR1 register */ uint32_t readCr1() const { return getSpi().CR1; } /** * \return current value of CR2 register */ uint32_t readCr2() const { return getSpi().CR2; } /** * \return current value of DR register */ uint32_t readDr() const { return getSpi().DR; } /** * \return current value of SR register */ uint32_t readSr() const { return getSpi().SR; } /** * \brief Writes value to CR1 register. * * \param [in] cr1 is the value that will be written to CR1 register */ void writeCr1(const uint32_t cr1) const { getSpi().CR1 = cr1; } /** * \brief Writes value to CR2 register. * * \param [in] cr2 is the value that will be written to CR2 register */ void writeCr2(const uint32_t cr2) const { getSpi().CR2 = cr2; } /** * \brief Writes value to DR register. * * \param [in] dr is the value that will be written to DR register */ void writeDr(const uint32_t dr) const { getSpi().DR = dr; } /** * \brief Writes value to SR register. * * \param [in] sr is the value that will be written to SR register */ void writeSr(const uint32_t sr) const { getSpi().SR = sr; } private: /// base address of SPI peripheral uintptr_t spiBase_; /// peripheral clock frequency, Hz uint32_t peripheralFrequency_; }; } // namespace chip } // namespace distortos #endif // SOURCE_CHIP_STM32_PERIPHERALS_SPIV1_INCLUDE_DISTORTOS_CHIP_STM32_SPIV1_SPIPERIPHERAL_HPP_ <commit_msg>Make STM32 SPIv1 SpiPeripheral::getSpi() private<commit_after>/** * \file * \brief SpiPeripheral class header for SPIv1 in STM32 * * \author Copyright (C) 2016-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef SOURCE_CHIP_STM32_PERIPHERALS_SPIV1_INCLUDE_DISTORTOS_CHIP_STM32_SPIV1_SPIPERIPHERAL_HPP_ #define SOURCE_CHIP_STM32_PERIPHERALS_SPIV1_INCLUDE_DISTORTOS_CHIP_STM32_SPIV1_SPIPERIPHERAL_HPP_ #include "distortos/chip/getBusFrequency.hpp" namespace distortos { namespace chip { /// SpiPeripheral class is a raw SPI peripheral for SPIv1 in STM32 class SpiPeripheral { public: /** * \brief SpiPeripheral's constructor * * \param [in] spiBase is a base address of SPI peripheral */ constexpr explicit SpiPeripheral(const uintptr_t spiBase) : spiBase_{spiBase}, peripheralFrequency_{getBusFrequency(spiBase)} { } /** * \return peripheral clock frequency, Hz */ uint32_t getPeripheralFrequency() const { return peripheralFrequency_; } /** * \return current value of CR1 register */ uint32_t readCr1() const { return getSpi().CR1; } /** * \return current value of CR2 register */ uint32_t readCr2() const { return getSpi().CR2; } /** * \return current value of DR register */ uint32_t readDr() const { return getSpi().DR; } /** * \return current value of SR register */ uint32_t readSr() const { return getSpi().SR; } /** * \brief Writes value to CR1 register. * * \param [in] cr1 is the value that will be written to CR1 register */ void writeCr1(const uint32_t cr1) const { getSpi().CR1 = cr1; } /** * \brief Writes value to CR2 register. * * \param [in] cr2 is the value that will be written to CR2 register */ void writeCr2(const uint32_t cr2) const { getSpi().CR2 = cr2; } /** * \brief Writes value to DR register. * * \param [in] dr is the value that will be written to DR register */ void writeDr(const uint32_t dr) const { getSpi().DR = dr; } /** * \brief Writes value to SR register. * * \param [in] sr is the value that will be written to SR register */ void writeSr(const uint32_t sr) const { getSpi().SR = sr; } private: /** * \return reference to SPI_TypeDef object */ SPI_TypeDef& getSpi() const { return *reinterpret_cast<SPI_TypeDef*>(spiBase_); } /// base address of SPI peripheral uintptr_t spiBase_; /// peripheral clock frequency, Hz uint32_t peripheralFrequency_; }; } // namespace chip } // namespace distortos #endif // SOURCE_CHIP_STM32_PERIPHERALS_SPIV1_INCLUDE_DISTORTOS_CHIP_STM32_SPIV1_SPIPERIPHERAL_HPP_ <|endoftext|>
<commit_before>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 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 Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "InstanceScript.h" #include "ObjectMgr.h" #include "ScriptMgr.h" #include "TemporarySummon.h" #include "molten_core.h" MinionData const minionData[] = { { NPC_FIRESWORN, DATA_GARR }, { NPC_FLAMEWALKER, DATA_GEHENNAS }, { NPC_FLAMEWALKER_PROTECTOR, DATA_LUCIFRON }, { NPC_FLAMEWALKER_PRIEST, DATA_SULFURON }, { NPC_FLAMEWALKER_HEALER, DATA_MAJORDOMO_EXECUTUS }, { NPC_FLAMEWALKER_ELITE, DATA_MAJORDOMO_EXECUTUS }, { 0, 0 } // END }; struct MCBossObject { uint32 bossId; uint32 runeId; uint32 circleId; }; constexpr uint8 MAX_MC_LINKED_BOSS_OBJ = 7; MCBossObject const linkedBossObjData[MAX_MC_LINKED_BOSS_OBJ]= { { DATA_MAGMADAR, GO_RUNE_KRESS, GO_CIRCLE_MAGMADAR }, { DATA_GEHENNAS, GO_RUNE_MOHN, GO_CIRCLE_GEHENNAS }, { DATA_GARR, GO_RUNE_BLAZ, GO_CIRCLE_GARR }, { DATA_SHAZZRAH, GO_RUNE_MAZJ, GO_CIRCLE_SHAZZRAH }, { DATA_GEDDON, GO_RUNE_ZETH, GO_CIRCLE_GEDDON }, { DATA_GOLEMAGG, GO_RUNE_THERI, GO_CIRCLE_GOLEMAGG }, { DATA_SULFURON, GO_RUNE_KORO, GO_CIRCLE_SULFURON }, }; constexpr uint8 SAY_SPAWN = 1; class instance_molten_core : public InstanceMapScript { public: instance_molten_core() : InstanceMapScript(MCScriptName, 409) {} struct instance_molten_core_InstanceMapScript : public InstanceScript { instance_molten_core_InstanceMapScript(Map* map) : InstanceScript(map) { SetBossNumber(MAX_ENCOUNTER); LoadMinionData(minionData); } void OnPlayerEnter(Player* /*player*/) override { if (CheckMajordomoExecutus()) { SummonMajordomoExecutus(); } } void OnCreatureCreate(Creature* creature) override { switch (creature->GetEntry()) { case NPC_GOLEMAGG_THE_INCINERATOR: { _golemaggGUID = creature->GetGUID(); break; } case NPC_CORE_RAGER: { _golemaggMinionsGUIDS.insert(creature->GetGUID()); break; } case NPC_MAJORDOMO_EXECUTUS: { _majordomoExecutusGUID = creature->GetGUID(); break; } case NPC_GARR: { _garrGUID = creature->GetGUID(); break; } case NPC_RAGNAROS: { _ragnarosGUID = creature->GetGUID(); break; } case NPC_FIRESWORN: case NPC_FLAMEWALKER: case NPC_FLAMEWALKER_PROTECTOR: case NPC_FLAMEWALKER_PRIEST: case NPC_FLAMEWALKER_HEALER: case NPC_FLAMEWALKER_ELITE: { AddMinion(creature, true); break; } } } void OnCreatureRemove(Creature* creature) override { switch (creature->GetEntry()) { case NPC_FIRESWORN: { AddMinion(creature, false); break; } case NPC_FLAMEWALKER: case NPC_FLAMEWALKER_PROTECTOR: case NPC_FLAMEWALKER_PRIEST: case NPC_FLAMEWALKER_HEALER: case NPC_FLAMEWALKER_ELITE: { AddMinion(creature, false); break; } } } void OnGameObjectCreate(GameObject* go) override { switch (go->GetEntry()) { case GO_CACHE_OF_THE_FIRELORD: { _cacheOfTheFirelordGUID = go->GetGUID(); break; } case GO_CIRCLE_GEDDON: case GO_CIRCLE_GARR: case GO_CIRCLE_GEHENNAS: case GO_CIRCLE_GOLEMAGG: case GO_CIRCLE_MAGMADAR: case GO_CIRCLE_SHAZZRAH: case GO_CIRCLE_SULFURON: { for (uint8 i = 0; i < MAX_MC_LINKED_BOSS_OBJ; ++i) { if (linkedBossObjData[i].circleId != go->GetEntry()) { continue; } if (GetBossState(linkedBossObjData[i].bossId) == DONE) { go->DespawnOrUnsummon(); } else { _circlesGUIDs[linkedBossObjData[i].bossId] = go->GetGUID(); } } break; } case GO_RUNE_KRESS: case GO_RUNE_MOHN: case GO_RUNE_BLAZ: case GO_RUNE_MAZJ: case GO_RUNE_ZETH: case GO_RUNE_THERI: case GO_RUNE_KORO: { for (uint8 i = 0; i < MAX_MC_LINKED_BOSS_OBJ; ++i) { if (linkedBossObjData[i].runeId != go->GetEntry()) { continue; } if (GetBossState(linkedBossObjData[i].bossId) == DONE) { go->SetGoState(GO_STATE_ACTIVE); } else { _runesGUIDs[linkedBossObjData[i].bossId] = go->GetGUID(); } } break; } case GO_LAVA_STEAM: { _lavaSteamGUID = go->GetGUID(); break; } case GO_LAVA_SPLASH: { _lavaSplashGUID = go->GetGUID(); break; } case GO_LAVA_BURST: { if (Creature* ragnaros = instance->GetCreature(_ragnarosGUID)) { ragnaros->AI()->SetGUID(go->GetGUID(), GO_LAVA_BURST); } break; } } } ObjectGuid GetGuidData(uint32 type) const override { switch (type) { case DATA_GOLEMAGG: return _golemaggGUID; case DATA_MAJORDOMO_EXECUTUS: return _majordomoExecutusGUID; case DATA_GARR: return _garrGUID; case DATA_LAVA_STEAM: return _lavaSteamGUID; case DATA_LAVA_SPLASH: return _lavaSplashGUID; case DATA_RAGNAROS: return _ragnarosGUID; } return ObjectGuid::Empty; } bool SetBossState(uint32 bossId, EncounterState state) override { if (!InstanceScript::SetBossState(bossId, state)) { return false; } if (bossId == DATA_MAJORDOMO_EXECUTUS && state == DONE) { DoRespawnGameObject(_cacheOfTheFirelordGUID, 7 * DAY); } else if (bossId == DATA_GOLEMAGG) { switch (state) { case NOT_STARTED: case FAIL: { if (!_golemaggMinionsGUIDS.empty()) { for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS) { Creature* minion = instance->GetCreature(minionGuid); if (minion && minion->isDead()) { minion->Respawn(); } } } break; } case IN_PROGRESS: { if (!_golemaggMinionsGUIDS.empty()) { for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS) { if (Creature* minion = instance->GetCreature(minionGuid)) { minion->AI()->DoZoneInCombat(nullptr, 150.0f); } } } break; } case DONE: { if (!_golemaggMinionsGUIDS.empty()) { for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS) { if (Creature* minion = instance->GetCreature(minionGuid)) { minion->CastSpell(minion, SPELL_CORE_RAGER_QUIET_SUICIDE, true); } } _golemaggMinionsGUIDS.clear(); } break; } default: break; } } // Perform needed checks for Majordomu if (bossId < DATA_MAJORDOMO_EXECUTUS && state == DONE) { if (GameObject* circle = instance->GetGameObject(_circlesGUIDs[bossId])) { circle->DespawnOrUnsummon(); _circlesGUIDs[bossId].Clear(); } if (GameObject* rune = instance->GetGameObject(_runesGUIDs[bossId])) { rune->SetGoState(GO_STATE_ACTIVE); _runesGUIDs[bossId].Clear(); } if (CheckMajordomoExecutus()) { SummonMajordomoExecutus(); } } return true; } void DoAction(int32 action) override { if (action == ACTION_RESET_GOLEMAGG_ENCOUNTER) { if (Creature* golemagg = instance->GetCreature(_golemaggGUID)) { golemagg->AI()->EnterEvadeMode(); } if (!_golemaggMinionsGUIDS.empty()) { for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS) { if (Creature* minion = instance->GetCreature(minionGuid)) { minion->AI()->EnterEvadeMode(); } } } } } void SummonMajordomoExecutus() { if (instance->GetCreature(_majordomoExecutusGUID)) { return; } if (GetBossState(DATA_MAJORDOMO_EXECUTUS) != DONE) { if (Creature* creature = instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, MajordomoSummonPos)) { creature->AI()->Talk(SAY_SPAWN); } } else { instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, MajordomoRagnaros); } } bool CheckMajordomoExecutus() const { if (GetBossState(DATA_RAGNAROS) == DONE) { return false; } for (uint8 i = 0; i < DATA_MAJORDOMO_EXECUTUS; ++i) { if (i == DATA_LUCIFRON) { continue; } if (GetBossState(i) != DONE) { return false; } } // Prevent spawning if Ragnaros is present if (instance->GetCreature(_ragnarosGUID)) { return false; } return true; } std::string GetSaveData() override { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "M C " << GetBossSaveData(); OUT_SAVE_INST_DATA_COMPLETE; return saveStream.str(); } void Load(char const* data) override { if (!data) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(data); char dataHead1, dataHead2; std::istringstream loadStream(data); loadStream >> dataHead1 >> dataHead2; if (dataHead1 == 'M' && dataHead2 == 'C') { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { uint32 tmpState; loadStream >> tmpState; if (tmpState == IN_PROGRESS || tmpState > TO_BE_DECIDED) { tmpState = NOT_STARTED; } SetBossState(i, static_cast<EncounterState>(tmpState)); } if (CheckMajordomoExecutus()) { SummonMajordomoExecutus(); } } else { OUT_LOAD_INST_DATA_FAIL; } OUT_LOAD_INST_DATA_COMPLETE; } private: std::unordered_map<uint32/*bossid*/, ObjectGuid/*circleGUID*/> _circlesGUIDs; std::unordered_map<uint32/*bossid*/, ObjectGuid/*runeGUID*/> _runesGUIDs; // Golemagg encounter related ObjectGuid _golemaggGUID; GuidSet _golemaggMinionsGUIDS; // Ragnaros encounter related ObjectGuid _ragnarosGUID; ObjectGuid _lavaSteamGUID; ObjectGuid _lavaSplashGUID; ObjectGuid _majordomoExecutusGUID; ObjectGuid _cacheOfTheFirelordGUID; ObjectGuid _garrGUID; ObjectGuid _magmadarGUID; }; InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_molten_core_InstanceMapScript(map); } }; void AddSC_instance_molten_core() { new instance_molten_core(); } <commit_msg>fix(Scripts/MoltenCore): Boss' runes should not respawn after 5 min o… (#13127)<commit_after>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 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 Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "InstanceScript.h" #include "ObjectMgr.h" #include "ScriptMgr.h" #include "TemporarySummon.h" #include "molten_core.h" MinionData const minionData[] = { { NPC_FIRESWORN, DATA_GARR }, { NPC_FLAMEWALKER, DATA_GEHENNAS }, { NPC_FLAMEWALKER_PROTECTOR, DATA_LUCIFRON }, { NPC_FLAMEWALKER_PRIEST, DATA_SULFURON }, { NPC_FLAMEWALKER_HEALER, DATA_MAJORDOMO_EXECUTUS }, { NPC_FLAMEWALKER_ELITE, DATA_MAJORDOMO_EXECUTUS }, { 0, 0 } // END }; struct MCBossObject { uint32 bossId; uint32 runeId; uint32 circleId; }; constexpr uint8 MAX_MC_LINKED_BOSS_OBJ = 7; MCBossObject const linkedBossObjData[MAX_MC_LINKED_BOSS_OBJ]= { { DATA_MAGMADAR, GO_RUNE_KRESS, GO_CIRCLE_MAGMADAR }, { DATA_GEHENNAS, GO_RUNE_MOHN, GO_CIRCLE_GEHENNAS }, { DATA_GARR, GO_RUNE_BLAZ, GO_CIRCLE_GARR }, { DATA_SHAZZRAH, GO_RUNE_MAZJ, GO_CIRCLE_SHAZZRAH }, { DATA_GEDDON, GO_RUNE_ZETH, GO_CIRCLE_GEDDON }, { DATA_GOLEMAGG, GO_RUNE_THERI, GO_CIRCLE_GOLEMAGG }, { DATA_SULFURON, GO_RUNE_KORO, GO_CIRCLE_SULFURON }, }; constexpr uint8 SAY_SPAWN = 1; class instance_molten_core : public InstanceMapScript { public: instance_molten_core() : InstanceMapScript(MCScriptName, 409) {} struct instance_molten_core_InstanceMapScript : public InstanceScript { instance_molten_core_InstanceMapScript(Map* map) : InstanceScript(map) { SetBossNumber(MAX_ENCOUNTER); LoadMinionData(minionData); } void OnPlayerEnter(Player* /*player*/) override { if (CheckMajordomoExecutus()) { SummonMajordomoExecutus(); } } void OnCreatureCreate(Creature* creature) override { switch (creature->GetEntry()) { case NPC_GOLEMAGG_THE_INCINERATOR: { _golemaggGUID = creature->GetGUID(); break; } case NPC_CORE_RAGER: { _golemaggMinionsGUIDS.insert(creature->GetGUID()); break; } case NPC_MAJORDOMO_EXECUTUS: { _majordomoExecutusGUID = creature->GetGUID(); break; } case NPC_GARR: { _garrGUID = creature->GetGUID(); break; } case NPC_RAGNAROS: { _ragnarosGUID = creature->GetGUID(); break; } case NPC_FIRESWORN: case NPC_FLAMEWALKER: case NPC_FLAMEWALKER_PROTECTOR: case NPC_FLAMEWALKER_PRIEST: case NPC_FLAMEWALKER_HEALER: case NPC_FLAMEWALKER_ELITE: { AddMinion(creature, true); break; } } } void OnCreatureRemove(Creature* creature) override { switch (creature->GetEntry()) { case NPC_FIRESWORN: { AddMinion(creature, false); break; } case NPC_FLAMEWALKER: case NPC_FLAMEWALKER_PROTECTOR: case NPC_FLAMEWALKER_PRIEST: case NPC_FLAMEWALKER_HEALER: case NPC_FLAMEWALKER_ELITE: { AddMinion(creature, false); break; } } } void OnGameObjectCreate(GameObject* go) override { switch (go->GetEntry()) { case GO_CACHE_OF_THE_FIRELORD: { _cacheOfTheFirelordGUID = go->GetGUID(); break; } case GO_CIRCLE_GEDDON: case GO_CIRCLE_GARR: case GO_CIRCLE_GEHENNAS: case GO_CIRCLE_GOLEMAGG: case GO_CIRCLE_MAGMADAR: case GO_CIRCLE_SHAZZRAH: case GO_CIRCLE_SULFURON: { for (uint8 i = 0; i < MAX_MC_LINKED_BOSS_OBJ; ++i) { if (linkedBossObjData[i].circleId != go->GetEntry()) { continue; } if (GetBossState(linkedBossObjData[i].bossId) == DONE) { go->DespawnOrUnsummon(0ms, Seconds(WEEK)); } else { _circlesGUIDs[linkedBossObjData[i].bossId] = go->GetGUID(); } } break; } case GO_RUNE_KRESS: case GO_RUNE_MOHN: case GO_RUNE_BLAZ: case GO_RUNE_MAZJ: case GO_RUNE_ZETH: case GO_RUNE_THERI: case GO_RUNE_KORO: { for (uint8 i = 0; i < MAX_MC_LINKED_BOSS_OBJ; ++i) { if (linkedBossObjData[i].runeId != go->GetEntry()) { continue; } if (GetBossState(linkedBossObjData[i].bossId) == DONE) { go->UseDoorOrButton(WEEK * IN_MILLISECONDS); } else { _runesGUIDs[linkedBossObjData[i].bossId] = go->GetGUID(); } } break; } case GO_LAVA_STEAM: { _lavaSteamGUID = go->GetGUID(); break; } case GO_LAVA_SPLASH: { _lavaSplashGUID = go->GetGUID(); break; } case GO_LAVA_BURST: { if (Creature* ragnaros = instance->GetCreature(_ragnarosGUID)) { ragnaros->AI()->SetGUID(go->GetGUID(), GO_LAVA_BURST); } break; } } } ObjectGuid GetGuidData(uint32 type) const override { switch (type) { case DATA_GOLEMAGG: return _golemaggGUID; case DATA_MAJORDOMO_EXECUTUS: return _majordomoExecutusGUID; case DATA_GARR: return _garrGUID; case DATA_LAVA_STEAM: return _lavaSteamGUID; case DATA_LAVA_SPLASH: return _lavaSplashGUID; case DATA_RAGNAROS: return _ragnarosGUID; } return ObjectGuid::Empty; } bool SetBossState(uint32 bossId, EncounterState state) override { if (!InstanceScript::SetBossState(bossId, state)) { return false; } if (bossId == DATA_MAJORDOMO_EXECUTUS && state == DONE) { DoRespawnGameObject(_cacheOfTheFirelordGUID, 7 * DAY); } else if (bossId == DATA_GOLEMAGG) { switch (state) { case NOT_STARTED: case FAIL: { if (!_golemaggMinionsGUIDS.empty()) { for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS) { Creature* minion = instance->GetCreature(minionGuid); if (minion && minion->isDead()) { minion->Respawn(); } } } break; } case IN_PROGRESS: { if (!_golemaggMinionsGUIDS.empty()) { for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS) { if (Creature* minion = instance->GetCreature(minionGuid)) { minion->AI()->DoZoneInCombat(nullptr, 150.0f); } } } break; } case DONE: { if (!_golemaggMinionsGUIDS.empty()) { for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS) { if (Creature* minion = instance->GetCreature(minionGuid)) { minion->CastSpell(minion, SPELL_CORE_RAGER_QUIET_SUICIDE, true); } } _golemaggMinionsGUIDS.clear(); } break; } default: break; } } // Perform needed checks for Majordomu if (bossId < DATA_MAJORDOMO_EXECUTUS && state == DONE) { if (GameObject* circle = instance->GetGameObject(_circlesGUIDs[bossId])) { circle->DespawnOrUnsummon(0ms, Seconds(WEEK)); _circlesGUIDs[bossId].Clear(); } if (GameObject* rune = instance->GetGameObject(_runesGUIDs[bossId])) { rune->UseDoorOrButton(WEEK * IN_MILLISECONDS); _runesGUIDs[bossId].Clear(); } if (CheckMajordomoExecutus()) { SummonMajordomoExecutus(); } } return true; } void DoAction(int32 action) override { if (action == ACTION_RESET_GOLEMAGG_ENCOUNTER) { if (Creature* golemagg = instance->GetCreature(_golemaggGUID)) { golemagg->AI()->EnterEvadeMode(); } if (!_golemaggMinionsGUIDS.empty()) { for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS) { if (Creature* minion = instance->GetCreature(minionGuid)) { minion->AI()->EnterEvadeMode(); } } } } } void SummonMajordomoExecutus() { if (instance->GetCreature(_majordomoExecutusGUID)) { return; } if (GetBossState(DATA_MAJORDOMO_EXECUTUS) != DONE) { if (Creature* creature = instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, MajordomoSummonPos)) { creature->AI()->Talk(SAY_SPAWN); } } else { instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, MajordomoRagnaros); } } bool CheckMajordomoExecutus() const { if (GetBossState(DATA_RAGNAROS) == DONE) { return false; } for (uint8 i = 0; i < DATA_MAJORDOMO_EXECUTUS; ++i) { if (i == DATA_LUCIFRON) { continue; } if (GetBossState(i) != DONE) { return false; } } // Prevent spawning if Ragnaros is present if (instance->GetCreature(_ragnarosGUID)) { return false; } return true; } std::string GetSaveData() override { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "M C " << GetBossSaveData(); OUT_SAVE_INST_DATA_COMPLETE; return saveStream.str(); } void Load(char const* data) override { if (!data) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(data); char dataHead1, dataHead2; std::istringstream loadStream(data); loadStream >> dataHead1 >> dataHead2; if (dataHead1 == 'M' && dataHead2 == 'C') { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { uint32 tmpState; loadStream >> tmpState; if (tmpState == IN_PROGRESS || tmpState > TO_BE_DECIDED) { tmpState = NOT_STARTED; } SetBossState(i, static_cast<EncounterState>(tmpState)); } if (CheckMajordomoExecutus()) { SummonMajordomoExecutus(); } } else { OUT_LOAD_INST_DATA_FAIL; } OUT_LOAD_INST_DATA_COMPLETE; } private: std::unordered_map<uint32/*bossid*/, ObjectGuid/*circleGUID*/> _circlesGUIDs; std::unordered_map<uint32/*bossid*/, ObjectGuid/*runeGUID*/> _runesGUIDs; // Golemagg encounter related ObjectGuid _golemaggGUID; GuidSet _golemaggMinionsGUIDS; // Ragnaros encounter related ObjectGuid _ragnarosGUID; ObjectGuid _lavaSteamGUID; ObjectGuid _lavaSplashGUID; ObjectGuid _majordomoExecutusGUID; ObjectGuid _cacheOfTheFirelordGUID; ObjectGuid _garrGUID; ObjectGuid _magmadarGUID; }; InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_molten_core_InstanceMapScript(map); } }; void AddSC_instance_molten_core() { new instance_molten_core(); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "SpectralUnmixing.h" // Qt #include <QMessageBox> // mitk image #include <mitkImage.h> // Include to perform Spectral Unmixing #include "mitkPASpectralUnmixingFilterBase.h" #include "mitkPALinearSpectralUnmixingFilter.h" #include "mitkPASpectralUnmixingSO2.h" const std::string SpectralUnmixing::VIEW_ID = "org.mitk.views.spectralunmixing"; void SpectralUnmixing::SetFocus() { m_Controls.buttonPerformImageProcessing->setFocus(); } void SpectralUnmixing::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); connect(m_Controls.buttonPerformImageProcessing, &QPushButton::clicked, this, &SpectralUnmixing::DoImageProcessing); connect(m_Controls.ButtonAddWavelength, &QPushButton::clicked, this, &SpectralUnmixing::Wavelength); connect(m_Controls.ButtonClearWavelength, &QPushButton::clicked, this, &SpectralUnmixing::ClearWavelength); } // Adds Wavelength @ Plugin with button void SpectralUnmixing::Wavelength() { if (m_Wavelengths.empty()) { size = 0; } unsigned int wavelength = m_Controls.spinBoxAddWavelength->value(); m_Wavelengths.push_back(wavelength); size += 1; // size implemented like this because '.size' is const MITK_INFO << "ALL WAVELENGTHS: "; for (int i = 0; i < size; ++i) { MITK_INFO << m_Wavelengths[i] << "nm"; } } void SpectralUnmixing::ClearWavelength() { m_Wavelengths.clear(); } void SpectralUnmixing::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/, const QList<mitk::DataNode::Pointer> &nodes) { // iterate all selected objects, adjust warning visibility foreach (mitk::DataNode::Pointer node, nodes) { if (node.IsNotNull() && dynamic_cast<mitk::Image *>(node->GetData())) { m_Controls.labelWarning->setVisible(false); m_Controls.buttonPerformImageProcessing->setEnabled(true); return; } } m_Controls.labelWarning->setVisible(true); m_Controls.buttonPerformImageProcessing->setEnabled(false); } void SpectralUnmixing::DoImageProcessing() { QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection(); if (nodes.empty()) return; mitk::DataNode *node = nodes.front(); if (!node) { // Nothing selected. Inform the user and return QMessageBox::information(nullptr, "Template", "Please load and select an image before starting image processing."); return; } // here we have a valid mitk::DataNode // a node itself is not very useful, we need its data item (the image) mitk::BaseData *data = node->GetData(); if (data) { // test if this data item is an image or not (could also be a surface or something totally different) mitk::Image *image = dynamic_cast<mitk::Image *>(data); if (image) { std::stringstream message; std::string name; message << "PERFORMING SPECTRAL UNMIXING "; if (node->GetName(name)) { // a property called "name" was found for this DataNode message << "'" << name << "'"; } message << "."; MITK_INFO << message.str(); auto m_SpectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New(); m_SpectralUnmixingFilter->SetInput(image); // Set Algortihm to filter auto qs = m_Controls.QComboBoxAlgorithm->currentText(); std::string Algorithm = qs.toUtf8().constData(); if (Algorithm == "householderQr") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::householderQr); else if (Algorithm == "ldlt") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::ldlt); else if (Algorithm == "llt") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::llt); else if (Algorithm == "colPivHouseholderQr") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::colPivHouseholderQr); else if (Algorithm == "jacobiSvd") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::jacobiSvd); else if (Algorithm == "fullPivLu") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivLu); else if (Algorithm == "fullPivHouseholderQr") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivHouseholderQr); else if (Algorithm == "test") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::test); else mitkThrow() << "ALGORITHM ERROR!"; // Wavelength implementation into filter for (unsigned int imageIndex = 0; imageIndex < m_Wavelengths.size(); imageIndex++) { unsigned int wavelength = m_Wavelengths[imageIndex]; m_SpectralUnmixingFilter->AddWavelength(wavelength); } // Checking which chromophores wanted for SU if none throw exeption! unsigned int numberofChromophores = 0; DeOxbool = m_Controls.checkBoxDeOx->isChecked(); Oxbool = m_Controls.checkBoxOx->isChecked(); if (DeOxbool || Oxbool) { MITK_INFO << "CHOSEN CHROMOPHORES:"; } if (Oxbool) { numberofChromophores += 1; MITK_INFO << "- Oxyhemoglobin"; // Set chromophore Oxyhemoglobon: m_SpectralUnmixingFilter->AddChromophore( mitk::pa::SpectralUnmixingFilterBase::ChromophoreType::OXYGENATED_HEMOGLOBIN); } if (DeOxbool) { numberofChromophores += 1; MITK_INFO << "- Deoxygenated hemoglobin"; // Set chromophore Deoxygenated hemoglobin: m_SpectralUnmixingFilter->AddChromophore( mitk::pa::SpectralUnmixingFilterBase::ChromophoreType::DEOXYGENATED_HEMOGLOBIN); } if (numberofChromophores == 0) { mitkThrow() << "PRESS 'IGNORE' AND CHOOSE A CHROMOPHORE!"; } MITK_INFO << "Updating Filter..."; m_SpectralUnmixingFilter->Update(); if (Oxbool) { mitk::Image::Pointer HbO2 = m_SpectralUnmixingFilter->GetOutput(0); mitk::DataNode::Pointer dataNodeHbO2 = mitk::DataNode::New(); dataNodeHbO2->SetData(HbO2); dataNodeHbO2->SetName("HbO2"); this->GetDataStorage()->Add(dataNodeHbO2); } if (DeOxbool) { mitk::Image::Pointer Hb = m_SpectralUnmixingFilter->GetOutput(1); mitk::DataNode::Pointer dataNodeHb = mitk::DataNode::New(); dataNodeHb->SetData(Hb); dataNodeHb->SetName("Hb"); this->GetDataStorage()->Add(dataNodeHb); } //mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage()); //*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //FRAGE zu SetInput: reicht es dort einen image pointer anzugeben? //wenn ja zweite Variante wenn nein dann erste. funktioniern aber leider beide nicht:/ bool sO2bool = m_Controls.checkBoxsO2->isChecked(); //1: /* mitk::Image::Pointer HbO2 = m_SpectralUnmixingFilter->GetOutput(0); mitk::DataNode::Pointer dataNodeHbO2 = mitk::DataNode::New(); dataNodeHbO2->SetData(HbO2); mitk::BaseData *dataHbO2 = dataNodeHbO2->GetData(); mitk::Image *imageHbO2 = dynamic_cast<mitk::Image *>(dataHbO2); mitk::Image::Pointer Hb = m_SpectralUnmixingFilter->GetOutput(1); mitk::DataNode::Pointer dataNodeHb = mitk::DataNode::New(); dataNodeHb->SetData(Hb); mitk::BaseData *dataHb = dataNodeHb->GetData(); mitk::Image *imageHb = dynamic_cast<mitk::Image *>(dataHb); auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New(); m_sO2->SetInput(0,imageHbO2); m_sO2->SetInput(1,imageHb); m_sO2->Update(); mitk::Image::Pointer sO2 = m_sO2->GetOutput(0); mitk::DataNode::Pointer dataNodesO2 = mitk::DataNode::New(); dataNodesO2->SetData(sO2); dataNodesO2->SetName("sO2"); this->GetDataStorage()->Add(dataNodesO2);/**/ //2: /* if (sO2bool) { if (DeOxbool) { if (Oxbool) { MITK_INFO << "CALCULATE OXYGEN SATURATION ..."; auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New(); m_sO2->SetInput(0, m_SpectralUnmixingFilter->GetOutput(0)); m_sO2->SetInput(1, m_SpectralUnmixingFilter->GetOutput(1)); //http://docs.mitk.org/nightly/PipelineingConceptPage.html //m_SpectralUnmixingFilter->Update(); //m_sO2->SetInput(m_SpectralUnmixingFilter->GetOutput()); m_sO2->Update(); mitk::Image::Pointer sO2 = m_sO2->GetOutput(0); mitk::DataNode::Pointer dataNodesO2 = mitk::DataNode::New(); dataNodesO2->SetData(sO2); dataNodesO2->SetName("sO2"); this->GetDataStorage()->Add(dataNodesO2); MITK_INFO << "[DONE]"; } else mitkThrow() << "SELECT CHROMOPHORE OXYHEMOGLOBIN!"; } else mitkThrow() << "SELECT CHROMOPHORE DEOXYHEMOGLOBIN!"; } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());/**/ //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/**/ MITK_INFO << "Adding images to DataStorage...[DONE]"; } } } <commit_msg>changed name of output files and solved rendering.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "SpectralUnmixing.h" // Qt #include <QMessageBox> // mitk image #include <mitkImage.h> // Include to perform Spectral Unmixing #include "mitkPASpectralUnmixingFilterBase.h" #include "mitkPALinearSpectralUnmixingFilter.h" #include "mitkPASpectralUnmixingSO2.h" const std::string SpectralUnmixing::VIEW_ID = "org.mitk.views.spectralunmixing"; void SpectralUnmixing::SetFocus() { m_Controls.buttonPerformImageProcessing->setFocus(); } void SpectralUnmixing::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); connect(m_Controls.buttonPerformImageProcessing, &QPushButton::clicked, this, &SpectralUnmixing::DoImageProcessing); connect(m_Controls.ButtonAddWavelength, &QPushButton::clicked, this, &SpectralUnmixing::Wavelength); connect(m_Controls.ButtonClearWavelength, &QPushButton::clicked, this, &SpectralUnmixing::ClearWavelength); } // Adds Wavelength @ Plugin with button void SpectralUnmixing::Wavelength() { if (m_Wavelengths.empty()) { size = 0; } unsigned int wavelength = m_Controls.spinBoxAddWavelength->value(); m_Wavelengths.push_back(wavelength); size += 1; // size implemented like this because '.size' is const MITK_INFO << "ALL WAVELENGTHS: "; for (int i = 0; i < size; ++i) { MITK_INFO << m_Wavelengths[i] << "nm"; } } void SpectralUnmixing::ClearWavelength() { m_Wavelengths.clear(); } void SpectralUnmixing::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/, const QList<mitk::DataNode::Pointer> &nodes) { // iterate all selected objects, adjust warning visibility foreach (mitk::DataNode::Pointer node, nodes) { if (node.IsNotNull() && dynamic_cast<mitk::Image *>(node->GetData())) { m_Controls.labelWarning->setVisible(false); m_Controls.buttonPerformImageProcessing->setEnabled(true); return; } } m_Controls.labelWarning->setVisible(true); m_Controls.buttonPerformImageProcessing->setEnabled(false); } void SpectralUnmixing::DoImageProcessing() { QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection(); if (nodes.empty()) return; mitk::DataNode *node = nodes.front(); if (!node) { // Nothing selected. Inform the user and return QMessageBox::information(nullptr, "Template", "Please load and select an image before starting image processing."); return; } // here we have a valid mitk::DataNode // a node itself is not very useful, we need its data item (the image) mitk::BaseData *data = node->GetData(); if (data) { // test if this data item is an image or not (could also be a surface or something totally different) mitk::Image *image = dynamic_cast<mitk::Image *>(data); if (image) { std::stringstream message; std::string name; message << "PERFORMING SPECTRAL UNMIXING "; if (node->GetName(name)) { // a property called "name" was found for this DataNode message << "'" << name << "'"; } message << "."; MITK_INFO << message.str(); auto m_SpectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New(); m_SpectralUnmixingFilter->SetInput(image); // Set Algortihm to filter auto qs = m_Controls.QComboBoxAlgorithm->currentText(); std::string Algorithm = qs.toUtf8().constData(); if (Algorithm == "householderQr") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::householderQr); else if (Algorithm == "ldlt") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::ldlt); else if (Algorithm == "llt") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::llt); else if (Algorithm == "colPivHouseholderQr") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::colPivHouseholderQr); else if (Algorithm == "jacobiSvd") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::jacobiSvd); else if (Algorithm == "fullPivLu") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivLu); else if (Algorithm == "fullPivHouseholderQr") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivHouseholderQr); else if (Algorithm == "test") m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::test); else mitkThrow() << "ALGORITHM ERROR!"; // Wavelength implementation into filter for (unsigned int imageIndex = 0; imageIndex < m_Wavelengths.size(); imageIndex++) { unsigned int wavelength = m_Wavelengths[imageIndex]; m_SpectralUnmixingFilter->AddWavelength(wavelength); } // Checking which chromophores wanted for SU if none throw exeption! unsigned int numberofChromophores = 0; DeOxbool = m_Controls.checkBoxDeOx->isChecked(); Oxbool = m_Controls.checkBoxOx->isChecked(); if (DeOxbool || Oxbool) { MITK_INFO << "CHOSEN CHROMOPHORES:"; } if (Oxbool) { numberofChromophores += 1; MITK_INFO << "- Oxyhemoglobin"; // Set chromophore Oxyhemoglobon: m_SpectralUnmixingFilter->AddChromophore( mitk::pa::SpectralUnmixingFilterBase::ChromophoreType::OXYGENATED_HEMOGLOBIN); } if (DeOxbool) { numberofChromophores += 1; MITK_INFO << "- Deoxygenated hemoglobin"; // Set chromophore Deoxygenated hemoglobin: m_SpectralUnmixingFilter->AddChromophore( mitk::pa::SpectralUnmixingFilterBase::ChromophoreType::DEOXYGENATED_HEMOGLOBIN); } if (numberofChromophores == 0) { mitkThrow() << "PRESS 'IGNORE' AND CHOOSE A CHROMOPHORE!"; } MITK_INFO << "Updating Filter..."; m_SpectralUnmixingFilter->Update(); if (Oxbool) { mitk::Image::Pointer HbO2 = m_SpectralUnmixingFilter->GetOutput(0); mitk::DataNode::Pointer dataNodeHbO2 = mitk::DataNode::New(); dataNodeHbO2->SetData(HbO2); dataNodeHbO2->SetName("HbO2: " + Algorithm); this->GetDataStorage()->Add(dataNodeHbO2); } if (DeOxbool) { mitk::Image::Pointer Hb = m_SpectralUnmixingFilter->GetOutput(1); mitk::DataNode::Pointer dataNodeHb = mitk::DataNode::New(); dataNodeHb->SetData(Hb); dataNodeHb->SetName("Hb: " + Algorithm); this->GetDataStorage()->Add(dataNodeHb); } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage()); //*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //FRAGE zu SetInput: reicht es dort einen image pointer anzugeben? //wenn ja zweite Variante wenn nein dann erste. funktioniern aber leider beide nicht:/ bool sO2bool = m_Controls.checkBoxsO2->isChecked(); //1: /* mitk::Image::Pointer HbO2 = m_SpectralUnmixingFilter->GetOutput(0); mitk::DataNode::Pointer dataNodeHbO2 = mitk::DataNode::New(); dataNodeHbO2->SetData(HbO2); mitk::BaseData *dataHbO2 = dataNodeHbO2->GetData(); mitk::Image *imageHbO2 = dynamic_cast<mitk::Image *>(dataHbO2); mitk::Image::Pointer Hb = m_SpectralUnmixingFilter->GetOutput(1); mitk::DataNode::Pointer dataNodeHb = mitk::DataNode::New(); dataNodeHb->SetData(Hb); mitk::BaseData *dataHb = dataNodeHb->GetData(); mitk::Image *imageHb = dynamic_cast<mitk::Image *>(dataHb); auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New(); m_sO2->SetInput(0,imageHbO2); m_sO2->SetInput(1,imageHb); m_sO2->Update(); mitk::Image::Pointer sO2 = m_sO2->GetOutput(0); mitk::DataNode::Pointer dataNodesO2 = mitk::DataNode::New(); dataNodesO2->SetData(sO2); dataNodesO2->SetName("sO2"); this->GetDataStorage()->Add(dataNodesO2);/**/ //2: /* if (sO2bool) { if (DeOxbool) { if (Oxbool) { MITK_INFO << "CALCULATE OXYGEN SATURATION ..."; auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New(); m_sO2->SetInput(0, m_SpectralUnmixingFilter->GetOutput(0)); m_sO2->SetInput(1, m_SpectralUnmixingFilter->GetOutput(1)); //http://docs.mitk.org/nightly/PipelineingConceptPage.html //m_SpectralUnmixingFilter->Update(); //m_sO2->SetInput(m_SpectralUnmixingFilter->GetOutput()); m_sO2->Update(); mitk::Image::Pointer sO2 = m_sO2->GetOutput(0); mitk::DataNode::Pointer dataNodesO2 = mitk::DataNode::New(); dataNodesO2->SetData(sO2); dataNodesO2->SetName("sO2"); this->GetDataStorage()->Add(dataNodesO2); MITK_INFO << "[DONE]"; } else mitkThrow() << "SELECT CHROMOPHORE OXYHEMOGLOBIN!"; } else mitkThrow() << "SELECT CHROMOPHORE DEOXYHEMOGLOBIN!"; } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());/**/ //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/**/ MITK_INFO << "Adding images to DataStorage...[DONE]"; } } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Main.cxx // //////////////////////////////////////////////////////////////////////////////// // // Developed by Donnacha Forde (@DonnachaForde) // // Copyright 2006-2008, Donnacha Forde. All rights reserved. // // This software is provided 'as is' without warranty, expressed or implied. // Donnacha Forde accepts no responsibility for the use or reliability of this software. // //////////////////////////////////////////////////////////////////////////////// // espresso lib #include <espresso.hxx> using namespace espresso; // crt #include <cstdio> #include <cstdlib> #include <cassert> #include <iostream> #include <cctype> using namespace std; #include <errno.h> #ifdef WIN32 #include <io.h> #else #include <unistd.h> #endif // prototypes void ProcessFile(const Args& args); /******************************************************************************\ ****************************************************************************** ****************************************************************************** ********************************* MAIN ********************************* ****************************************************************************** ****************************************************************************** \******************************************************************************/ int main(int argc, char* argv[], char* envp[]) { // // arg parsing // Args args(argc, argv, "bin2txt", "Displays binary files in text format.", "1.0 (Beta)", "Donnacha Forde", "2005-2007", "@DonnachaForde"); // pick up default args/switches args.Initialize(); // specify our switches & aliases args.Add("columns", Arg::INTEGER, "Number of hexadecimal columns to display on each line.", true); args.Add("file", Arg::STRING, "Filename to modify.", true, "filename"); args.Add("text", Arg::NOARG, "Display text only."); args.Add("hex", Arg::NOARG, "Display hexadecimal only."); args.AddAlias("columns", 'c'); args.AddAlias("file", 'f'); args.AddAlias("text", 't'); args.AddAlias("hex", 'x'); // create argmgr to handle default switches ArgMgrCLI argMgr; if (!argMgr.ParseAndProcess(args)) { ::exit(0); } // check display preferences if (args.IsPresent("hex") && args.IsPresent("text")) { cout << "ERROR: Cannot display only hex and only text at once." << endl; argMgr.OnArgError(args); ::exit(0); } if (args.IsPresent("text") && args.IsPresent("columns")) { cout << "ERROR: Specifying number of columns in not applicable when displaying text only." << endl; argMgr.OnArgError(args); ::exit(0); } ProcessFile(args); return 0; } //------------------------------------------------------------------------------ // // Function : ProcessFile // // Return type : void // // Argument : const Args& args // // Description : // // Notes : // //------------------------------------------------------------------------------ void ProcessFile(const Args& args) { // // now use any args specified // bool IsDisplayHexOnly = args.IsPresent("hex"); bool IsDisplayTextOnly = args.IsPresent("text"); // default to 16 wide int nNumColumnsToDisplay = 16; if (args.IsPresent("columns")) { nNumColumnsToDisplay = args.GetNumericValue("columns"); } // handle the file/target FILE* fdIn = NULL; if (args.IsPresent("file") || args.IsTargetPresent()) { const char* szInputFilename = NULL; if (args.IsPresent("file")) { szInputFilename = args.GetStringValue("file").c_str(); } else { szInputFilename = args.GetTarget().c_str(); } // check the filename if (!espresso::strings::IsValidString(szInputFilename)) { cout << "ERROR: Unable to process empty filename." << endl; ::exit(-1); } // can we open the file for reading (and hence, does it even exist)... int nRetCode = ::access(szInputFilename, 04); if ((nRetCode == EACCES) || (nRetCode == ENOENT)) { cout << "ERROR: Either the file '" << szInputFilename << "' does not exist or is not available for reading purposes." << endl; ::exit(-1); } // open the file fdIn = ::fopen(szInputFilename, "rb"); assert(fdIn != NULL); if (fdIn == NULL) { cout << "ERROR: Failed to open file: '" << szInputFilename << "' for reading." << endl; ::exit(-1); } } else { // use stdin fdIn = stdin; } // // main processing loop // ::setvbuf(stdin, NULL, _IOLBF, 0); ::setvbuf(stdout, NULL, _IOLBF, 0); int ch = 0; int nNumColumnsShown = 0; if (IsDisplayTextOnly) { while ((ch = ::fgetc(fdIn)) != EOF) { // if we're showing text, we must handle CR/LF (for this we must read ahead by one char, hence the two similar 'else' clauses if ((char)ch == '\\') { // read next char ch = ::fgetc(fdIn); if ((char)ch == 'n') { ::fprintf(stdout, "\n"); } else { // if not a printable char, substitute with a dot if (isprint(ch)) { ::fprintf(stdout, "\\%c", (char)ch); } else { ::fprintf(stdout, "\\."); } } } else { if (isprint(ch)) { ::fprintf(stdout, "%c", (char)ch); } else { ::fprintf(stdout, "."); } } } } else { // create buffer for string representation char* szBuffer = new char[nNumColumnsToDisplay + 1]; ::memset(szBuffer, 0, (nNumColumnsToDisplay + 1)); char* pch = szBuffer; while ((ch = ::fgetc(fdIn)) != EOF) { // build up string representation if (!IsDisplayHexOnly) { // if not a printable char, substitute with a dot if (!isprint(ch)) { ch = '.'; } *pch++ = (char)ch; } // display the hex representation ::fprintf(stdout, "%02x ", ch); // handle column display logic nNumColumnsShown++; if (nNumColumnsShown == nNumColumnsToDisplay) { assert(::strlen(szBuffer) <= nNumColumnsToDisplay); ::fprintf(stdout, " %s\n", szBuffer); nNumColumnsShown = 0; ::memset(szBuffer, 0, (nNumColumnsToDisplay + 1)); pch = szBuffer; } } // write blank columns at end where necessary for (int i = nNumColumnsToDisplay; i > nNumColumnsShown; i--) { ::fprintf(stdout, " "); } // deal with stragling buffer szBuffer[nNumColumnsShown] = '\0'; ::fprintf(stdout, " %s\n", szBuffer); // // tidy up // delete [] szBuffer; } ::fclose(fdIn); ::fclose(stdout); return; } <commit_msg>Explicity disable CRT Security Warnings.<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Main.cxx // //////////////////////////////////////////////////////////////////////////////// // // Developed by Donnacha Forde (@DonnachaForde) // // Copyright 2006-2008, Donnacha Forde. All rights reserved. // // This software is provided 'as is' without warranty, expressed or implied. // Donnacha Forde accepts no responsibility for the use or reliability of this software. // //////////////////////////////////////////////////////////////////////////////// // disable newer warnings #ifdef WIN32 #pragma message("note : CRT security warning (so we can use ol'fashion 'C' calls)") #define _CRT_SECURE_NO_WARNINGS #endif // espresso lib #include <espresso.hxx> using namespace espresso; // crt #include <cstdio> #include <cstdlib> #include <cassert> #include <iostream> #include <cctype> using namespace std; #include <errno.h> #ifdef WIN32 #include <io.h> #else #include <unistd.h> #endif // prototypes void ProcessFile(const Args& args); /******************************************************************************\ ****************************************************************************** ****************************************************************************** ********************************* MAIN ********************************* ****************************************************************************** ****************************************************************************** \******************************************************************************/ int main(int argc, char* argv[], char* envp[]) { // // arg parsing // Args args(argc, argv, "bin2txt", "Displays binary files in text format.", "1.0 (Beta)", "Donnacha Forde", "2005-2007", "@DonnachaForde"); // pick up default args/switches args.Initialize(); // specify our switches & aliases args.Add("columns", Arg::INTEGER, "Number of hexadecimal columns to display on each line.", true); args.Add("file", Arg::STRING, "Filename to modify.", true, "filename"); args.Add("text", Arg::NOARG, "Display text only."); args.Add("hex", Arg::NOARG, "Display hexadecimal only."); args.AddAlias("columns", 'c'); args.AddAlias("file", 'f'); args.AddAlias("text", 't'); args.AddAlias("hex", 'x'); // create argmgr to handle default switches ArgMgrCLI argMgr; if (!argMgr.ParseAndProcessArgs(args)) { ::exit(0); } // check display preferences if (args.IsPresent("hex") && args.IsPresent("text")) { cout << "ERROR: Cannot display only hex and only text at once." << endl; argMgr.OnArgError(args); ::exit(0); } if (args.IsPresent("text") && args.IsPresent("columns")) { cout << "ERROR: Specifying number of columns in not applicable when displaying text only." << endl; argMgr.OnArgError(args); ::exit(0); } ProcessFile(args); return 0; } //------------------------------------------------------------------------------ // // Function : ProcessFile // // Return type : void // // Argument : const Args& args // // Description : // // Notes : // //------------------------------------------------------------------------------ void ProcessFile(const Args& args) { // // now use any args specified // bool IsDisplayHexOnly = args.IsPresent("hex"); bool IsDisplayTextOnly = args.IsPresent("text"); // default to 16 wide int nNumColumnsToDisplay = 16; if (args.IsPresent("columns")) { nNumColumnsToDisplay = args.GetNumericValue("columns"); } // handle the file/target FILE* fdIn = NULL; if (args.IsPresent("file") || args.IsTargetPresent()) { const char* szInputFilename = NULL; if (args.IsPresent("file")) { szInputFilename = args.GetStringValue("file").c_str(); } else { szInputFilename = args.GetTarget().c_str(); } // check the filename if (!espresso::strings::IsValidString(szInputFilename)) { cout << "ERROR: Unable to process empty filename." << endl; ::exit(-1); } // can we open the file for reading (and hence, does it even exist)... int nRetCode = ::access(szInputFilename, 04); if ((nRetCode == EACCES) || (nRetCode == ENOENT)) { cout << "ERROR: Either the file '" << szInputFilename << "' does not exist or is not available for reading purposes." << endl; ::exit(-1); } // open the file fdIn = ::fopen(szInputFilename, "rb"); assert(fdIn != NULL); if (fdIn == NULL) { cout << "ERROR: Failed to open file: '" << szInputFilename << "' for reading." << endl; ::exit(-1); } } else { // use stdin fdIn = stdin; } // // main processing loop // ::setvbuf(stdin, NULL, _IOLBF, 0); ::setvbuf(stdout, NULL, _IOLBF, 0); int ch = 0; int nNumColumnsShown = 0; if (IsDisplayTextOnly) { while ((ch = ::fgetc(fdIn)) != EOF) { // if we're showing text, we must handle CR/LF (for this we must read ahead by one char, hence the two similar 'else' clauses if ((char)ch == '\\') { // read next char ch = ::fgetc(fdIn); if ((char)ch == 'n') { ::fprintf(stdout, "\n"); } else { // if not a printable char, substitute with a dot if (isprint(ch)) { ::fprintf(stdout, "\\%c", (char)ch); } else { ::fprintf(stdout, "\\."); } } } else { if (isprint(ch)) { ::fprintf(stdout, "%c", (char)ch); } else { ::fprintf(stdout, "."); } } } } else { // create buffer for string representation char* szBuffer = new char[nNumColumnsToDisplay + 1]; ::memset(szBuffer, 0, (nNumColumnsToDisplay + 1)); char* pch = szBuffer; while ((ch = ::fgetc(fdIn)) != EOF) { // build up string representation if (!IsDisplayHexOnly) { // if not a printable char, substitute with a dot if (!isprint(ch)) { ch = '.'; } *pch++ = (char)ch; } // display the hex representation ::fprintf(stdout, "%02x ", ch); // handle column display logic nNumColumnsShown++; if (nNumColumnsShown == nNumColumnsToDisplay) { assert(::strlen(szBuffer) <= nNumColumnsToDisplay); ::fprintf(stdout, " %s\n", szBuffer); nNumColumnsShown = 0; ::memset(szBuffer, 0, (nNumColumnsToDisplay + 1)); pch = szBuffer; } } // write blank columns at end where necessary for (int i = nNumColumnsToDisplay; i > nNumColumnsShown; i--) { ::fprintf(stdout, " "); } // deal with stragling buffer szBuffer[nNumColumnsShown] = '\0'; ::fprintf(stdout, " %s\n", szBuffer); // // tidy up // delete [] szBuffer; } ::fclose(fdIn); ::fclose(stdout); return; } <|endoftext|>
<commit_before>// ======================================================================================== // ApproxMVBB // Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz // (døt) ch> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // ======================================================================================== #include <iostream> #include "ApproxMVBB/ComputeApproxMVBB.hpp" int main(int argc, char** argv) { unsigned int nPoints = 100000; std::cout << "Sample " << nPoints << " points in unite cube (coordinates are in world frame I) " << std::endl; ApproxMVBB::Matrix3Dyn points(3, nPoints); points.setRandom(); ApproxMVBB::OOBB oobb = ApproxMVBB::approximateMVBB(points, 0.001, 500, 5 /*increasing the grid size decreases speed */ , 0, 5); std::cout << "Computed OOBB: " << std::endl << "---> lower point in OOBB frame: " << oobb.m_minPoint.transpose() << std::endl << "---> upper point in OOBB frame: " << oobb.m_maxPoint.transpose() << std::endl << "---> coordinate transformation A_IK matrix from OOBB frame K " "to world frame I" << std::endl << oobb.m_q_KI.matrix() << std::endl << "---> this is also the rotation matrix R_KI which turns the " "world frame I into the OOBB frame K" << std::endl << std::endl; // To make all points inside the OOBB : ApproxMVBB::Matrix33 A_KI = oobb.m_q_KI.matrix().transpose(); // faster to store the transformation matrix first auto size = points.cols(); for (unsigned int i = 0; i < size; ++i) { oobb.unite(A_KI * points.col(i)); } std::cout << "OOBB with all point included: " << std::endl << "---> lower point in OOBB frame: " << oobb.m_minPoint.transpose() << std::endl << "---> upper point in OOBB frame: " << oobb.m_maxPoint.transpose() << std::endl; return 0; } <commit_msg>Documentation<commit_after>// ======================================================================================== // ApproxMVBB // Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz // (døt) ch> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // ======================================================================================== #include <iostream> #include "ApproxMVBB/ComputeApproxMVBB.hpp" int main(int argc, char** argv) { unsigned int nPoints = 100000; std::cout << "Sample " << nPoints << " points in unite cube (coordinates are in world frame I) " << std::endl; ApproxMVBB::Matrix3Dyn points(3, nPoints); points.setRandom(); ApproxMVBB::OOBB oobb = ApproxMVBB::approximateMVBB(points, 0.001, 500, 5, /*increasing the grid size decreases speed */ 0, 5); std::cout << "Computed OOBB: " << std::endl << "---> lower point in OOBB frame: " << oobb.m_minPoint.transpose() << std::endl << "---> upper point in OOBB frame: " << oobb.m_maxPoint.transpose() << std::endl << "---> coordinate transformation A_IK matrix from OOBB frame K " "to world frame I" << std::endl << oobb.m_q_KI.matrix() << std::endl << "---> this is also the rotation matrix R_KI which turns the " "world frame I into the OOBB frame K" << std::endl << std::endl; // To make all points inside the OOBB : ApproxMVBB::Matrix33 A_KI = oobb.m_q_KI.matrix().transpose(); // faster to store the transformation matrix first auto size = points.cols(); for (unsigned int i = 0; i < size; ++i) { oobb.unite(A_KI * points.col(i)); } std::cout << "OOBB with all point included: " << std::endl << "---> lower point in OOBB frame: " << oobb.m_minPoint.transpose() << std::endl << "---> upper point in OOBB frame: " << oobb.m_maxPoint.transpose() << std::endl; return 0; } <|endoftext|>
<commit_before>#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/opencv.hpp> #include "opencv2/nonfree/nonfree.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/nonfree/features2d.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <opencv2/legacy/legacy.hpp> #include <math.h> #include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <fstream> //--------------------- Classes --------------------- class MovObj{ private: int h, w; int area; cv::Point2f square_origin; cv::Point2f center; cv::Point2f vel; cv::Mat template_obj; public: MovObj(int h_, int w_, int area_){ //center = center_; //square_origin = square_origin_; h = h_; w = w_; area = area_; } //~MovObj(); int get_height(){ return(h); } int get_width(){ return(w); } int get_area(){ return(area); } }; class Opt_flow { private: cv::VideoCapture video; cv::String filename; cv::Mat frame; cv::Mat opt_flow,flow_mask,cont_mask; cv::Mat prev_frame,next_frame; cv::Mat x_vals,y_vals; std::vector<float> vel_x; std::vector<float> vel_y; float std_error; cv::Vec3b frame_intensity,next_frame_intensity; float errors; int counter; CvSize win_size; int step,interval_pixels,tam_vel; int kernel_size; int threshold,ratio; int pyr_scale, levels, winsize, iterations, poly_n, poly_sigma; std::vector<cv::Vec4i> hierarchy; std::vector<std::vector<cv::Point> > contours; std::vector<MovObj> mov_objects; public: Opt_flow(cv::VideoCapture video_ , cv::String filename_) { cv::namedWindow("Video"); cv::namedWindow("OPT_FLOW"); cv::namedWindow("Contours"); cv::namedWindow("Trackbars"); //cv::namedWindow("OPT_FLOW-X"); //cv::namedWindow("OPT_FLOW-Y"); video=video_; filename=filename_; std_error=80; counter=0; std_error=(std_error/100); win_size.height=3; win_size.width=3; kernel_size=3; interval_pixels=2; tam_vel=1; step=5; threshold=2; ratio=1; pyr_scale = 5; //Will be divided for 10 levels = 3; winsize = 15; iterations = 3; poly_n = 5; poly_sigma = 1.2; video.open(filename); } ~Opt_flow(){ cv::destroyWindow("Video"); //cv::destroyWindow("OPT_FLOW-X"); //cv::destroyWindow("OPT_FLOW-Y"); cv::destroyWindow("OPT_FLOW"); cv::destroyWindow("Contours"); cv::destroyWindow("Trackbars"); } void play(){ int i=0; while (char(cv::waitKey(1))!='q'&&video.isOpened()){ video >> frame; if (i==0){ cv::cvtColor(frame,prev_frame,cv::COLOR_BGR2GRAY); cv::GaussianBlur(prev_frame,prev_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT); } if(i!=0&&i%step==0){ getchar(); cv::cvtColor(frame,next_frame,cv::COLOR_BGR2GRAY); cv::GaussianBlur(next_frame,next_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT); //std::cout << "PREV_FRAME:" << prev_frame.size() << '|' << prev_frame.channels() << '\n'; //std::cout << "NEXT_FRAME:" << next_frame.size() << '|' << next_frame.channels() << '\n'; cv::calcOpticalFlowFarneback(prev_frame, next_frame, opt_flow, pyr_scale/10.0, levels, winsize, iterations, poly_n, poly_sigma, 0); //draw_flow(opt_flow,frame); get_xvals(opt_flow); get_yvals(opt_flow); generate_flowmask(x_vals,y_vals); cv::GaussianBlur(flow_mask,flow_mask,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT); cv::threshold(flow_mask,flow_mask,threshold, threshold*ratio,cv::THRESH_BINARY); flow_mask.convertTo(cont_mask,CV_8U); cv::findContours(cont_mask,contours, hierarchy, CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE); get_contours(flow_mask); create_trackbars(); show_frame(); //print_moving_objects_vector(); //getchar(); prev_frame=next_frame.clone(); } std::cout << "i = " << i << '\n'; i++; } } void show_frame(){ cv::imshow("Video",frame); cv::imshow("OPT_FLOW",flow_mask); cv::imshow("Contours",cont_mask); } void create_trackbars(){ cv::createTrackbar("Pyramid Scale", "Trackbars", &pyr_scale, 9); cv::createTrackbar("Levels", "Trackbars", &levels, 10); cv::createTrackbar("Window Size", "Trackbars", &winsize, 50); cv::createTrackbar("Iterations", "Trackbars", &iterations, 10); cv::createTrackbar("Pixel Neighborhood Size", "Trackbars", &poly_n, 10); } void background_extr(){ int i,j,aux_error; for(i=0;i<(frame.rows)-1;i++){ for(j=0;j<(frame.cols)-1;j++){ counter++; frame_intensity = frame.at<uint>(i,j); next_frame_intensity = next_frame.at<uint>(i,j); if (next_frame_intensity.val[0]==0){ next_frame_intensity.val[0]=1; } errors=frame_intensity.val[0]/next_frame_intensity.val[0]; if(errors<1-std_error||errors>1+std_error){ opt_flow.at<uint>(i,j)=255; //std::cout << "MUDOU O PIXEL" << '\n'; } } } //std::cout << "TROCOU FRAME" << '\n'; } void blackfy(cv::Mat input){ for(int i=0;i<input.rows;i++){ for(int j=0;j<input.cols;j++){ input.at<uint>(i,j)=0; //std::cout << "(" << i << "," << j << ")" << '\n'; } } } void draw_flow(cv::Mat input, cv::Mat output){ for (int y = 0; y < output.rows; y += interval_pixels) { for (int x = 0; x < output.cols; x += interval_pixels) { const cv::Point2f flowatxy = input.at<cv::Point2f>(y, x) * tam_vel; cv::line(output, cv::Point(x, y), cv::Point(cvRound(x + flowatxy.x), cvRound(y + flowatxy.y)), cv::Scalar(255, 0, 0)); cv::circle(output, cv::Point(x, y), 1, cv::Scalar(0, 0, 0), -1); } } } void get_xvals(cv::Mat input){ x_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F); for (int i=0;i<input.rows;i++){ for(int j=0;j<input.cols;j++){ //std::cout << "X_VALS:" << x_vals.size() << '|' << x_vals.channels() << '|' << x_vals.type() << '\n'; x_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).x; } } } void get_yvals(cv::Mat input){ y_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F); for (int i=0;i<input.rows;i++){ for(int j=0;j<input.cols;j++){ //std::cout << "Y_VALS:" << y_vals.size() << '|' << y_vals.channels() << '|' << y_vals.type() << '\n'; y_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).y; } } } void generate_flowmask(cv::Mat x_matrix,cv::Mat y_matrix) { flow_mask=cv::Mat::zeros(x_matrix.rows,x_matrix.cols, CV_32F); for (int i=0;i<x_matrix.rows;i++){ for(int j=0;j<x_matrix.cols;j++){ flow_mask.at<float>(i,j)=magnitude(x_matrix.at<float>(i,j), y_matrix.at<float>(i,j)); } } } float magnitude(float a, float b){ float mag; mag=sqrt((a*a)+(b*b)); return(mag); } void get_contours(cv::Mat input){ std::vector<std::vector<cv::Point> > contours_poly(contours.size()); std::vector<cv::Rect> boundRect(contours.size()); for(int i=0;i<contours.size();i++){ cv::approxPolyDP(cv::Mat(contours[i]),contours_poly[i],3,true ); boundRect[i] = cv::boundingRect(cv::Mat(contours_poly[i])); draw_rectangles(boundRect); get_mov_obj(boundRect); } } void draw_rectangles(std::vector<cv::Rect> boundRect){ for(int i=0; i< contours.size(); i++ ){ rectangle(frame, boundRect[i].tl(), boundRect[i].br(), cv::Scalar(0,0,255), 2, 8, 0 ); } } void get_mov_obj(std::vector<cv::Rect> boundRect){ for (int i=0;i<contours.size();i++){ MovObj aux(boundRect[i].height,boundRect[i].width,boundRect[i].area()); mov_objects.push_back(aux); /*std::cout << "Object i=" << i << ':' << '\n'; std::cout << "Height:" << mov_objects[i].get_height() << '\n'; std::cout << "Width:" << mov_objects[i].get_width() << '\n'; getchar();*/ } } void print_moving_objects_vector(){ for(int i=0;i<mov_objects.size();i++){ std::cout << "i=" << i << '\n'; std::cout << "Height:" << mov_objects[i].get_height() << '\n'; std::cout << "Width:" << mov_objects[i].get_width() << '\n'; std::cout << "Area:" << mov_objects[i].get_area() << '\n'; std::cout << "----------------------------------" << '\n'; } } }; //--------------------- Global Variables --------------------- //--------------------- Main Function --------------------- int main(int argc, char *argv[]){ cv::String filename; cv::VideoCapture video; if (argc<=1){ std::cout << "\n\nThere was no input video to run.\nPress ENTER to quit.\n>>"; getchar(); return(-1); } filename=argv[1]; Opt_flow opt_flow(video,filename); opt_flow.play(); return(0); } <commit_msg>Getting moving objects square_origin and center<commit_after>#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/opencv.hpp> #include "opencv2/nonfree/nonfree.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/nonfree/features2d.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <opencv2/legacy/legacy.hpp> #include <math.h> #include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <fstream> //--------------------- Classes --------------------- class MovObj{ private: int h, w; int area; cv::Point2f square_origin; cv::Point2f center; cv::Point2f vel; cv::Mat template_obj; public: MovObj(cv::Point2f square_origin_,int h_, int w_, int area_){ //center = center_; //square_origin = square_origin_; h = h_; w = w_; area = area_; square_origin=square_origin_; center.x=((square_origin.x)+(square_origin.x+w))/2; center.y=((square_origin.y)+(square_origin.y+h))/2; } //~MovObj(); int get_height(){ return(h); } int get_width(){ return(w); } int get_area(){ return(area); } cv::Point2f get_origin(){ return(square_origin); } }; class Opt_flow { private: cv::VideoCapture video; cv::String filename; cv::Mat frame; cv::Mat opt_flow,flow_mask,cont_mask; cv::Mat prev_frame,next_frame; cv::Mat x_vals,y_vals; std::vector<float> vel_x; std::vector<float> vel_y; float std_error; cv::Vec3b frame_intensity,next_frame_intensity; float errors; int counter; CvSize win_size; int step,interval_pixels,tam_vel; int kernel_size; int threshold,ratio; int pyr_scale, levels, winsize, iterations, poly_n, poly_sigma; std::vector<cv::Vec4i> hierarchy; std::vector<std::vector<cv::Point> > contours; std::vector<MovObj> mov_objects; public: Opt_flow(cv::VideoCapture video_ , cv::String filename_) { cv::namedWindow("Video"); cv::namedWindow("OPT_FLOW"); cv::namedWindow("Contours"); cv::namedWindow("Trackbars"); //cv::namedWindow("OPT_FLOW-X"); //cv::namedWindow("OPT_FLOW-Y"); video=video_; filename=filename_; std_error=80; counter=0; std_error=(std_error/100); win_size.height=3; win_size.width=3; kernel_size=3; interval_pixels=2; tam_vel=1; step=5; threshold=2; ratio=1; pyr_scale = 5; //Will be divided for 10 levels = 3; winsize = 15; iterations = 3; poly_n = 5; poly_sigma = 1.2; video.open(filename); } ~Opt_flow(){ cv::destroyWindow("Video"); //cv::destroyWindow("OPT_FLOW-X"); //cv::destroyWindow("OPT_FLOW-Y"); cv::destroyWindow("OPT_FLOW"); cv::destroyWindow("Contours"); cv::destroyWindow("Trackbars"); } void play(){ int i=0; while (char(cv::waitKey(1))!='q'&&video.isOpened()){ video >> frame; if (i==0){ cv::cvtColor(frame,prev_frame,cv::COLOR_BGR2GRAY); cv::GaussianBlur(prev_frame,prev_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT); } if(i!=0&&i%step==0){ //getchar(); cv::cvtColor(frame,next_frame,cv::COLOR_BGR2GRAY); cv::GaussianBlur(next_frame,next_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT); //std::cout << "PREV_FRAME:" << prev_frame.size() << '|' << prev_frame.channels() << '\n'; //std::cout << "NEXT_FRAME:" << next_frame.size() << '|' << next_frame.channels() << '\n'; cv::calcOpticalFlowFarneback(prev_frame, next_frame, opt_flow, pyr_scale/10.0, levels, winsize, iterations, poly_n, poly_sigma, 0); //draw_flow(opt_flow,frame); get_xvals(opt_flow); get_yvals(opt_flow); generate_flowmask(x_vals,y_vals); cv::GaussianBlur(flow_mask,flow_mask,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT); cv::threshold(flow_mask,flow_mask,threshold, threshold*ratio,cv::THRESH_BINARY); flow_mask.convertTo(cont_mask,CV_8U); cv::findContours(cont_mask,contours, hierarchy, CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE); get_contours(flow_mask); create_trackbars(); show_frame(); //print_moving_objects_vector(); //getchar(); prev_frame=next_frame.clone(); } std::cout << "i = " << i << '\n'; i++; } } void show_frame(){ cv::imshow("Video",frame); cv::imshow("OPT_FLOW",flow_mask); cv::imshow("Contours",cont_mask); } void create_trackbars(){ cv::createTrackbar("Pyramid Scale", "Trackbars", &pyr_scale, 9); cv::createTrackbar("Levels", "Trackbars", &levels, 10); cv::createTrackbar("Window Size", "Trackbars", &winsize, 50); cv::createTrackbar("Iterations", "Trackbars", &iterations, 10); cv::createTrackbar("Pixel Neighborhood Size", "Trackbars", &poly_n, 10); } void background_extr(){ int i,j,aux_error; for(i=0;i<(frame.rows)-1;i++){ for(j=0;j<(frame.cols)-1;j++){ counter++; frame_intensity = frame.at<uint>(i,j); next_frame_intensity = next_frame.at<uint>(i,j); if (next_frame_intensity.val[0]==0){ next_frame_intensity.val[0]=1; } errors=frame_intensity.val[0]/next_frame_intensity.val[0]; if(errors<1-std_error||errors>1+std_error){ opt_flow.at<uint>(i,j)=255; //std::cout << "MUDOU O PIXEL" << '\n'; } } } //std::cout << "TROCOU FRAME" << '\n'; } void blackfy(cv::Mat input){ for(int i=0;i<input.rows;i++){ for(int j=0;j<input.cols;j++){ input.at<uint>(i,j)=0; //std::cout << "(" << i << "," << j << ")" << '\n'; } } } void draw_flow(cv::Mat input, cv::Mat output){ for (int y = 0; y < output.rows; y += interval_pixels) { for (int x = 0; x < output.cols; x += interval_pixels) { const cv::Point2f flowatxy = input.at<cv::Point2f>(y, x) * tam_vel; cv::line(output, cv::Point(x, y), cv::Point(cvRound(x + flowatxy.x), cvRound(y + flowatxy.y)), cv::Scalar(255, 0, 0)); cv::circle(output, cv::Point(x, y), 1, cv::Scalar(0, 0, 0), -1); } } } void get_xvals(cv::Mat input){ x_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F); for (int i=0;i<input.rows;i++){ for(int j=0;j<input.cols;j++){ //std::cout << "X_VALS:" << x_vals.size() << '|' << x_vals.channels() << '|' << x_vals.type() << '\n'; x_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).x; } } } void get_yvals(cv::Mat input){ y_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F); for (int i=0;i<input.rows;i++){ for(int j=0;j<input.cols;j++){ //std::cout << "Y_VALS:" << y_vals.size() << '|' << y_vals.channels() << '|' << y_vals.type() << '\n'; y_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).y; } } } void generate_flowmask(cv::Mat x_matrix,cv::Mat y_matrix) { flow_mask=cv::Mat::zeros(x_matrix.rows,x_matrix.cols, CV_32F); for (int i=0;i<x_matrix.rows;i++){ for(int j=0;j<x_matrix.cols;j++){ flow_mask.at<float>(i,j)=magnitude(x_matrix.at<float>(i,j), y_matrix.at<float>(i,j)); } } } float magnitude(float a, float b){ float mag; mag=sqrt((a*a)+(b*b)); return(mag); } void get_contours(cv::Mat input){ std::vector<std::vector<cv::Point> > contours_poly(contours.size()); std::vector<cv::Rect> boundRect(contours.size()); for(int i=0;i<contours.size();i++){ cv::approxPolyDP(cv::Mat(contours[i]),contours_poly[i],3,true ); boundRect[i] = cv::boundingRect(cv::Mat(contours_poly[i])); draw_rectangles(boundRect); get_mov_obj(boundRect); } } void draw_rectangles(std::vector<cv::Rect> boundRect){ for(int i=0; i< contours.size(); i++ ){ rectangle(frame, boundRect[i].tl(), boundRect[i].br(), cv::Scalar(0,0,255), 2, 8, 0 ); } } void get_mov_obj(std::vector<cv::Rect> boundRect){ cv::Point2f origin_point_aux; for (int i=0;i<contours.size();i++){ origin_point_aux.x=boundRect[i].x; origin_point_aux.y=boundRect[i].y; MovObj aux(origin_point_aux,boundRect[i].height,boundRect[i].width,boundRect[i].area()); mov_objects.push_back(aux); /*std::cout << "Object i=" << i << ':' << '\n'; std::cout << "Height:" << mov_objects[i].get_height() << '\n'; std::cout << "Width:" << mov_objects[i].get_width() << '\n'; getchar();*/ } } void print_moving_objects_vector(){ for(int i=0;i<mov_objects.size();i++){ std::cout << "i=" << i << '\n'; std::cout << "Height:" << mov_objects[i].get_height() << '\n'; std::cout << "Width:" << mov_objects[i].get_width() << '\n'; std::cout << "Area:" << mov_objects[i].get_area() << '\n'; std::cout << "Origin Point:" << mov_objects[i].get_origin() << '\n'; std::cout << "----------------------------------" << '\n'; } } }; //--------------------- Global Variables --------------------- //--------------------- Main Function --------------------- int main(int argc, char *argv[]){ cv::String filename; cv::VideoCapture video; if (argc<=1){ std::cout << "\n\nThere was no input video to run.\nPress ENTER to quit.\n>>"; getchar(); return(-1); } filename=argv[1]; Opt_flow opt_flow(video,filename); opt_flow.play(); return(0); } <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <iostream> #include <sstream> #include <sys/time.h> #include <stdint.h> #include "modp_b64.h" using namespace std; const int LOOP_COUNT = 100000; static const uint8_t kBase64DecodeTable[256] ={ 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3e,0xff,0xff,0xff,0x3f, 0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e, 0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0xff,0xff,0xff,0xff,0xff, 0xff,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28, 0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, }; static const uint8_t *kBase64EncodeTable = (const uint8_t *) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; void base64_encode(const uint8_t *in, uint32_t len, uint8_t *buf) { buf[0] = kBase64EncodeTable[(in[0] >> 2) & 0x3f]; if (len == 3) { buf[1] = kBase64EncodeTable[((in[0] << 4) & 0x30) | ((in[1] >> 4) & 0x0f)]; buf[2] = kBase64EncodeTable[((in[1] << 2) & 0x3c) | ((in[2] >> 6) & 0x03)]; buf[3] = kBase64EncodeTable[in[2] & 0x3f]; } else if (len == 2) { buf[1] = kBase64EncodeTable[((in[0] << 4) & 0x30) | ((in[1] >> 4) & 0x0f)]; buf[2] = kBase64EncodeTable[(in[1] << 2) & 0x3c]; } else { // len == 1 buf[1] = kBase64EncodeTable[(in[0] << 4) & 0x30]; } } std::string Base64Encode(const std::string& src, std::string ending = "") { uint8_t i = 0; uint8_t b[4]; const uint8_t *bytes = (const uint8_t *) src.c_str(); uint32_t len = src.length(); std::stringstream ss; while (len >= 3) { base64_encode(bytes, 3, b); for (i = 0; i < 4; i++) ss << b[i]; bytes += 3; len -= 3; } if (len > 0) { base64_encode(bytes, len, b); for (i = 0; i < len + 1; i++) ss << b[i]; } ss << ending; return ss.str(); } std::string Base64Encode1(const std::string& src, std::string ending = "") { uint8_t i = 0; uint8_t b[4]; const uint8_t *bytes = (const uint8_t *) src.c_str(); uint32_t len = src.length(); std::string s; while (len >= 3) { base64_encode(bytes, 3, b); for (i = 0; i < 4; i++) s += b[i]; bytes += 3; len -= 3; } if (len > 0) { base64_encode(bytes, len, b); for (i = 0; i < len + 1; i++) s += b[i]; } s += ending; return s; } std::string Base64Encode2(const std::string& src, std::string ending = "") { uint8_t i = 0; uint8_t b[4]; const uint8_t *bytes = (const uint8_t *) src.c_str(); uint32_t len = src.length(); std::string s; s.reserve(len*4/3 + 4); std::cout << "begin:" << s.capacity() << std::endl; while (len >= 3) { base64_encode(bytes, 3, b); //for (i = 0; i < 4; i++) //s.append(b[0], 3); s.append(reinterpret_cast<char const*>(b),4); bytes += 3; len -= 3; } if (len) { base64_encode(bytes, len, b); s.append(reinterpret_cast<char const*>(b),len+1); } s += ending; std::cout << "end:" << s.capacity() << std::endl; return s; } std::string Base64Encode3(const std::string& src, std::string ending = "") { uint8_t i = 0; uint8_t b[4]; const uint8_t *bytes = (const uint8_t *) src.c_str(); uint32_t len = src.length(); std::string s; while (len >= 3) { base64_encode(bytes, 3, b); s += b[0]; s += b[1]; s += b[2]; s += b[3]; bytes += 3; len -= 3; } if (len > 0) { base64_encode(bytes, len, b); s.append(reinterpret_cast<char const*>(b),len+1); } s += ending; return s; } bool Base64EncodeModp(const std::string& input, std::string* output) { std::string temp; temp.resize(modp_b64_encode_len(input.size())); // makes room for null byte // null terminates result since result is base64 text! int input_size = static_cast<int>(input.size()); int output_size= modp_b64_encode(&(temp[0]), input.data(), input_size); if (output_size < 0) return false; temp.resize(output_size); // strips off null byte output->swap(temp); return true; } int main(int argc, char *argv[]) { std::string s = "zqus387489tid'23 tck=e02fce03a933b5c8fffdf46442a2e8e9ts" "1461052882959uunid4tid=23&tck=e02fce03a933b5c8fffdf46442a2e8e9&ts=1461052882959&ver=1ip:106.39.88.82hostname:tf41dg.prod.mediav.comagent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4)" "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36lang:en,zh-CN;q=0.8,zh;q=0.6,zh-TW;q=0.4referer:http://ckmap.mediav.com/b?type=10proxy:106.39.88.82, 202.79.203.111_mvctn191270=_mvsrc=118216_523698_1043440&_mvcam=191270_1241961_11970810_58740969_0&osr=oqdT0qhmgzj0&time=1449650466&rdom=anonymous; _mvctn165564=_mvsrc=118478_524001_1044112&_mvcam=165564_1224948_11775153_58841999_0&osr=Zg4c0cS49V00&time=1451040575&rdom=anonymous; v=)he((]^XdqB2fOE=[AjT; _jzqa=1.4336274511317232000.1447337529.1447337529.1461045516.2; _jzqc=1; _jzqckmp=1; ckmts=PUPtXAzi,P6PtXAzi,RGPtXAzi,R6PtXAzi,U6PtXAzi,JGPtXAzi,JrPtXAzi,J6PtXAzi,bUPtXAziver1 0:0|0:0|0:0|0:10 p!" " version 1.01"; string a; struct timeval start, end; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { a = Base64Encode(s); } std::cout << "base64encoded: " << a << std::endl; gettimeofday(&end, NULL); std::cout << "Base64Encode timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; string b; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { b = Base64Encode1(s); } std::cout << "base64encoded: " << b << std::endl; gettimeofday(&end, NULL); std::cout << " Base64Encode1 timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; string e; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { e = Base64Encode2(s); } std::cout << "base64encoded: " << e << std::endl; gettimeofday(&end, NULL); std::cout << " Base64Encode2 timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; string f; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { f = Base64Encode3(s); } std::cout << "base64encoded: " << e << std::endl; gettimeofday(&end, NULL); std::cout << " Base64Encode3 timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; string c; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { Base64EncodeModp(s, &c); } std::cout << "base64encoded: " << c << std::endl; gettimeofday(&end, NULL); std::cout << " Base64Encode1 timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; return 0; } <commit_msg>temp commit<commit_after>#include <stdio.h> #include <string.h> #include <iostream> #include <sstream> #include <sys/time.h> #include <stdint.h> #include "modp_b64.h" using namespace std; const int LOOP_COUNT = 100000; static const uint8_t kBase64DecodeTable[256] ={ 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3e,0xff,0xff,0xff,0x3f, 0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e, 0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0xff,0xff,0xff,0xff,0xff, 0xff,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28, 0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, }; static const uint8_t *kBase64EncodeTable = (const uint8_t *) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; void base64_encode(const uint8_t *in, uint32_t len, uint8_t *buf) { buf[0] = kBase64EncodeTable[(in[0] >> 2) & 0x3f]; if (len == 3) { buf[1] = kBase64EncodeTable[((in[0] << 4) & 0x30) | ((in[1] >> 4) & 0x0f)]; buf[2] = kBase64EncodeTable[((in[1] << 2) & 0x3c) | ((in[2] >> 6) & 0x03)]; buf[3] = kBase64EncodeTable[in[2] & 0x3f]; } else if (len == 2) { buf[1] = kBase64EncodeTable[((in[0] << 4) & 0x30) | ((in[1] >> 4) & 0x0f)]; buf[2] = kBase64EncodeTable[(in[1] << 2) & 0x3c]; } else { // len == 1 buf[1] = kBase64EncodeTable[(in[0] << 4) & 0x30]; } } std::string Base64Encode(const std::string& src, std::string ending = "") { uint8_t i = 0; uint8_t b[4]; const uint8_t *bytes = (const uint8_t *) src.c_str(); uint32_t len = src.length(); std::stringstream ss; while (len >= 3) { base64_encode(bytes, 3, b); for (i = 0; i < 4; i++) ss << b[i]; bytes += 3; len -= 3; } if (len > 0) { base64_encode(bytes, len, b); for (i = 0; i < len + 1; i++) ss << b[i]; } ss << ending; return ss.str(); } std::string Base64Encode1(const std::string& src, std::string ending = "") { uint8_t i = 0; uint8_t b[4]; const uint8_t *bytes = (const uint8_t *) src.c_str(); uint32_t len = src.length(); std::string s; while (len >= 3) { base64_encode(bytes, 3, b); for (i = 0; i < 4; i++) s += b[i]; bytes += 3; len -= 3; } if (len > 0) { base64_encode(bytes, len, b); for (i = 0; i < len + 1; i++) s += b[i]; } s += ending; return s; } std::string Base64Encode2(const std::string& src, std::string ending = "") { uint8_t i = 0; uint8_t b[4]; const uint8_t *bytes = (const uint8_t *) src.c_str(); uint32_t len = src.length(); std::string s; s.reserve(len*4/3 + 4); while (len >= 3) { base64_encode(bytes, 3, b); //for (i = 0; i < 4; i++) //s.append(b[0], 3); s.append(reinterpret_cast<char const*>(b),4); bytes += 3; len -= 3; } if (len) { base64_encode(bytes, len, b); s.append(reinterpret_cast<char const*>(b),len+1); } s += ending; return s; } std::string Base64Encode3(const std::string& src, std::string ending = "") { uint8_t i = 0; uint8_t b[4]; const uint8_t *bytes = (const uint8_t *) src.c_str(); uint32_t len = src.length(); std::string s; while (len >= 3) { base64_encode(bytes, 3, b); s += b[0]; s += b[1]; s += b[2]; s += b[3]; bytes += 3; len -= 3; } if (len > 0) { base64_encode(bytes, len, b); s.append(reinterpret_cast<char const*>(b),len+1); } s += ending; return s; } bool Base64EncodeModp(const std::string& input, std::string* output) { std::string temp; temp.resize(modp_b64_encode_len(input.size())); // makes room for null byte // null terminates result since result is base64 text! int input_size = static_cast<int>(input.size()); int output_size= modp_b64_encode(&(temp[0]), input.data(), input_size); if (output_size < 0) return false; temp.resize(output_size); // strips off null byte output->swap(temp); return true; } int main(int argc, char *argv[]) { std::string s = "zqus387489tid'23 tck=e02fce03a933b5c8fffdf46442a2e8e9ts" "1461052882959uunid4tid=23&tck=e02fce03a933b5c8fffdf46442a2e8e9&ts=1461052882959&ver=1ip:106.39.88.82hostname:tf41dg.prod.mediav.comagent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4)" "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36lang:en,zh-CN;q=0.8,zh;q=0.6,zh-TW;q=0.4referer:http://ckmap.mediav.com/b?type=10proxy:106.39.88.82, 202.79.203.111_mvctn191270=_mvsrc=118216_523698_1043440&_mvcam=191270_1241961_11970810_58740969_0&osr=oqdT0qhmgzj0&time=1449650466&rdom=anonymous; _mvctn165564=_mvsrc=118478_524001_1044112&_mvcam=165564_1224948_11775153_58841999_0&osr=Zg4c0cS49V00&time=1451040575&rdom=anonymous; v=)he((]^XdqB2fOE=[AjT; _jzqa=1.4336274511317232000.1447337529.1447337529.1461045516.2; _jzqc=1; _jzqckmp=1; ckmts=PUPtXAzi,P6PtXAzi,RGPtXAzi,R6PtXAzi,U6PtXAzi,JGPtXAzi,JrPtXAzi,J6PtXAzi,bUPtXAziver1 0:0|0:0|0:0|0:10 p!" " version 1.01"; string a; struct timeval start, end; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { a = Base64Encode(s); } std::cout << "base64encoded: " << a << std::endl; gettimeofday(&end, NULL); std::cout << "Base64Encode timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; string b; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { b = Base64Encode1(s); } std::cout << "base64encoded: " << b << std::endl; gettimeofday(&end, NULL); std::cout << " Base64Encode1 timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; string e; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { e = Base64Encode2(s); } std::cout << "base64encoded: " << e << std::endl; gettimeofday(&end, NULL); std::cout << " Base64Encode2 timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; string f; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { f = Base64Encode3(s); } std::cout << "base64encoded: " << e << std::endl; gettimeofday(&end, NULL); std::cout << " Base64Encode3 timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; string c; gettimeofday(&start, NULL); for (int i = 0; i < LOOP_COUNT; ++i) { Base64EncodeModp(s, &c); } std::cout << "base64encoded: " << c << std::endl; gettimeofday(&end, NULL); std::cout << " Base64Encode1 timeuse: " << 1000000*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright 2016 The Cartographer Authors * * 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 "cartographer_ros/map_builder_bridge.h" #include "cartographer/common/make_unique.h" #include "cartographer/io/color.h" #include "cartographer/io/proto_stream.h" #include "cartographer/mapping/pose_graph.h" #include "cartographer_ros/msg_conversion.h" namespace cartographer_ros { namespace { constexpr double kTrajectoryLineStripMarkerScale = 0.07; constexpr double kConstraintMarkerScale = 0.025; ::std_msgs::ColorRGBA ToMessage(const cartographer::io::FloatColor& color) { ::std_msgs::ColorRGBA result; result.r = color[0]; result.g = color[1]; result.b = color[2]; result.a = 1.f; return result; } visualization_msgs::Marker CreateTrajectoryMarker(const int trajectory_id, const std::string& frame_id) { visualization_msgs::Marker marker; marker.ns = "Trajectory " + std::to_string(trajectory_id); marker.id = 0; marker.type = visualization_msgs::Marker::LINE_STRIP; marker.header.stamp = ::ros::Time::now(); marker.header.frame_id = frame_id; marker.color = ToMessage(cartographer::io::GetColor(trajectory_id)); marker.scale.x = kTrajectoryLineStripMarkerScale; marker.pose.orientation.w = 1.; marker.pose.position.z = 0.05; return marker; } void PushAndResetLineMarker(visualization_msgs::Marker* marker, std::vector<visualization_msgs::Marker>* markers) { if (marker->points.size() > 1) { markers->push_back(*marker); ++marker->id; } marker->points.clear(); } } // namespace MapBuilderBridge::MapBuilderBridge( const NodeOptions& node_options, std::unique_ptr<cartographer::mapping::MapBuilderInterface> map_builder, tf2_ros::Buffer* const tf_buffer) : node_options_(node_options), map_builder_(std::move(map_builder)), tf_buffer_(tf_buffer) {} void MapBuilderBridge::LoadMap(const std::string& map_filename) { LOG(INFO) << "Loading map '" << map_filename << "'..."; cartographer::io::ProtoStreamReader stream(map_filename); map_builder_->LoadMap(&stream); } int MapBuilderBridge::AddTrajectory( const std::unordered_set<std::string>& expected_sensor_ids, const TrajectoryOptions& trajectory_options) { const int trajectory_id = map_builder_->AddTrajectoryBuilder( expected_sensor_ids, trajectory_options.trajectory_builder_options, ::std::bind(&MapBuilderBridge::OnLocalSlamResult, this, ::std::placeholders::_1, ::std::placeholders::_2, ::std::placeholders::_3, ::std::placeholders::_4, ::std::placeholders::_5)); LOG(INFO) << "Added trajectory with ID '" << trajectory_id << "'."; // Make sure there is no trajectory with 'trajectory_id' yet. CHECK_EQ(sensor_bridges_.count(trajectory_id), 0); sensor_bridges_[trajectory_id] = cartographer::common::make_unique<SensorBridge>( trajectory_options.num_subdivisions_per_laser_scan, trajectory_options.tracking_frame, node_options_.lookup_transform_timeout_sec, tf_buffer_, map_builder_->GetTrajectoryBuilder(trajectory_id)); auto emplace_result = trajectory_options_.emplace(trajectory_id, trajectory_options); CHECK(emplace_result.second == true); return trajectory_id; } void MapBuilderBridge::FinishTrajectory(const int trajectory_id) { LOG(INFO) << "Finishing trajectory with ID '" << trajectory_id << "'..."; // Make sure there is a trajectory with 'trajectory_id'. CHECK_EQ(sensor_bridges_.count(trajectory_id), 1); map_builder_->FinishTrajectory(trajectory_id); sensor_bridges_.erase(trajectory_id); } void MapBuilderBridge::RunFinalOptimization() { LOG(INFO) << "Running final trajectory optimization..."; map_builder_->pose_graph()->RunFinalOptimization(); } void MapBuilderBridge::SerializeState(const std::string& filename) { cartographer::io::ProtoStreamWriter writer(filename); map_builder_->SerializeState(&writer); CHECK(writer.Close()) << "Could not write state."; } bool MapBuilderBridge::HandleSubmapQuery( cartographer_ros_msgs::SubmapQuery::Request& request, cartographer_ros_msgs::SubmapQuery::Response& response) { cartographer::mapping::proto::SubmapQuery::Response response_proto; cartographer::mapping::SubmapId submap_id{request.trajectory_id, request.submap_index}; const std::string error = map_builder_->SubmapToProto(submap_id, &response_proto); if (!error.empty()) { LOG(ERROR) << error; return false; } CHECK(response_proto.textures_size() > 0) << "empty textures given for submap: " << submap_id; response.submap_version = response_proto.submap_version(); for (const auto& texture_proto : response_proto.textures()) { response.textures.emplace_back(); auto& texture = response.textures.back(); texture.cells.insert(texture.cells.begin(), texture_proto.cells().begin(), texture_proto.cells().end()); texture.width = texture_proto.width(); texture.height = texture_proto.height(); texture.resolution = texture_proto.resolution(); texture.slice_pose = ToGeometryMsgPose( cartographer::transform::ToRigid3(texture_proto.slice_pose())); } return true; } cartographer_ros_msgs::SubmapList MapBuilderBridge::GetSubmapList() { cartographer_ros_msgs::SubmapList submap_list; submap_list.header.stamp = ::ros::Time::now(); submap_list.header.frame_id = node_options_.map_frame; for (const auto& submap_id_pose : map_builder_->pose_graph()->GetAllSubmapPoses()) { cartographer_ros_msgs::SubmapEntry submap_entry; submap_entry.trajectory_id = submap_id_pose.id.trajectory_id; submap_entry.submap_index = submap_id_pose.id.submap_index; submap_entry.submap_version = submap_id_pose.data.version; submap_entry.pose = ToGeometryMsgPose(submap_id_pose.data.pose); submap_list.submap.push_back(submap_entry); } return submap_list; } std::unordered_map<int, MapBuilderBridge::TrajectoryState> MapBuilderBridge::GetTrajectoryStates() { std::unordered_map<int, TrajectoryState> trajectory_states; for (const auto& entry : sensor_bridges_) { const int trajectory_id = entry.first; const SensorBridge& sensor_bridge = *entry.second; std::shared_ptr<const TrajectoryState::LocalSlamData> local_slam_data; { cartographer::common::MutexLocker lock(&mutex_); if (trajectory_state_data_.count(trajectory_id) == 0) { continue; } local_slam_data = trajectory_state_data_.at(trajectory_id); } // Make sure there is a trajectory with 'trajectory_id'. CHECK_EQ(trajectory_options_.count(trajectory_id), 1); trajectory_states[trajectory_id] = { local_slam_data, map_builder_->pose_graph()->GetLocalToGlobalTransform(trajectory_id), sensor_bridge.tf_bridge().LookupToTracking( local_slam_data->time, trajectory_options_[trajectory_id].published_frame), trajectory_options_[trajectory_id]}; } return trajectory_states; } visualization_msgs::MarkerArray MapBuilderBridge::GetTrajectoryNodeList() { visualization_msgs::MarkerArray trajectory_node_list; const auto node_poses = map_builder_->pose_graph()->GetTrajectoryNodePoses(); for (const int trajectory_id : node_poses.trajectory_ids()) { visualization_msgs::Marker marker = CreateTrajectoryMarker(trajectory_id, node_options_.map_frame); for (const auto& node_id_data : node_poses.trajectory(trajectory_id)) { if (node_id_data.data.has_constant_data) { PushAndResetLineMarker(&marker, &trajectory_node_list.markers); continue; } const ::geometry_msgs::Point node_point = ToGeometryMsgPoint(node_id_data.data.global_pose.translation()); marker.points.push_back(node_point); // Work around the 16384 point limit in RViz by splitting the // trajectory into multiple markers. if (marker.points.size() == 16384) { PushAndResetLineMarker(&marker, &trajectory_node_list.markers); // Push back the last point, so the two markers appear connected. marker.points.push_back(node_point); } } PushAndResetLineMarker(&marker, &trajectory_node_list.markers); } return trajectory_node_list; } visualization_msgs::MarkerArray MapBuilderBridge::GetConstraintList() { visualization_msgs::MarkerArray constraint_list; int marker_id = 0; visualization_msgs::Marker constraint_intra_marker; constraint_intra_marker.id = marker_id++; constraint_intra_marker.ns = "Intra constraints"; constraint_intra_marker.type = visualization_msgs::Marker::LINE_LIST; constraint_intra_marker.header.stamp = ros::Time::now(); constraint_intra_marker.header.frame_id = node_options_.map_frame; constraint_intra_marker.scale.x = kConstraintMarkerScale; constraint_intra_marker.pose.orientation.w = 1.0; visualization_msgs::Marker residual_intra_marker = constraint_intra_marker; residual_intra_marker.id = marker_id++; residual_intra_marker.ns = "Intra residuals"; // This and other markers which are less numerous are set to be slightly // above the intra constraints marker in order to ensure that they are // visible. residual_intra_marker.pose.position.z = 0.1; visualization_msgs::Marker constraint_inter_marker = constraint_intra_marker; constraint_inter_marker.id = marker_id++; constraint_inter_marker.ns = "Inter constraints"; constraint_inter_marker.pose.position.z = 0.1; visualization_msgs::Marker residual_inter_marker = constraint_intra_marker; residual_inter_marker.id = marker_id++; residual_inter_marker.ns = "Inter residuals"; residual_inter_marker.pose.position.z = 0.1; const auto trajectory_nodes = map_builder_->pose_graph()->GetTrajectoryNodes(); const auto submap_data = map_builder_->pose_graph()->GetAllSubmapData(); const auto constraints = map_builder_->pose_graph()->constraints(); for (const auto& constraint : constraints) { visualization_msgs::Marker *constraint_marker, *residual_marker; std_msgs::ColorRGBA color_constraint, color_residual; if (constraint.tag == cartographer::mapping::PoseGraph::Constraint::INTRA_SUBMAP) { constraint_marker = &constraint_intra_marker; residual_marker = &residual_intra_marker; // Color mapping for submaps of various trajectories - add trajectory id // to ensure different starting colors. Also add a fixed offset of 25 // to avoid having identical colors as trajectories. color_constraint = ToMessage( cartographer::io::GetColor(constraint.submap_id.submap_index + constraint.submap_id.trajectory_id + 25)); color_residual.a = 1.0; color_residual.r = 1.0; } else { constraint_marker = &constraint_inter_marker; residual_marker = &residual_inter_marker; // Bright yellow color_constraint.a = 1.0; color_constraint.r = color_constraint.g = 1.0; // Bright cyan color_residual.a = 1.0; color_residual.b = color_residual.g = 1.0; } for (int i = 0; i < 2; ++i) { constraint_marker->colors.push_back(color_constraint); residual_marker->colors.push_back(color_residual); } const auto submap_it = submap_data.find(constraint.submap_id); if (submap_it == submap_data.end()) { continue; } const auto& submap_pose = submap_it->data.pose; const auto node_it = trajectory_nodes.find(constraint.node_id); if (node_it == trajectory_nodes.end()) { continue; } const auto& trajectory_node_pose = node_it->data.global_pose; const cartographer::transform::Rigid3d constraint_pose = submap_pose * constraint.pose.zbar_ij; constraint_marker->points.push_back( ToGeometryMsgPoint(submap_pose.translation())); constraint_marker->points.push_back( ToGeometryMsgPoint(constraint_pose.translation())); residual_marker->points.push_back( ToGeometryMsgPoint(constraint_pose.translation())); residual_marker->points.push_back( ToGeometryMsgPoint(trajectory_node_pose.translation())); } constraint_list.markers.push_back(constraint_intra_marker); constraint_list.markers.push_back(residual_intra_marker); constraint_list.markers.push_back(constraint_inter_marker); constraint_list.markers.push_back(residual_inter_marker); return constraint_list; } SensorBridge* MapBuilderBridge::sensor_bridge(const int trajectory_id) { return sensor_bridges_.at(trajectory_id).get(); } void MapBuilderBridge::OnLocalSlamResult( const int trajectory_id, const ::cartographer::common::Time time, const ::cartographer::transform::Rigid3d local_pose, ::cartographer::sensor::RangeData range_data_in_local, const std::unique_ptr<const ::cartographer::mapping::NodeId>) { std::shared_ptr<const TrajectoryState::LocalSlamData> local_slam_data = std::make_shared<TrajectoryState::LocalSlamData>( TrajectoryState::LocalSlamData{time, local_pose, std::move(range_data_in_local)}); cartographer::common::MutexLocker lock(&mutex_); trajectory_state_data_[trajectory_id] = std::move(local_slam_data); } } // namespace cartographer_ros <commit_msg>Use GetTrajectoryNodePoses and GetAllSubmapPoses in GetConstraintList (#651)<commit_after>/* * Copyright 2016 The Cartographer Authors * * 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 "cartographer_ros/map_builder_bridge.h" #include "cartographer/common/make_unique.h" #include "cartographer/io/color.h" #include "cartographer/io/proto_stream.h" #include "cartographer/mapping/pose_graph.h" #include "cartographer_ros/msg_conversion.h" namespace cartographer_ros { namespace { constexpr double kTrajectoryLineStripMarkerScale = 0.07; constexpr double kConstraintMarkerScale = 0.025; ::std_msgs::ColorRGBA ToMessage(const cartographer::io::FloatColor& color) { ::std_msgs::ColorRGBA result; result.r = color[0]; result.g = color[1]; result.b = color[2]; result.a = 1.f; return result; } visualization_msgs::Marker CreateTrajectoryMarker(const int trajectory_id, const std::string& frame_id) { visualization_msgs::Marker marker; marker.ns = "Trajectory " + std::to_string(trajectory_id); marker.id = 0; marker.type = visualization_msgs::Marker::LINE_STRIP; marker.header.stamp = ::ros::Time::now(); marker.header.frame_id = frame_id; marker.color = ToMessage(cartographer::io::GetColor(trajectory_id)); marker.scale.x = kTrajectoryLineStripMarkerScale; marker.pose.orientation.w = 1.; marker.pose.position.z = 0.05; return marker; } void PushAndResetLineMarker(visualization_msgs::Marker* marker, std::vector<visualization_msgs::Marker>* markers) { if (marker->points.size() > 1) { markers->push_back(*marker); ++marker->id; } marker->points.clear(); } } // namespace MapBuilderBridge::MapBuilderBridge( const NodeOptions& node_options, std::unique_ptr<cartographer::mapping::MapBuilderInterface> map_builder, tf2_ros::Buffer* const tf_buffer) : node_options_(node_options), map_builder_(std::move(map_builder)), tf_buffer_(tf_buffer) {} void MapBuilderBridge::LoadMap(const std::string& map_filename) { LOG(INFO) << "Loading map '" << map_filename << "'..."; cartographer::io::ProtoStreamReader stream(map_filename); map_builder_->LoadMap(&stream); } int MapBuilderBridge::AddTrajectory( const std::unordered_set<std::string>& expected_sensor_ids, const TrajectoryOptions& trajectory_options) { const int trajectory_id = map_builder_->AddTrajectoryBuilder( expected_sensor_ids, trajectory_options.trajectory_builder_options, ::std::bind(&MapBuilderBridge::OnLocalSlamResult, this, ::std::placeholders::_1, ::std::placeholders::_2, ::std::placeholders::_3, ::std::placeholders::_4, ::std::placeholders::_5)); LOG(INFO) << "Added trajectory with ID '" << trajectory_id << "'."; // Make sure there is no trajectory with 'trajectory_id' yet. CHECK_EQ(sensor_bridges_.count(trajectory_id), 0); sensor_bridges_[trajectory_id] = cartographer::common::make_unique<SensorBridge>( trajectory_options.num_subdivisions_per_laser_scan, trajectory_options.tracking_frame, node_options_.lookup_transform_timeout_sec, tf_buffer_, map_builder_->GetTrajectoryBuilder(trajectory_id)); auto emplace_result = trajectory_options_.emplace(trajectory_id, trajectory_options); CHECK(emplace_result.second == true); return trajectory_id; } void MapBuilderBridge::FinishTrajectory(const int trajectory_id) { LOG(INFO) << "Finishing trajectory with ID '" << trajectory_id << "'..."; // Make sure there is a trajectory with 'trajectory_id'. CHECK_EQ(sensor_bridges_.count(trajectory_id), 1); map_builder_->FinishTrajectory(trajectory_id); sensor_bridges_.erase(trajectory_id); } void MapBuilderBridge::RunFinalOptimization() { LOG(INFO) << "Running final trajectory optimization..."; map_builder_->pose_graph()->RunFinalOptimization(); } void MapBuilderBridge::SerializeState(const std::string& filename) { cartographer::io::ProtoStreamWriter writer(filename); map_builder_->SerializeState(&writer); CHECK(writer.Close()) << "Could not write state."; } bool MapBuilderBridge::HandleSubmapQuery( cartographer_ros_msgs::SubmapQuery::Request& request, cartographer_ros_msgs::SubmapQuery::Response& response) { cartographer::mapping::proto::SubmapQuery::Response response_proto; cartographer::mapping::SubmapId submap_id{request.trajectory_id, request.submap_index}; const std::string error = map_builder_->SubmapToProto(submap_id, &response_proto); if (!error.empty()) { LOG(ERROR) << error; return false; } CHECK(response_proto.textures_size() > 0) << "empty textures given for submap: " << submap_id; response.submap_version = response_proto.submap_version(); for (const auto& texture_proto : response_proto.textures()) { response.textures.emplace_back(); auto& texture = response.textures.back(); texture.cells.insert(texture.cells.begin(), texture_proto.cells().begin(), texture_proto.cells().end()); texture.width = texture_proto.width(); texture.height = texture_proto.height(); texture.resolution = texture_proto.resolution(); texture.slice_pose = ToGeometryMsgPose( cartographer::transform::ToRigid3(texture_proto.slice_pose())); } return true; } cartographer_ros_msgs::SubmapList MapBuilderBridge::GetSubmapList() { cartographer_ros_msgs::SubmapList submap_list; submap_list.header.stamp = ::ros::Time::now(); submap_list.header.frame_id = node_options_.map_frame; for (const auto& submap_id_pose : map_builder_->pose_graph()->GetAllSubmapPoses()) { cartographer_ros_msgs::SubmapEntry submap_entry; submap_entry.trajectory_id = submap_id_pose.id.trajectory_id; submap_entry.submap_index = submap_id_pose.id.submap_index; submap_entry.submap_version = submap_id_pose.data.version; submap_entry.pose = ToGeometryMsgPose(submap_id_pose.data.pose); submap_list.submap.push_back(submap_entry); } return submap_list; } std::unordered_map<int, MapBuilderBridge::TrajectoryState> MapBuilderBridge::GetTrajectoryStates() { std::unordered_map<int, TrajectoryState> trajectory_states; for (const auto& entry : sensor_bridges_) { const int trajectory_id = entry.first; const SensorBridge& sensor_bridge = *entry.second; std::shared_ptr<const TrajectoryState::LocalSlamData> local_slam_data; { cartographer::common::MutexLocker lock(&mutex_); if (trajectory_state_data_.count(trajectory_id) == 0) { continue; } local_slam_data = trajectory_state_data_.at(trajectory_id); } // Make sure there is a trajectory with 'trajectory_id'. CHECK_EQ(trajectory_options_.count(trajectory_id), 1); trajectory_states[trajectory_id] = { local_slam_data, map_builder_->pose_graph()->GetLocalToGlobalTransform(trajectory_id), sensor_bridge.tf_bridge().LookupToTracking( local_slam_data->time, trajectory_options_[trajectory_id].published_frame), trajectory_options_[trajectory_id]}; } return trajectory_states; } visualization_msgs::MarkerArray MapBuilderBridge::GetTrajectoryNodeList() { visualization_msgs::MarkerArray trajectory_node_list; const auto node_poses = map_builder_->pose_graph()->GetTrajectoryNodePoses(); for (const int trajectory_id : node_poses.trajectory_ids()) { visualization_msgs::Marker marker = CreateTrajectoryMarker(trajectory_id, node_options_.map_frame); for (const auto& node_id_data : node_poses.trajectory(trajectory_id)) { if (node_id_data.data.has_constant_data) { PushAndResetLineMarker(&marker, &trajectory_node_list.markers); continue; } const ::geometry_msgs::Point node_point = ToGeometryMsgPoint(node_id_data.data.global_pose.translation()); marker.points.push_back(node_point); // Work around the 16384 point limit in RViz by splitting the // trajectory into multiple markers. if (marker.points.size() == 16384) { PushAndResetLineMarker(&marker, &trajectory_node_list.markers); // Push back the last point, so the two markers appear connected. marker.points.push_back(node_point); } } PushAndResetLineMarker(&marker, &trajectory_node_list.markers); } return trajectory_node_list; } visualization_msgs::MarkerArray MapBuilderBridge::GetConstraintList() { visualization_msgs::MarkerArray constraint_list; int marker_id = 0; visualization_msgs::Marker constraint_intra_marker; constraint_intra_marker.id = marker_id++; constraint_intra_marker.ns = "Intra constraints"; constraint_intra_marker.type = visualization_msgs::Marker::LINE_LIST; constraint_intra_marker.header.stamp = ros::Time::now(); constraint_intra_marker.header.frame_id = node_options_.map_frame; constraint_intra_marker.scale.x = kConstraintMarkerScale; constraint_intra_marker.pose.orientation.w = 1.0; visualization_msgs::Marker residual_intra_marker = constraint_intra_marker; residual_intra_marker.id = marker_id++; residual_intra_marker.ns = "Intra residuals"; // This and other markers which are less numerous are set to be slightly // above the intra constraints marker in order to ensure that they are // visible. residual_intra_marker.pose.position.z = 0.1; visualization_msgs::Marker constraint_inter_marker = constraint_intra_marker; constraint_inter_marker.id = marker_id++; constraint_inter_marker.ns = "Inter constraints"; constraint_inter_marker.pose.position.z = 0.1; visualization_msgs::Marker residual_inter_marker = constraint_intra_marker; residual_inter_marker.id = marker_id++; residual_inter_marker.ns = "Inter residuals"; residual_inter_marker.pose.position.z = 0.1; const auto trajectory_node_poses = map_builder_->pose_graph()->GetTrajectoryNodePoses(); const auto submap_poses = map_builder_->pose_graph()->GetAllSubmapPoses(); const auto constraints = map_builder_->pose_graph()->constraints(); for (const auto& constraint : constraints) { visualization_msgs::Marker *constraint_marker, *residual_marker; std_msgs::ColorRGBA color_constraint, color_residual; if (constraint.tag == cartographer::mapping::PoseGraph::Constraint::INTRA_SUBMAP) { constraint_marker = &constraint_intra_marker; residual_marker = &residual_intra_marker; // Color mapping for submaps of various trajectories - add trajectory id // to ensure different starting colors. Also add a fixed offset of 25 // to avoid having identical colors as trajectories. color_constraint = ToMessage( cartographer::io::GetColor(constraint.submap_id.submap_index + constraint.submap_id.trajectory_id + 25)); color_residual.a = 1.0; color_residual.r = 1.0; } else { constraint_marker = &constraint_inter_marker; residual_marker = &residual_inter_marker; // Bright yellow color_constraint.a = 1.0; color_constraint.r = color_constraint.g = 1.0; // Bright cyan color_residual.a = 1.0; color_residual.b = color_residual.g = 1.0; } for (int i = 0; i < 2; ++i) { constraint_marker->colors.push_back(color_constraint); residual_marker->colors.push_back(color_residual); } const auto submap_it = submap_poses.find(constraint.submap_id); if (submap_it == submap_poses.end()) { continue; } const auto& submap_pose = submap_it->data.pose; const auto node_it = trajectory_node_poses.find(constraint.node_id); if (node_it == trajectory_node_poses.end()) { continue; } const auto& trajectory_node_pose = node_it->data.global_pose; const cartographer::transform::Rigid3d constraint_pose = submap_pose * constraint.pose.zbar_ij; constraint_marker->points.push_back( ToGeometryMsgPoint(submap_pose.translation())); constraint_marker->points.push_back( ToGeometryMsgPoint(constraint_pose.translation())); residual_marker->points.push_back( ToGeometryMsgPoint(constraint_pose.translation())); residual_marker->points.push_back( ToGeometryMsgPoint(trajectory_node_pose.translation())); } constraint_list.markers.push_back(constraint_intra_marker); constraint_list.markers.push_back(residual_intra_marker); constraint_list.markers.push_back(constraint_inter_marker); constraint_list.markers.push_back(residual_inter_marker); return constraint_list; } SensorBridge* MapBuilderBridge::sensor_bridge(const int trajectory_id) { return sensor_bridges_.at(trajectory_id).get(); } void MapBuilderBridge::OnLocalSlamResult( const int trajectory_id, const ::cartographer::common::Time time, const ::cartographer::transform::Rigid3d local_pose, ::cartographer::sensor::RangeData range_data_in_local, const std::unique_ptr<const ::cartographer::mapping::NodeId>) { std::shared_ptr<const TrajectoryState::LocalSlamData> local_slam_data = std::make_shared<TrajectoryState::LocalSlamData>( TrajectoryState::LocalSlamData{time, local_pose, std::move(range_data_in_local)}); cartographer::common::MutexLocker lock(&mutex_); trajectory_state_data_[trajectory_id] = std::move(local_slam_data); } } // namespace cartographer_ros <|endoftext|>
<commit_before>/* * This file is part of Maliit Plugins * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * * Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "view/renderer.h" #include "view/glass.h" #include "logic/layoutupdater.h" #include "models/keyarea.h" #include "models/key.h" #include "models/keylabel.h" #include "models/layout.h" #include <QtGui> namespace { MaliitKeyboard::Key createKey(const QPixmap &pm, const MaliitKeyboard::SharedFont &f, const QRect &kr, const QRect &lr, const QByteArray &t, const QColor &c, MaliitKeyboard::Key::Action a = MaliitKeyboard::Key::ActionInsert) { MaliitKeyboard::KeyLabel l; l.setText(t); l.setColor(c); l.setFont(f); MaliitKeyboard::Key k; k.setRect(kr); k.setBackground(pm); k.setLabel(l); k.setAction(a); return k; } MaliitKeyboard::KeyArea createPrimaryKeyArea() { typedef QByteArray QBA; QPixmap pm(8, 8); pm.fill(Qt::lightGray); MaliitKeyboard::SharedFont font(new QFont); font->setBold(true); font->setPointSize(16); MaliitKeyboard::KeyArea ka; ka.rect = QRectF(0, 554, 480, 300); ka.keys.append(createKey(pm, font, QRect(10, 10, 40, 60), QRect(5, 5, 20, 40), QBA("Q"), Qt::darkBlue)); ka.keys.append(createKey(pm, font, QRect(60, 10, 80, 120), QRect(5, 5, 70, 40), QBA("W"), Qt::darkMagenta)); ka.keys.append(createKey(pm, font, QRect(10, 80, 40, 50), QRect(5, 5, 20, 40), QBA("A"), Qt::black)); ka.keys.append(createKey(pm, font, QRect(10, 140, 130, 60), QRect(5, 5, 120, 40), QBA("shift"), Qt::darkCyan, MaliitKeyboard::Key::ActionShift)); ka.keys.append(createKey(pm, font, QRect(160, 10, 120, 120), QRect(5, 5, 120, 40), QBA("switch"), Qt::darkCyan, MaliitKeyboard::Key::ActionSwitch)); return ka; } MaliitKeyboard::KeyArea createSecondaryKeyArea() { typedef QByteArray QBA; QPixmap pm(8, 8); pm.fill(Qt::lightGray); MaliitKeyboard::SharedFont font(new QFont); font->setBold(true); font->setPointSize(16); MaliitKeyboard::KeyArea ka; ka.rect = QRectF(0, 0, 480, 100); ka.keys.append(createKey(pm, font, QRect(10, 10, 40, 60), QRect(5, 5, 20, 40), QBA("T"), Qt::darkBlue)); ka.keys.append(createKey(pm, font, QRect(60, 10, 80, 80), QRect(5, 5, 20, 40), QBA("O"), Qt::darkMagenta)); return ka; } } int main(int argc, char ** argv) { QApplication app(argc, argv); QWidget *window = new QWidget; window->resize(480, 854); window->showFullScreen(); MaliitKeyboard::SharedLayout l0(new MaliitKeyboard::Layout); l0->setCenterPanel(createPrimaryKeyArea()); MaliitKeyboard::SharedLayout l1(new MaliitKeyboard::Layout); l1->setCenterPanel(createSecondaryKeyArea()); MaliitKeyboard::Renderer renderer; renderer.setWindow(window); renderer.addLayout(l0); renderer.addLayout(l1); renderer.show(); MaliitKeyboard::Glass glass; glass.setWindow(renderer.viewport()); glass.addLayout(l0); glass.addLayout(l1); // One layout updater can only manage one layout. If more layouts need to // be managed, then more layout updaters are required. MaliitKeyboard::LayoutUpdater updater; updater.init(); updater.setLayout(l0); QObject::connect(&glass, SIGNAL(keyPressed(Key, SharedLayout)), &updater, SLOT(onKeyPressed(Key, SharedLayout))); QObject::connect(&glass, SIGNAL(keyReleased(Key, SharedLayout)), &updater, SLOT(onKeyReleased(Key, SharedLayout))); QObject::connect(&updater, SIGNAL(layoutChanged(SharedLayout)), &renderer, SLOT(onLayoutChanged(SharedLayout))); QObject::connect(&updater, SIGNAL(keysChanged(SharedLayout)), &renderer, SLOT(onKeysChanged(SharedLayout))); return app.exec(); } <commit_msg>Remove unused KeyLabel rectangle parameters from maliit-keyboard-viewer<commit_after>/* * This file is part of Maliit Plugins * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * * Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * Neither the name of Nokia Corporation nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "view/renderer.h" #include "view/glass.h" #include "logic/layoutupdater.h" #include "models/keyarea.h" #include "models/key.h" #include "models/keylabel.h" #include "models/layout.h" #include <QtGui> namespace { MaliitKeyboard::Key createKey(const QPixmap &pm, const MaliitKeyboard::SharedFont &f, const QRect &kr, const QByteArray &t, const QColor &c, MaliitKeyboard::Key::Action a = MaliitKeyboard::Key::ActionInsert) { MaliitKeyboard::KeyLabel l; l.setText(t); l.setColor(c); l.setFont(f); MaliitKeyboard::Key k; k.setRect(kr); k.setBackground(pm); k.setLabel(l); k.setAction(a); return k; } MaliitKeyboard::KeyArea createPrimaryKeyArea() { typedef QByteArray QBA; QPixmap pm(8, 8); pm.fill(Qt::lightGray); MaliitKeyboard::SharedFont font(new QFont); font->setBold(true); font->setPointSize(16); MaliitKeyboard::KeyArea ka; ka.rect = QRectF(0, 554, 480, 300); ka.keys.append(createKey(pm, font, QRect(10, 10, 40, 60), QBA("Q"), Qt::darkBlue)); ka.keys.append(createKey(pm, font, QRect(60, 10, 80, 120), QBA("W"), Qt::darkMagenta)); ka.keys.append(createKey(pm, font, QRect(10, 80, 40, 50), QBA("A"), Qt::black)); ka.keys.append(createKey(pm, font, QRect(10, 140, 130, 60), QBA("shift"), Qt::darkCyan, MaliitKeyboard::Key::ActionShift)); ka.keys.append(createKey(pm, font, QRect(160, 10, 120, 120), QBA("switch"), Qt::darkCyan, MaliitKeyboard::Key::ActionSwitch)); return ka; } MaliitKeyboard::KeyArea createSecondaryKeyArea() { typedef QByteArray QBA; QPixmap pm(8, 8); pm.fill(Qt::lightGray); MaliitKeyboard::SharedFont font(new QFont); font->setBold(true); font->setPointSize(16); MaliitKeyboard::KeyArea ka; ka.rect = QRectF(0, 0, 480, 100); ka.keys.append(createKey(pm, font, QRect(10, 10, 40, 60), QBA("T"), Qt::darkBlue)); ka.keys.append(createKey(pm, font, QRect(60, 10, 80, 80), QBA("O"), Qt::darkMagenta)); return ka; } } int main(int argc, char ** argv) { QApplication app(argc, argv); QWidget *window = new QWidget; window->resize(480, 854); window->showFullScreen(); MaliitKeyboard::SharedLayout l0(new MaliitKeyboard::Layout); l0->setCenterPanel(createPrimaryKeyArea()); MaliitKeyboard::SharedLayout l1(new MaliitKeyboard::Layout); l1->setCenterPanel(createSecondaryKeyArea()); MaliitKeyboard::Renderer renderer; renderer.setWindow(window); renderer.addLayout(l0); renderer.addLayout(l1); renderer.show(); MaliitKeyboard::Glass glass; glass.setWindow(renderer.viewport()); glass.addLayout(l0); glass.addLayout(l1); // One layout updater can only manage one layout. If more layouts need to // be managed, then more layout updaters are required. MaliitKeyboard::LayoutUpdater updater; updater.init(); updater.setLayout(l0); QObject::connect(&glass, SIGNAL(keyPressed(Key, SharedLayout)), &updater, SLOT(onKeyPressed(Key, SharedLayout))); QObject::connect(&glass, SIGNAL(keyReleased(Key, SharedLayout)), &updater, SLOT(onKeyReleased(Key, SharedLayout))); QObject::connect(&updater, SIGNAL(layoutChanged(SharedLayout)), &renderer, SLOT(onLayoutChanged(SharedLayout))); QObject::connect(&updater, SIGNAL(keysChanged(SharedLayout)), &renderer, SLOT(onKeysChanged(SharedLayout))); return app.exec(); } <|endoftext|>
<commit_before>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unordered_map> #include "matrix_worker_thread.h" #include "sparse_matrix.h" namespace fm { static const int MAX_PENDING_IOS = 32; class matrix_io_callback: public safs::callback { typedef std::unordered_map<char *, compute_task::ptr> task_map_t; task_map_t tasks; size_t pending_size; public: matrix_io_callback() { pending_size = 0; } ~matrix_io_callback() { assert(pending_size == 0); } size_t get_pending_size() const { return pending_size; } size_t get_pending_ios() const { return tasks.size(); } int invoke(safs::io_request *reqs[], int num); void add_task(const safs::io_request &req, compute_task::ptr task) { tasks.insert(task_map_t::value_type(req.get_buf(), task)); pending_size += req.get_size(); } }; int matrix_io_callback::invoke(safs::io_request *reqs[], int num) { for (int i = 0; i < num; i++) { pending_size -= reqs[i]->get_size(); task_map_t::const_iterator it = tasks.find(reqs[i]->get_buf()); it->second->run(reqs[i]->get_buf(), reqs[i]->get_size()); // Once a task is complete, we can remove it from the hashtable. tasks.erase(it); } return 0; } bool matrix_worker_thread::get_next_io(matrix_io &io) { if (this_io_gen->has_next_io()) { io = this_io_gen->get_next_io(); return io.is_valid(); } else { for (size_t i = 0; i < io_gens.size(); i++) { if (io_gens[steal_io_id]->has_next_io()) { io = io_gens[steal_io_id]->steal_io(); if (io.is_valid()) return true; } steal_io_id = (steal_io_id + 1) % io_gens.size(); } return false; } } void matrix_worker_thread::run() { matrix_io_callback *cb = new matrix_io_callback(); io->set_callback(cb); matrix_io mio; while (get_next_io(mio)) { compute_task::ptr task = tcreator->create(mio); safs::io_request req = task->get_request(); cb->add_task(req, task); io->access(&req, 1); // TODO it might not be good to have a fixed number of pending I/O. // We need to control memory consumption for the buffers. while (io->num_pending_ios() > MAX_PENDING_IOS) io->wait4complete(1); } io->wait4complete(io->num_pending_ios()); assert(io->num_pending_ios() == 0); stop(); delete cb; } } <commit_msg>[Matrix]: use shared_ptr for callback.<commit_after>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unordered_map> #include "matrix_worker_thread.h" #include "sparse_matrix.h" namespace fm { static const int MAX_PENDING_IOS = 32; class matrix_io_callback: public safs::callback { typedef std::unordered_map<char *, compute_task::ptr> task_map_t; task_map_t tasks; size_t pending_size; public: matrix_io_callback() { pending_size = 0; } ~matrix_io_callback() { assert(pending_size == 0); } size_t get_pending_size() const { return pending_size; } size_t get_pending_ios() const { return tasks.size(); } int invoke(safs::io_request *reqs[], int num); void add_task(const safs::io_request &req, compute_task::ptr task) { tasks.insert(task_map_t::value_type(req.get_buf(), task)); pending_size += req.get_size(); } }; int matrix_io_callback::invoke(safs::io_request *reqs[], int num) { for (int i = 0; i < num; i++) { pending_size -= reqs[i]->get_size(); task_map_t::const_iterator it = tasks.find(reqs[i]->get_buf()); it->second->run(reqs[i]->get_buf(), reqs[i]->get_size()); // Once a task is complete, we can remove it from the hashtable. tasks.erase(it); } return 0; } bool matrix_worker_thread::get_next_io(matrix_io &io) { if (this_io_gen->has_next_io()) { io = this_io_gen->get_next_io(); return io.is_valid(); } else { for (size_t i = 0; i < io_gens.size(); i++) { if (io_gens[steal_io_id]->has_next_io()) { io = io_gens[steal_io_id]->steal_io(); if (io.is_valid()) return true; } steal_io_id = (steal_io_id + 1) % io_gens.size(); } return false; } } void matrix_worker_thread::run() { matrix_io_callback *cb = new matrix_io_callback(); io->set_callback(safs::callback::ptr(cb)); matrix_io mio; while (get_next_io(mio)) { compute_task::ptr task = tcreator->create(mio); safs::io_request req = task->get_request(); cb->add_task(req, task); io->access(&req, 1); // TODO it might not be good to have a fixed number of pending I/O. // We need to control memory consumption for the buffers. while (io->num_pending_ios() > MAX_PENDING_IOS) io->wait4complete(1); } io->wait4complete(io->num_pending_ios()); assert(io->num_pending_ios() == 0); stop(); } } <|endoftext|>
<commit_before>// Copyright 2019 The MediaPipe Authors. // // 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 <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/port/status_builder.h" #include "mediapipe/gpu/gl_context.h" #include "mediapipe/gpu/gl_context_internal.h" #ifndef EGL_OPENGL_ES3_BIT_KHR #define EGL_OPENGL_ES3_BIT_KHR 0x00000040 #endif #if HAS_EGL namespace mediapipe { namespace { static pthread_key_t egl_release_thread_key; static pthread_once_t egl_release_key_once = PTHREAD_ONCE_INIT; static void EglThreadExitCallback(void* key_value) { #if defined(__ANDROID__) eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); #else // Some implementations have chosen to allow EGL_NO_DISPLAY as a valid display // parameter for eglMakeCurrent. This behavior is not portable to all EGL // implementations, and should be considered as an undocumented vendor // extension. // https://www.khronos.org/registry/EGL/sdk/docs/man/html/eglMakeCurrent.xhtml // // NOTE: crashes on some Android devices (occurs with libGLES_meow.so). eglMakeCurrent(eglGetDisplay(EGL_DEFAULT_DISPLAY), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); #endif eglReleaseThread(); } // If a key has a destructor callback, and a thread has a non-NULL value for // that key, then the destructor is called when the thread exits. static void MakeEglReleaseThreadKey() { int err = pthread_key_create(&egl_release_thread_key, EglThreadExitCallback); if (err) { LOG(ERROR) << "cannot create pthread key: " << err; } } // This function can be called any number of times. For any thread on which it // was called at least once, the EglThreadExitCallback will be called (once) // when the thread exits. static void EnsureEglThreadRelease() { pthread_once(&egl_release_key_once, MakeEglReleaseThreadKey); pthread_setspecific(egl_release_thread_key, reinterpret_cast<void*>(0xDEADBEEF)); } static absl::StatusOr<EGLDisplay> GetInitializedDefaultEglDisplay() { EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); RET_CHECK(display != EGL_NO_DISPLAY) << "eglGetDisplay() returned error " << std::showbase << std::hex << eglGetError(); EGLint major = 0; EGLint minor = 0; EGLBoolean egl_initialized = eglInitialize(display, &major, &minor); RET_CHECK(egl_initialized) << "Unable to initialize EGL"; LOG(INFO) << "Successfully initialized EGL. Major : " << major << " Minor: " << minor; return display; } static absl::StatusOr<EGLDisplay> GetInitializedEglDisplay() { auto status_or_display = GetInitializedDefaultEglDisplay(); return status_or_display; } } // namespace GlContext::StatusOrGlContext GlContext::Create(std::nullptr_t nullp, bool create_thread) { return Create(EGL_NO_CONTEXT, create_thread); } GlContext::StatusOrGlContext GlContext::Create(const GlContext& share_context, bool create_thread) { return Create(share_context.context_, create_thread); } GlContext::StatusOrGlContext GlContext::Create(EGLContext share_context, bool create_thread) { std::shared_ptr<GlContext> context(new GlContext()); MP_RETURN_IF_ERROR(context->CreateContext(share_context)); MP_RETURN_IF_ERROR(context->FinishInitialization(create_thread)); return std::move(context); } absl::Status GlContext::CreateContextInternal(EGLContext share_context, int gl_version) { CHECK(gl_version == 2 || gl_version == 3); const EGLint config_attr[] = { // clang-format off EGL_RENDERABLE_TYPE, gl_version == 3 ? EGL_OPENGL_ES3_BIT_KHR : EGL_OPENGL_ES2_BIT, // Allow rendering to pixel buffers or directly to windows. EGL_SURFACE_TYPE, #ifdef MEDIAPIPE_OMIT_EGL_WINDOW_BIT EGL_PBUFFER_BIT, #else EGL_PBUFFER_BIT | EGL_WINDOW_BIT, #endif EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, // if you need the alpha channel EGL_DEPTH_SIZE, 16, // if you need the depth buffer EGL_NONE // clang-format on }; // TODO: improve config selection. EGLint num_configs; EGLBoolean success = eglChooseConfig(display_, config_attr, &config_, 1, &num_configs); if (!success) { return ::mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC) << "eglChooseConfig() returned error " << std::showbase << std::hex << eglGetError(); } if (!num_configs) { return mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC) << "eglChooseConfig() returned no matching EGL configuration for " << "RGBA8888 D16 ES" << gl_version << " request. "; } const EGLint context_attr[] = { // clang-format off EGL_CONTEXT_CLIENT_VERSION, gl_version, EGL_NONE // clang-format on }; context_ = eglCreateContext(display_, config_, share_context, context_attr); int error = eglGetError(); RET_CHECK(context_ != EGL_NO_CONTEXT) << "Could not create GLES " << gl_version << " context; " << "eglCreateContext() returned error " << std::showbase << std::hex << error << (error == EGL_BAD_CONTEXT ? ": external context uses a different version of OpenGL" : ""); // We can't always rely on GL_MAJOR_VERSION and GL_MINOR_VERSION, since // GLES 2 does not have them, so let's set the major version here at least. gl_major_version_ = gl_version; return absl::OkStatus(); } absl::Status GlContext::CreateContext(EGLContext share_context) { ASSIGN_OR_RETURN(display_, GetInitializedEglDisplay()); auto status = CreateContextInternal(share_context, 3); if (!status.ok()) { LOG(WARNING) << "Creating a context with OpenGL ES 3 failed: " << status; LOG(WARNING) << "Fall back on OpenGL ES 2."; status = CreateContextInternal(share_context, 2); } MP_RETURN_IF_ERROR(status); EGLint pbuffer_attr[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; surface_ = eglCreatePbufferSurface(display_, config_, pbuffer_attr); RET_CHECK(surface_ != EGL_NO_SURFACE) << "eglCreatePbufferSurface() returned error " << std::showbase << std::hex << eglGetError(); return absl::OkStatus(); } void GlContext::DestroyContext() { #ifdef __ANDROID__ if (HasContext()) { // Detach the current program to work around b/166322604. auto detach_program = [this] { GlContext::ContextBinding saved_context; GetCurrentContextBinding(&saved_context); // Note: cannot use ThisContextBinding because it calls shared_from_this, // which is not available during destruction. if (eglMakeCurrent(display_, surface_, surface_, context_)) { glUseProgram(0); } else { LOG(ERROR) << "eglMakeCurrent() returned error " << std::showbase << std::hex << eglGetError(); } return SetCurrentContextBinding(saved_context); }; auto status = thread_ ? thread_->Run(detach_program) : detach_program(); LOG_IF(ERROR, !status.ok()) << status; } #endif // __ANDROID__ if (thread_) { // Delete thread-local storage. // TODO: in theory our EglThreadExitCallback should suffice for // this; however, heapcheck still reports a leak without this call here // when using SwiftShader. // Perhaps heapcheck misses the thread destructors? thread_ ->Run([] { eglReleaseThread(); return absl::OkStatus(); }) .IgnoreError(); } // Destroy the context and surface. if (IsCurrent()) { if (!eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { LOG(ERROR) << "eglMakeCurrent() returned error " << std::showbase << std::hex << eglGetError(); } } if (surface_ != EGL_NO_SURFACE) { if (!eglDestroySurface(display_, surface_)) { LOG(ERROR) << "eglDestroySurface() returned error " << std::showbase << std::hex << eglGetError(); } surface_ = EGL_NO_SURFACE; } if (context_ != EGL_NO_CONTEXT) { if (!eglDestroyContext(display_, context_)) { LOG(ERROR) << "eglDestroyContext() returned error " << std::showbase << std::hex << eglGetError(); } context_ = EGL_NO_CONTEXT; } // Under standard EGL, eglTerminate will terminate the display connection // for the entire process, no matter how many times eglInitialize has been // called. So we do not want to terminate it here, in case someone else is // using it. // However, Android implements non-standard reference-counted semantics for // eglInitialize/eglTerminate, so we should call it on that platform. #ifdef __ANDROID__ // TODO: this is removed for now since it caused issues on // YouTube. But in theory we _should_ be calling it. Needs more // investigation. // eglTerminate(display_); #endif // __ANDROID__ } GlContext::ContextBinding GlContext::ThisContextBindingPlatform() { GlContext::ContextBinding result; result.display = display_; result.draw_surface = surface_; result.read_surface = surface_; result.context = context_; return result; } void GlContext::GetCurrentContextBinding(GlContext::ContextBinding* binding) { binding->display = eglGetCurrentDisplay(); binding->draw_surface = eglGetCurrentSurface(EGL_DRAW); binding->read_surface = eglGetCurrentSurface(EGL_READ); binding->context = eglGetCurrentContext(); } absl::Status GlContext::SetCurrentContextBinding( const ContextBinding& new_binding) { EnsureEglThreadRelease(); EGLDisplay display = new_binding.display; if (display == EGL_NO_DISPLAY) { display = eglGetCurrentDisplay(); } if (display == EGL_NO_DISPLAY) { display = eglGetDisplay(EGL_DEFAULT_DISPLAY); } EGLBoolean success = eglMakeCurrent(display, new_binding.draw_surface, new_binding.read_surface, new_binding.context); RET_CHECK(success) << "eglMakeCurrent() returned error " << std::showbase << std::hex << eglGetError(); return absl::OkStatus(); } bool GlContext::HasContext() const { return context_ != EGL_NO_CONTEXT; } bool GlContext::IsCurrent() const { return HasContext() && (eglGetCurrentContext() == context_); } } // namespace mediapipe #endif // HAS_EGL <commit_msg>Internal change<commit_after>// Copyright 2019 The MediaPipe Authors. // // 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 <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/port/status_builder.h" #include "mediapipe/gpu/gl_context.h" #include "mediapipe/gpu/gl_context_internal.h" #ifndef EGL_OPENGL_ES3_BIT_KHR #define EGL_OPENGL_ES3_BIT_KHR 0x00000040 #endif #if HAS_EGL namespace mediapipe { namespace { static pthread_key_t egl_release_thread_key; static pthread_once_t egl_release_key_once = PTHREAD_ONCE_INIT; static void EglThreadExitCallback(void* key_value) { EGLDisplay current_display = eglGetCurrentDisplay(); if (current_display != EGL_NO_DISPLAY) { // Some implementations have chosen to allow EGL_NO_DISPLAY as a valid // display parameter for eglMakeCurrent. This behavior is not portable to // all EGL implementations, and should be considered as an undocumented // vendor extension. // https://www.khronos.org/registry/EGL/sdk/docs/man/html/eglMakeCurrent.xhtml // Instead, to release the current context, we pass the current display. // If the current display is already EGL_NO_DISPLAY, no context is current. eglMakeCurrent(current_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } eglReleaseThread(); } // If a key has a destructor callback, and a thread has a non-NULL value for // that key, then the destructor is called when the thread exits. static void MakeEglReleaseThreadKey() { int err = pthread_key_create(&egl_release_thread_key, EglThreadExitCallback); if (err) { LOG(ERROR) << "cannot create pthread key: " << err; } } // This function can be called any number of times. For any thread on which it // was called at least once, the EglThreadExitCallback will be called (once) // when the thread exits. static void EnsureEglThreadRelease() { pthread_once(&egl_release_key_once, MakeEglReleaseThreadKey); pthread_setspecific(egl_release_thread_key, reinterpret_cast<void*>(0xDEADBEEF)); } static absl::StatusOr<EGLDisplay> GetInitializedDefaultEglDisplay() { EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); RET_CHECK(display != EGL_NO_DISPLAY) << "eglGetDisplay() returned error " << std::showbase << std::hex << eglGetError(); EGLint major = 0; EGLint minor = 0; EGLBoolean egl_initialized = eglInitialize(display, &major, &minor); RET_CHECK(egl_initialized) << "Unable to initialize EGL"; LOG(INFO) << "Successfully initialized EGL. Major : " << major << " Minor: " << minor; return display; } static absl::StatusOr<EGLDisplay> GetInitializedEglDisplay() { auto status_or_display = GetInitializedDefaultEglDisplay(); return status_or_display; } } // namespace GlContext::StatusOrGlContext GlContext::Create(std::nullptr_t nullp, bool create_thread) { return Create(EGL_NO_CONTEXT, create_thread); } GlContext::StatusOrGlContext GlContext::Create(const GlContext& share_context, bool create_thread) { return Create(share_context.context_, create_thread); } GlContext::StatusOrGlContext GlContext::Create(EGLContext share_context, bool create_thread) { std::shared_ptr<GlContext> context(new GlContext()); MP_RETURN_IF_ERROR(context->CreateContext(share_context)); MP_RETURN_IF_ERROR(context->FinishInitialization(create_thread)); return std::move(context); } absl::Status GlContext::CreateContextInternal(EGLContext share_context, int gl_version) { CHECK(gl_version == 2 || gl_version == 3); const EGLint config_attr[] = { // clang-format off EGL_RENDERABLE_TYPE, gl_version == 3 ? EGL_OPENGL_ES3_BIT_KHR : EGL_OPENGL_ES2_BIT, // Allow rendering to pixel buffers or directly to windows. EGL_SURFACE_TYPE, #ifdef MEDIAPIPE_OMIT_EGL_WINDOW_BIT EGL_PBUFFER_BIT, #else EGL_PBUFFER_BIT | EGL_WINDOW_BIT, #endif EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, // if you need the alpha channel EGL_DEPTH_SIZE, 16, // if you need the depth buffer EGL_NONE // clang-format on }; // TODO: improve config selection. EGLint num_configs; EGLBoolean success = eglChooseConfig(display_, config_attr, &config_, 1, &num_configs); if (!success) { return ::mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC) << "eglChooseConfig() returned error " << std::showbase << std::hex << eglGetError(); } if (!num_configs) { return mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC) << "eglChooseConfig() returned no matching EGL configuration for " << "RGBA8888 D16 ES" << gl_version << " request. "; } const EGLint context_attr[] = { // clang-format off EGL_CONTEXT_CLIENT_VERSION, gl_version, EGL_NONE // clang-format on }; context_ = eglCreateContext(display_, config_, share_context, context_attr); int error = eglGetError(); RET_CHECK(context_ != EGL_NO_CONTEXT) << "Could not create GLES " << gl_version << " context; " << "eglCreateContext() returned error " << std::showbase << std::hex << error << (error == EGL_BAD_CONTEXT ? ": external context uses a different version of OpenGL" : ""); // We can't always rely on GL_MAJOR_VERSION and GL_MINOR_VERSION, since // GLES 2 does not have them, so let's set the major version here at least. gl_major_version_ = gl_version; return absl::OkStatus(); } absl::Status GlContext::CreateContext(EGLContext share_context) { ASSIGN_OR_RETURN(display_, GetInitializedEglDisplay()); auto status = CreateContextInternal(share_context, 3); if (!status.ok()) { LOG(WARNING) << "Creating a context with OpenGL ES 3 failed: " << status; LOG(WARNING) << "Fall back on OpenGL ES 2."; status = CreateContextInternal(share_context, 2); } MP_RETURN_IF_ERROR(status); EGLint pbuffer_attr[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; surface_ = eglCreatePbufferSurface(display_, config_, pbuffer_attr); RET_CHECK(surface_ != EGL_NO_SURFACE) << "eglCreatePbufferSurface() returned error " << std::showbase << std::hex << eglGetError(); return absl::OkStatus(); } void GlContext::DestroyContext() { #ifdef __ANDROID__ if (HasContext()) { // Detach the current program to work around b/166322604. auto detach_program = [this] { GlContext::ContextBinding saved_context; GetCurrentContextBinding(&saved_context); // Note: cannot use ThisContextBinding because it calls shared_from_this, // which is not available during destruction. if (eglMakeCurrent(display_, surface_, surface_, context_)) { glUseProgram(0); } else { LOG(ERROR) << "eglMakeCurrent() returned error " << std::showbase << std::hex << eglGetError(); } return SetCurrentContextBinding(saved_context); }; auto status = thread_ ? thread_->Run(detach_program) : detach_program(); LOG_IF(ERROR, !status.ok()) << status; } #endif // __ANDROID__ if (thread_) { // Delete thread-local storage. // TODO: in theory our EglThreadExitCallback should suffice for // this; however, heapcheck still reports a leak without this call here // when using SwiftShader. // Perhaps heapcheck misses the thread destructors? thread_ ->Run([] { eglReleaseThread(); return absl::OkStatus(); }) .IgnoreError(); } // Destroy the context and surface. if (IsCurrent()) { if (!eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { LOG(ERROR) << "eglMakeCurrent() returned error " << std::showbase << std::hex << eglGetError(); } } if (surface_ != EGL_NO_SURFACE) { if (!eglDestroySurface(display_, surface_)) { LOG(ERROR) << "eglDestroySurface() returned error " << std::showbase << std::hex << eglGetError(); } surface_ = EGL_NO_SURFACE; } if (context_ != EGL_NO_CONTEXT) { if (!eglDestroyContext(display_, context_)) { LOG(ERROR) << "eglDestroyContext() returned error " << std::showbase << std::hex << eglGetError(); } context_ = EGL_NO_CONTEXT; } // Under standard EGL, eglTerminate will terminate the display connection // for the entire process, no matter how many times eglInitialize has been // called. So we do not want to terminate it here, in case someone else is // using it. // However, Android implements non-standard reference-counted semantics for // eglInitialize/eglTerminate, so we should call it on that platform. #ifdef __ANDROID__ // TODO: this is removed for now since it caused issues on // YouTube. But in theory we _should_ be calling it. Needs more // investigation. // eglTerminate(display_); #endif // __ANDROID__ } GlContext::ContextBinding GlContext::ThisContextBindingPlatform() { GlContext::ContextBinding result; result.display = display_; result.draw_surface = surface_; result.read_surface = surface_; result.context = context_; return result; } void GlContext::GetCurrentContextBinding(GlContext::ContextBinding* binding) { binding->display = eglGetCurrentDisplay(); binding->draw_surface = eglGetCurrentSurface(EGL_DRAW); binding->read_surface = eglGetCurrentSurface(EGL_READ); binding->context = eglGetCurrentContext(); } absl::Status GlContext::SetCurrentContextBinding( const ContextBinding& new_binding) { EnsureEglThreadRelease(); EGLDisplay display = new_binding.display; if (display == EGL_NO_DISPLAY) { display = eglGetCurrentDisplay(); } if (display == EGL_NO_DISPLAY) { display = eglGetDisplay(EGL_DEFAULT_DISPLAY); } EGLBoolean success = eglMakeCurrent(display, new_binding.draw_surface, new_binding.read_surface, new_binding.context); RET_CHECK(success) << "eglMakeCurrent() returned error " << std::showbase << std::hex << eglGetError(); return absl::OkStatus(); } bool GlContext::HasContext() const { return context_ != EGL_NO_CONTEXT; } bool GlContext::IsCurrent() const { return HasContext() && (eglGetCurrentContext() == context_); } } // namespace mediapipe #endif // HAS_EGL <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /*! * \file tstRendezvousMesh.cpp * \author Stuart R. Slattery * \brief RendezvousMesh unit tests. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <sstream> #include <algorithm> #include <cassert> #include <DTK_RendezvousMesh.hpp> #include <DTK_MeshTypes.hpp> #include <DTK_MeshTraits.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_OpaqueWrapper.hpp> #include <Teuchos_TypeTraits.hpp> #include <MBRange.hpp> //---------------------------------------------------------------------------// // MPI Setup //---------------------------------------------------------------------------// template<class Ordinal> Teuchos::RCP<const Teuchos::Comm<Ordinal> > getDefaultComm() { #ifdef HAVE_MPI return Teuchos::DefaultComm<Ordinal>::getComm(); #else return Teuchos::rcp(new Teuchos::SerialComm<Ordinal>() ); #endif } //---------------------------------------------------------------------------// // Mesh Implementation //---------------------------------------------------------------------------// class MyMesh { public: typedef int handle_type; MyMesh() { /* ... */ } MyMesh( const std::vector<int>& node_handles, const std::vector<double>& coords, const std::vector<int>& hex_handles, const std::vector<int>& hex_connectivity ) : d_node_handles( node_handles ) , d_coords( coords ) , d_hex_handles( hex_handles ) , d_hex_connectivity( hex_connectivity ) { /* ... */ } ~MyMesh() { /* ... */ } std::vector<int>::const_iterator nodesBegin() const { return d_node_handles.begin(); } std::vector<int>::const_iterator nodesEnd() const { return d_node_handles.end(); } std::vector<double>::const_iterator coordsBegin() const { return d_coords.begin(); } std::vector<double>::const_iterator coordsEnd() const { return d_coords.end(); } std::vector<int>::const_iterator hexesBegin() const { return d_hex_handles.begin(); } std::vector<int>::const_iterator hexesEnd() const { return d_hex_handles.end(); } std::vector<int>::const_iterator connectivityBegin() const { return d_hex_connectivity.begin(); } std::vector<int>::const_iterator connectivityEnd() const { return d_hex_connectivity.end(); } private: std::vector<int> d_node_handles; std::vector<double> d_coords; std::vector<int> d_hex_handles; std::vector<int> d_hex_connectivity; }; //---------------------------------------------------------------------------// // DTK Traits Specializations //---------------------------------------------------------------------------// namespace DataTransferKit { //---------------------------------------------------------------------------// // Mesh traits specialization for MyMesh template<> class MeshTraits<MyMesh> { public: typedef MyMesh::handle_type handle_type; typedef std::vector<int>::const_iterator const_node_iterator; typedef std::vector<double>::const_iterator const_coordinate_iterator; typedef std::vector<int>::const_iterator const_element_iterator; typedef std::vector<int>::const_iterator const_connectivity_iterator; static inline const_node_iterator nodesBegin( const MyMesh& mesh ) { return mesh.nodesBegin(); } static inline const_node_iterator nodesEnd( const MyMesh& mesh ) { return mesh.nodesEnd(); } static inline const_coordinate_iterator coordsBegin( const MyMesh& mesh ) { return mesh.coordsBegin(); } static inline const_coordinate_iterator coordsEnd( const MyMesh& mesh ) { return mesh.coordsEnd(); } static inline std::size_t elementType( const MyMesh& mesh ) { return DTK_REGION; } static inline std::size_t elementTopology( const MyMesh& mesh ) { return DTK_HEXAHEDRON; } static inline std::size_t nodesPerElement( const MyMesh& mesh ) { return 8; } static inline const_element_iterator elementsBegin( const MyMesh& mesh ) { return mesh.hexesBegin(); } static inline const_element_iterator elementsEnd( const MyMesh& mesh ) { return mesh.hexesEnd(); } static inline const_connectivity_iterator connectivityBegin( const MyMesh& mesh ) { return mesh.connectivityBegin(); } static inline const_connectivity_iterator connectivityEnd( const MyMesh& mesh ) { return mesh.connectivityEnd(); } }; } // end namespace DataTransferKit //---------------------------------------------------------------------------// // Mesh create funciton. //---------------------------------------------------------------------------// MyMesh buildMyMesh() { // Make some nodes. std::vector<int> node_handles; std::vector<double> coords; node_handles.push_back( 0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); node_handles.push_back( 4 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); node_handles.push_back( 9 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); node_handles.push_back( 2 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); node_handles.push_back( 3 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); node_handles.push_back( 8 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); node_handles.push_back( 1 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); node_handles.push_back( 6 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); node_handles.push_back( 12 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 2.0 ); node_handles.push_back( 7 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 2.0 ); node_handles.push_back( 13 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 2.0 ); node_handles.push_back( 5 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 2.0 ); // Make 2 hexahedrons. std::vector<int> hex_handles; std::vector<int> hex_connectivity; hex_handles.push_back( 0 ); hex_connectivity.push_back( 0 ); hex_connectivity.push_back( 4 ); hex_connectivity.push_back( 9 ); hex_connectivity.push_back( 2 ); hex_connectivity.push_back( 3 ); hex_connectivity.push_back( 8 ); hex_connectivity.push_back( 1 ); hex_connectivity.push_back( 6 ); hex_handles.push_back( 1 ); hex_connectivity.push_back( 3 ); hex_connectivity.push_back( 8 ); hex_connectivity.push_back( 1 ); hex_connectivity.push_back( 6 ); hex_connectivity.push_back( 12 ); hex_connectivity.push_back( 7 ); hex_connectivity.push_back( 13 ); hex_connectivity.push_back( 5 ); return MyMesh( node_handles, coords, hex_handles, hex_connectivity ); } //---------------------------------------------------------------------------// // Tests //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( RendezvousMesh, rendezvous_mesh_test ) { using namespace DataTransferKit; // Create a mesh. typedef MeshTraits<MyMesh> MT; MyMesh my_mesh = buildMyMesh(); Teuchos::RCP< RendezvousMesh<MyMesh::handle_type> > mesh = createRendezvousMesh( my_mesh ); // Get the moab interface. moab::ErrorCode error; RendezvousMesh<MyMesh::handle_type>::RCP_Moab moab = mesh->getMoab(); // Grab the elements. moab::Range mesh_elements = mesh->getElements(); // Check the moab mesh element data. moab::Range::const_iterator element_iterator; MyMesh::handle_type native_handle = 0; for ( element_iterator = mesh_elements.begin(); element_iterator != mesh_elements.end(); ++element_iterator, ++native_handle ) { TEST_ASSERT( mesh->getNativeHandle( *element_iterator ) == native_handle ); TEST_ASSERT( moab->type_from_handle( *element_iterator ) == moab::MBHEX ); } // Check the moab mesh vertex data. moab::Range connectivity; error = moab->get_connectivity( mesh_elements, connectivity ); TEST_ASSERT( moab::MB_SUCCESS == error ); std::vector<double> vertex_coords( 3 * connectivity.size() ); error = moab->get_coords( connectivity, &vertex_coords[0] ); TEST_ASSERT( moab::MB_SUCCESS == error ); std::vector<double>::const_iterator moab_coord_iterator = vertex_coords.begin(); typename MT::const_coordinate_iterator coord_iterator; for ( coord_iterator = MT::coordsBegin( my_mesh ); coord_iterator != MT::coordsEnd( my_mesh ); ++coord_iterator, ++moab_coord_iterator ) { TEST_ASSERT( *coord_iterator == *moab_coord_iterator ); } } //---------------------------------------------------------------------------// // end tstRendezvousMesh.cpp //---------------------------------------------------------------------------// <commit_msg>Updated RendezvousMesh unit tests for blocked data interface.<commit_after>//---------------------------------------------------------------------------// /*! * \file tstRendezvousMesh.cpp * \author Stuart R. Slattery * \brief RendezvousMesh unit tests. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <sstream> #include <algorithm> #include <cassert> #include <DTK_RendezvousMesh.hpp> #include <DTK_MeshTypes.hpp> #include <DTK_MeshTraits.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_OpaqueWrapper.hpp> #include <Teuchos_TypeTraits.hpp> #include <MBRange.hpp> //---------------------------------------------------------------------------// // MPI Setup //---------------------------------------------------------------------------// template<class Ordinal> Teuchos::RCP<const Teuchos::Comm<Ordinal> > getDefaultComm() { #ifdef HAVE_MPI return Teuchos::DefaultComm<Ordinal>::getComm(); #else return Teuchos::rcp(new Teuchos::SerialComm<Ordinal>() ); #endif } //---------------------------------------------------------------------------// // Mesh Implementation //---------------------------------------------------------------------------// class MyMesh { public: typedef int handle_type; MyMesh() { /* ... */ } MyMesh( const std::vector<int>& node_handles, const std::vector<double>& coords, const std::vector<int>& hex_handles, const std::vector<int>& hex_connectivity ) : d_node_handles( node_handles ) , d_coords( coords ) , d_hex_handles( hex_handles ) , d_hex_connectivity( hex_connectivity ) { /* ... */ } ~MyMesh() { /* ... */ } std::vector<int>::const_iterator nodesBegin() const { return d_node_handles.begin(); } std::vector<int>::const_iterator nodesEnd() const { return d_node_handles.end(); } std::vector<double>::const_iterator coordsBegin() const { return d_coords.begin(); } std::vector<double>::const_iterator coordsEnd() const { return d_coords.end(); } std::vector<int>::const_iterator hexesBegin() const { return d_hex_handles.begin(); } std::vector<int>::const_iterator hexesEnd() const { return d_hex_handles.end(); } std::vector<int>::const_iterator connectivityBegin() const { return d_hex_connectivity.begin(); } std::vector<int>::const_iterator connectivityEnd() const { return d_hex_connectivity.end(); } private: std::vector<int> d_node_handles; std::vector<double> d_coords; std::vector<int> d_hex_handles; std::vector<int> d_hex_connectivity; }; //---------------------------------------------------------------------------// // DTK Traits Specializations //---------------------------------------------------------------------------// namespace DataTransferKit { //---------------------------------------------------------------------------// // Mesh traits specialization for MyMesh template<> class MeshTraits<MyMesh> { public: typedef MyMesh::handle_type handle_type; typedef std::vector<int>::const_iterator const_node_iterator; typedef std::vector<double>::const_iterator const_coordinate_iterator; typedef std::vector<int>::const_iterator const_element_iterator; typedef std::vector<int>::const_iterator const_connectivity_iterator; static inline const_node_iterator nodesBegin( const MyMesh& mesh ) { return mesh.nodesBegin(); } static inline const_node_iterator nodesEnd( const MyMesh& mesh ) { return mesh.nodesEnd(); } static inline const_coordinate_iterator coordsBegin( const MyMesh& mesh ) { return mesh.coordsBegin(); } static inline const_coordinate_iterator coordsEnd( const MyMesh& mesh ) { return mesh.coordsEnd(); } static inline std::size_t elementType( const MyMesh& mesh ) { return DTK_REGION; } static inline std::size_t elementTopology( const MyMesh& mesh ) { return DTK_HEXAHEDRON; } static inline std::size_t nodesPerElement( const MyMesh& mesh ) { return 8; } static inline const_element_iterator elementsBegin( const MyMesh& mesh ) { return mesh.hexesBegin(); } static inline const_element_iterator elementsEnd( const MyMesh& mesh ) { return mesh.hexesEnd(); } static inline const_connectivity_iterator connectivityBegin( const MyMesh& mesh ) { return mesh.connectivityBegin(); } static inline const_connectivity_iterator connectivityEnd( const MyMesh& mesh ) { return mesh.connectivityEnd(); } }; } // end namespace DataTransferKit //---------------------------------------------------------------------------// // Mesh create funciton. //---------------------------------------------------------------------------// MyMesh buildMyMesh() { // Make some nodes. std::vector<int> node_handles; std::vector<double> coords; // handles node_handles.push_back( 0 ); node_handles.push_back( 4 ); node_handles.push_back( 9 ); node_handles.push_back( 2 ); node_handles.push_back( 3 ); node_handles.push_back( 8 ); node_handles.push_back( 1 ); node_handles.push_back( 6 ); node_handles.push_back( 12 ); node_handles.push_back( 7 ); node_handles.push_back( 13 ); node_handles.push_back( 5 ); // x coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); // y coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); // z coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 2.0 ); coords.push_back( 2.0 ); coords.push_back( 2.0 ); coords.push_back( 2.0 ); // Make 2 hexahedrons. std::vector<int> hex_handles; std::vector<int> hex_connectivity; // handles hex_handles.push_back( 0 ); hex_handles.push_back( 1 ); // 0 hex_connectivity.push_back( 0 ); hex_connectivity.push_back( 3 ); // 1 hex_connectivity.push_back( 4 ); hex_connectivity.push_back( 8 ); // 2 hex_connectivity.push_back( 9 ); hex_connectivity.push_back( 1 ); // 3 hex_connectivity.push_back( 2 ); hex_connectivity.push_back( 6 ); // 4 hex_connectivity.push_back( 3 ); hex_connectivity.push_back( 12 ); // 5 hex_connectivity.push_back( 8 ); hex_connectivity.push_back( 7 ); // 6 hex_connectivity.push_back( 1 ); hex_connectivity.push_back( 13 ); // 7 hex_connectivity.push_back( 6 ); hex_connectivity.push_back( 5 ); return MyMesh( node_handles, coords, hex_handles, hex_connectivity ); } //---------------------------------------------------------------------------// // Tests //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( RendezvousMesh, rendezvous_mesh_test ) { using namespace DataTransferKit; // Create a mesh. typedef MeshTraits<MyMesh> MT; MyMesh my_mesh = buildMyMesh(); Teuchos::RCP< RendezvousMesh<MyMesh::handle_type> > mesh = createRendezvousMesh( my_mesh ); // Get the moab interface. moab::ErrorCode error; RendezvousMesh<MyMesh::handle_type>::RCP_Moab moab = mesh->getMoab(); // Grab the elements. moab::Range mesh_elements = mesh->getElements(); // Check the moab mesh element data. moab::Range::const_iterator element_iterator; MyMesh::handle_type native_handle = 0; for ( element_iterator = mesh_elements.begin(); element_iterator != mesh_elements.end(); ++element_iterator, ++native_handle ) { TEST_ASSERT( mesh->getNativeHandle( *element_iterator ) == native_handle ); TEST_ASSERT( moab->type_from_handle( *element_iterator ) == moab::MBHEX ); } // Check the moab mesh vertex data. moab::Range connectivity; error = moab->get_connectivity( mesh_elements, connectivity ); TEST_ASSERT( moab::MB_SUCCESS == error ); std::vector<double> vertex_coords( 3 * connectivity.size() ); error = moab->get_coords( connectivity, &vertex_coords[0] ); TEST_ASSERT( moab::MB_SUCCESS == error ); int num_nodes = connectivity.size(); std::vector<double>::const_iterator moab_coord_iterator; typename MT::const_coordinate_iterator coord_iterator = MT::coordsBegin( my_mesh ); int i = 0; for ( moab_coord_iterator = vertex_coords.begin(); moab_coord_iterator != vertex_coords.end(); ++i ) { for ( int d = 0; d < 3; ++d, ++moab_coord_iterator ) { TEST_ASSERT( coord_iterator[d*num_nodes + i] == *moab_coord_iterator ); } } } //---------------------------------------------------------------------------// // end tstRendezvousMesh.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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 // // https://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 "llvm/Support/Casting.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" #include "tensorflow/compiler/mlir/xla/transforms/rewriters.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { namespace { static bool isAllZero(DenseIntElementsAttr attr) { if (!attr.isSplat()) return false; return attr.getSplatValue<IntegerAttr>().getInt() == 0; } static bool isSplatConst(Value val) { auto op = val.getDefiningOp(); if (!dyn_cast_or_null<xla_hlo::ConstOp>(op)) return false; Attribute attr = cast<xla_hlo::ConstOp>(op).value(); if (auto x = attr.dyn_cast<DenseElementsAttr>()) return x.isSplat(); return true; } // Returns true if a >= b. If the method can not evaluate or a < b, returns // false. static bool isGreaterThanOrEqualTo(Value a, Value b) { auto constOpA = dyn_cast_or_null<xla_hlo::ConstOp>(a.getDefiningOp()); auto constOpB = dyn_cast_or_null<xla_hlo::ConstOp>(b.getDefiningOp()); if (!constOpA || !constOpB) return false; Attribute attrA = constOpA.value(); Attribute attrB = constOpB.value(); assert(attrA.getType() == attrB.getType()); if (attrA.isa<DenseFPElementsAttr>()) { auto valA = attrA.cast<DenseFPElementsAttr>().getSplatValue<FloatAttr>().getValue(); auto valB = attrB.cast<DenseFPElementsAttr>().getSplatValue<FloatAttr>().getValue(); return valA >= valB; } if (attrA.isa<DenseIntElementsAttr>()) { auto valA = attrA.cast<DenseIntElementsAttr>() .getSplatValue<IntegerAttr>() .getInt(); auto valB = attrB.cast<DenseIntElementsAttr>() .getSplatValue<IntegerAttr>() .getInt(); return valA >= valB; } llvm_unreachable("unknown value type"); } // Returns the value of the given index. If `attr` is a nullptr, returns 0. static int64_t getAttrValue(DenseIntElementsAttr attr, ArrayRef<uint64_t> index) { if (!attr) return 0; return attr.getValue<int64_t>(index); } static DenseIntElementsAttr getPaddingAttrs(xla_hlo::PadOp padOp, DenseIntElementsAttr paddingAttr, Builder *builder) { int rank = padOp.operand().getType().cast<RankedTensorType>().getRank(); SmallVector<int64_t, 8> padding; for (unsigned i = 0; i < rank; ++i) { padding.push_back(getAttrValue(paddingAttr, {i, 0}) + padOp.edge_padding_low().getValue<int64_t>(i)); padding.push_back(getAttrValue(paddingAttr, {i, 1}) + padOp.edge_padding_high().getValue<int64_t>(i)); } // paddingAttr.getType() doesn't work because it can be a nullptr. auto type = RankedTensorType::get({rank, 2}, builder->getIntegerType(64)); return DenseIntElementsAttr::get(type, padding); } class FoldPadIntoMaxPool : public OpRewritePattern<xla_hlo::ReduceWindowOp> { public: using OpRewritePattern<xla_hlo::ReduceWindowOp>::OpRewritePattern; // Returns true if the region has a single block, and the block is formed as: // ^bb0(%lhs: tensor<f32>, %rhs: tensor<f32>): // no predecessors // %res = xla_hlo.maximum %lhs, %rhs : tensor<f32> // "xla_hlo.return"(%res) : (tensor<f32>) -> () bool isMaxPool(Region &region) const { if (region.getBlocks().size() != 1) return false; Block &block = region.front(); if (block.getOperations().size() != 2) return false; auto op = block.begin(); return isa<xla_hlo::MaxOp>(op); } // Returns true if there is a reduction window doesn't cover any elements. // ReudceWindow takes padding attributes. The leftmost pixel of the first // window is at "0 - pad_low[i]", and the rightmost pixel is at // "window_size - 1 - pad_low[i]". If there is a window doesn't cover any // elements, the result of the window is initial value. bool hasOutsideWindow(xla_hlo::ReduceWindowOp op) const { int rank = op.getType().cast<RankedTensorType>().getRank(); for (unsigned i = 0; i < rank; ++i) { int rightmost = (getAttrValue(op.window_dimensions(), {i}) - 1) - getAttrValue(op.paddingAttr(), {i, 0}); if (rightmost >= 0) return false; } return true; } // Matches the following conditions, so we can fold the PadOp into the // following ReduceWindowOp: // 1) This is a max pooling operation. // 2) The operand of ReduceWindowOp is defined by a PadOp, and the operand of // the PadOp is defined by a MaxOp. // 3) All the elements of the result of MaxOp are greater than or equal to // padding value. // 4) There is no a window that just contains initial value of ReduceWindowOp. // 5) The initial value of ReduceWindowOp is less than or equal to the // padding value. // These conditions imply that all the elements are greater than or equal to // the padding value, so we can fold the PadOp into the ReduceWindowOp, and // use the padding value as initial value. LogicalResult matchAndRewrite(xla_hlo::ReduceWindowOp op, PatternRewriter &rewriter) const override { if (!isMaxPool(op.body())) return failure(); if (!isSplatConst(op.init_value())) return failure(); auto padOp = dyn_cast_or_null<xla_hlo::PadOp>(op.operand().getDefiningOp()); if (!padOp) return failure(); if (!isAllZero(padOp.interior_padding())) return failure(); if (!isSplatConst(padOp.padding_value())) return failure(); auto maxOp = dyn_cast_or_null<xla_hlo::MaxOp>(padOp.operand().getDefiningOp()); if (!maxOp) return failure(); Value maxConstOperand = maxOp.lhs(); if (!isSplatConst(maxConstOperand)) maxConstOperand = maxOp.rhs(); if (!isSplatConst(maxConstOperand)) return failure(); // In case that max op isn't folded when it takes two constant attributes. if (isSplatConst(maxOp.rhs()) && isGreaterThanOrEqualTo(maxOp.rhs(), maxConstOperand)) maxConstOperand = maxOp.rhs(); // If `maxConstOperand` is greater than or equal to the padding value, then // all the elements (in `op.operand()`) are greater than or equal to the // padding value. if (!isGreaterThanOrEqualTo(maxConstOperand, padOp.padding_value())) return failure(); // If the padding value is greater than or equal to initial value and all // the windows cover at least one padding value, we can just make the // initial value as padding value. // There are two cases: // 1) There is no outside window, i.e., all the windows at least cover an // element. Since all the elements are greater than or equal to the // padding value, it implies that the result is always the same if // "`op.init_value()` <= padding_value". // 2) There is a outside window, i.e., all the elements are // `op.init_value()`. In this case, the result is `op.init_value()`. We // can not make the initial value as padding value in this case. if (!isGreaterThanOrEqualTo(padOp.padding_value(), op.init_value()) || hasOutsideWindow(op)) return failure(); auto resultType = op.getResult().getType(); auto paddingAttr = getPaddingAttrs(padOp, op.paddingAttr(), &rewriter); auto newOp = rewriter.create<xla_hlo::ReduceWindowOp>( op.getLoc(), resultType, padOp.operand(), padOp.padding_value(), op.window_dimensionsAttr(), op.window_stridesAttr(), op.base_dilationsAttr(), op.window_dilationsAttr(), paddingAttr); newOp.body().takeBody(op.body()); rewriter.replaceOp(op, newOp.getResult()); return success(); } }; struct HLOToHLOPreprocessing : public PassWrapper<HLOToHLOPreprocessing, FunctionPass> { void runOnFunction() override { MLIRContext *context = &getContext(); ConversionTarget conversionTarget(*context); OwningRewritePatternList conversionPatterns; conversionTarget .addLegalDialect<xla_hlo::XlaHloDialect, StandardOpsDialect>(); conversionTarget.addIllegalOp<xla_hlo::BatchNormInferenceOp>(); xla_hlo::PopulateUnfuseBatchNormPatterns(context, &conversionPatterns); if (failed(applyPartialConversion(getFunction(), conversionTarget, conversionPatterns))) { return signalPassFailure(); } OwningRewritePatternList patterns; patterns.insert<FoldPadIntoMaxPool>(context); applyPatternsGreedily(getOperation(), patterns); } }; } // namespace std::unique_ptr<OperationPass<FuncOp>> createHLOPreprocessingPass() { return std::make_unique<HLOToHLOPreprocessing>(); } static PassRegistration<HLOToHLOPreprocessing> legalize_pass( "iree-flow-hlo-to-hlo-preprocessing", "Apply hlo to hlo transformations for some hlo ops"); } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir <commit_msg>Fix the pass due to the change of xla_hlo::PopulateUnfuseBatchNormPatterns.<commit_after>// Copyright 2020 Google LLC // // 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 // // https://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 "llvm/Support/Casting.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" #include "tensorflow/compiler/mlir/xla/transforms/rewriters.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { namespace { static bool isAllZero(DenseIntElementsAttr attr) { if (!attr.isSplat()) return false; return attr.getSplatValue<IntegerAttr>().getInt() == 0; } static bool isSplatConst(Value val) { auto op = val.getDefiningOp(); if (!dyn_cast_or_null<xla_hlo::ConstOp>(op)) return false; Attribute attr = cast<xla_hlo::ConstOp>(op).value(); if (auto x = attr.dyn_cast<DenseElementsAttr>()) return x.isSplat(); return true; } // Returns true if a >= b. If the method can not evaluate or a < b, returns // false. static bool isGreaterThanOrEqualTo(Value a, Value b) { auto constOpA = dyn_cast_or_null<xla_hlo::ConstOp>(a.getDefiningOp()); auto constOpB = dyn_cast_or_null<xla_hlo::ConstOp>(b.getDefiningOp()); if (!constOpA || !constOpB) return false; Attribute attrA = constOpA.value(); Attribute attrB = constOpB.value(); assert(attrA.getType() == attrB.getType()); if (attrA.isa<DenseFPElementsAttr>()) { auto valA = attrA.cast<DenseFPElementsAttr>().getSplatValue<FloatAttr>().getValue(); auto valB = attrB.cast<DenseFPElementsAttr>().getSplatValue<FloatAttr>().getValue(); return valA >= valB; } if (attrA.isa<DenseIntElementsAttr>()) { auto valA = attrA.cast<DenseIntElementsAttr>() .getSplatValue<IntegerAttr>() .getInt(); auto valB = attrB.cast<DenseIntElementsAttr>() .getSplatValue<IntegerAttr>() .getInt(); return valA >= valB; } llvm_unreachable("unknown value type"); } // Returns the value of the given index. If `attr` is a nullptr, returns 0. static int64_t getAttrValue(DenseIntElementsAttr attr, ArrayRef<uint64_t> index) { if (!attr) return 0; return attr.getValue<int64_t>(index); } static DenseIntElementsAttr getPaddingAttrs(xla_hlo::PadOp padOp, DenseIntElementsAttr paddingAttr, Builder *builder) { int rank = padOp.operand().getType().cast<RankedTensorType>().getRank(); SmallVector<int64_t, 8> padding; for (unsigned i = 0; i < rank; ++i) { padding.push_back(getAttrValue(paddingAttr, {i, 0}) + padOp.edge_padding_low().getValue<int64_t>(i)); padding.push_back(getAttrValue(paddingAttr, {i, 1}) + padOp.edge_padding_high().getValue<int64_t>(i)); } // paddingAttr.getType() doesn't work because it can be a nullptr. auto type = RankedTensorType::get({rank, 2}, builder->getIntegerType(64)); return DenseIntElementsAttr::get(type, padding); } class FoldPadIntoMaxPool : public OpRewritePattern<xla_hlo::ReduceWindowOp> { public: using OpRewritePattern<xla_hlo::ReduceWindowOp>::OpRewritePattern; // Returns true if the region has a single block, and the block is formed as: // ^bb0(%lhs: tensor<f32>, %rhs: tensor<f32>): // no predecessors // %res = xla_hlo.maximum %lhs, %rhs : tensor<f32> // "xla_hlo.return"(%res) : (tensor<f32>) -> () bool isMaxPool(Region &region) const { if (region.getBlocks().size() != 1) return false; Block &block = region.front(); if (block.getOperations().size() != 2) return false; auto op = block.begin(); return isa<xla_hlo::MaxOp>(op); } // Returns true if there is a reduction window doesn't cover any elements. // ReudceWindow takes padding attributes. The leftmost pixel of the first // window is at "0 - pad_low[i]", and the rightmost pixel is at // "window_size - 1 - pad_low[i]". If there is a window doesn't cover any // elements, the result of the window is initial value. bool hasOutsideWindow(xla_hlo::ReduceWindowOp op) const { int rank = op.getType().cast<RankedTensorType>().getRank(); for (unsigned i = 0; i < rank; ++i) { int rightmost = (getAttrValue(op.window_dimensions(), {i}) - 1) - getAttrValue(op.paddingAttr(), {i, 0}); if (rightmost >= 0) return false; } return true; } // Matches the following conditions, so we can fold the PadOp into the // following ReduceWindowOp: // 1) This is a max pooling operation. // 2) The operand of ReduceWindowOp is defined by a PadOp, and the operand of // the PadOp is defined by a MaxOp. // 3) All the elements of the result of MaxOp are greater than or equal to // padding value. // 4) There is no a window that just contains initial value of ReduceWindowOp. // 5) The initial value of ReduceWindowOp is less than or equal to the // padding value. // These conditions imply that all the elements are greater than or equal to // the padding value, so we can fold the PadOp into the ReduceWindowOp, and // use the padding value as initial value. LogicalResult matchAndRewrite(xla_hlo::ReduceWindowOp op, PatternRewriter &rewriter) const override { if (!isMaxPool(op.body())) return failure(); if (!isSplatConst(op.init_value())) return failure(); auto padOp = dyn_cast_or_null<xla_hlo::PadOp>(op.operand().getDefiningOp()); if (!padOp) return failure(); if (!isAllZero(padOp.interior_padding())) return failure(); if (!isSplatConst(padOp.padding_value())) return failure(); auto maxOp = dyn_cast_or_null<xla_hlo::MaxOp>(padOp.operand().getDefiningOp()); if (!maxOp) return failure(); Value maxConstOperand = maxOp.lhs(); if (!isSplatConst(maxConstOperand)) maxConstOperand = maxOp.rhs(); if (!isSplatConst(maxConstOperand)) return failure(); // In case that max op isn't folded when it takes two constant attributes. if (isSplatConst(maxOp.rhs()) && isGreaterThanOrEqualTo(maxOp.rhs(), maxConstOperand)) maxConstOperand = maxOp.rhs(); // If `maxConstOperand` is greater than or equal to the padding value, then // all the elements (in `op.operand()`) are greater than or equal to the // padding value. if (!isGreaterThanOrEqualTo(maxConstOperand, padOp.padding_value())) return failure(); // If the padding value is greater than or equal to initial value and all // the windows cover at least one padding value, we can just make the // initial value as padding value. // There are two cases: // 1) There is no outside window, i.e., all the windows at least cover an // element. Since all the elements are greater than or equal to the // padding value, it implies that the result is always the same if // "`op.init_value()` <= padding_value". // 2) There is a outside window, i.e., all the elements are // `op.init_value()`. In this case, the result is `op.init_value()`. We // can not make the initial value as padding value in this case. if (!isGreaterThanOrEqualTo(padOp.padding_value(), op.init_value()) || hasOutsideWindow(op)) return failure(); auto resultType = op.getResult().getType(); auto paddingAttr = getPaddingAttrs(padOp, op.paddingAttr(), &rewriter); auto newOp = rewriter.create<xla_hlo::ReduceWindowOp>( op.getLoc(), resultType, padOp.operand(), padOp.padding_value(), op.window_dimensionsAttr(), op.window_stridesAttr(), op.base_dilationsAttr(), op.window_dilationsAttr(), paddingAttr); newOp.body().takeBody(op.body()); rewriter.replaceOp(op, newOp.getResult()); return success(); } }; struct HLOToHLOPreprocessing : public PassWrapper<HLOToHLOPreprocessing, FunctionPass> { void runOnFunction() override { MLIRContext *context = &getContext(); OwningRewritePatternList patterns; xla_hlo::PopulateUnfuseBatchNormPatterns(context, &patterns); patterns.insert<FoldPadIntoMaxPool>(context); applyPatternsGreedily(getOperation(), patterns); } }; } // namespace std::unique_ptr<OperationPass<FuncOp>> createHLOPreprocessingPass() { return std::make_unique<HLOToHLOPreprocessing>(); } static PassRegistration<HLOToHLOPreprocessing> legalize_pass( "iree-flow-hlo-to-hlo-preprocessing", "Apply hlo to hlo transformations for some hlo ops"); } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtSystemKit module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtDeclarative/qdeclarativeextensionplugin.h> #include <QtDeclarative/qdeclarative.h> QT_BEGIN_NAMESPACE class QSystemInfoDeclarativeModule : public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("Qt.systeminfo")); } }; QT_END_NAMESPACE #include "qsysteminfo.moc" Q_EXPORT_PLUGIN2(qsysteminfodeclarativemodule, QT_PREPEND_NAMESPACE(QSystemInfoDeclarativeModule)) <commit_msg>Add all elements.<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtSystemKit module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtDeclarative/qdeclarativeextensionplugin.h> #include <QtDeclarative/qdeclarative.h> #include "qbatteryinfo.h" #include "qdeviceinfo.h" #include "qdeviceprofile.h" #include "qdisplayinfo.h" #include "qinputdeviceinfo.h" #include "qnetworkinfo.h" #include "qscreensaver.h" #include "qstorageinfo.h" QT_BEGIN_NAMESPACE class QSystemInfoDeclarativeModule : public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("Qt.systeminfo")); int major = 1; int minor = 0; qmlRegisterType<QBatteryInfo>(uri, major, minor, "BatteryInfo"); qmlRegisterType<QDeviceInfo>(uri, major, minor, "DeviceInfo"); qmlRegisterType<QDeviceProfile>(uri, major, minor, "DeviceProfile"); qmlRegisterType<QDisplayInfo>(uri, major, minor, "DisplayInfo"); qmlRegisterType<QInputDeviceInfo>(uri, major, minor, "InputDeviceInfo"); qmlRegisterType<QNetworkInfo>(uri, major, minor, "NetworkInfo"); qmlRegisterType<QScreenSaver>(uri, major, minor, "ScreenSaver"); qmlRegisterType<QStorageInfo>(uri, major, minor, "StorageInfo"); } }; QT_END_NAMESPACE #include "qsysteminfo.moc" Q_EXPORT_PLUGIN2(qsysteminfodeclarativemodule, QT_PREPEND_NAMESPACE(QSystemInfoDeclarativeModule)) <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "scannerpluginmanager.h" #include <logging/logger.h> #include <logging/translator.h> #include <tools/hostosinfo.h> #include <QCoreApplication> #include <QDirIterator> #include <QLibrary> namespace qbs { namespace Internal { ScannerPluginManager *ScannerPluginManager::instance() { static ScannerPluginManager *i = new ScannerPluginManager; return i; } ScannerPluginManager::ScannerPluginManager() { } QList<ScannerPlugin *> ScannerPluginManager::scannersForFileTag(const FileTag &fileTag) { return instance()->m_scannerPlugins.value(fileTag); } void ScannerPluginManager::loadPlugins(const QStringList &pluginPaths, const Logger &logger) { QStringList filters; if (HostOsInfo::isWindowsHost()) filters << "*.dll"; else if (HostOsInfo::isOsxHost()) filters << "*.dylib"; else filters << "*.so"; foreach (const QString &pluginPath, pluginPaths) { logger.qbsTrace() << QString::fromLocal8Bit("pluginmanager: loading plugins from '%1'.") .arg(QDir::toNativeSeparators(pluginPath)); QDirIterator it(pluginPath, filters, QDir::Files); while (it.hasNext()) { const QString fileName = it.next(); QScopedPointer<QLibrary> lib(new QLibrary(fileName)); if (!lib->load()) { logger.qbsWarning() << Tr::tr("pluginmanager: couldn't load plugin '%1'.") .arg(QDir::toNativeSeparators(fileName)); continue; } getScanners_f getScanners = reinterpret_cast<getScanners_f>(lib->resolve("getScanners")); if (!getScanners) { logger.qbsWarning() << Tr::tr("pluginmanager: couldn't resolve " "symbol in '%1'.").arg(QDir::toNativeSeparators(fileName)); continue; } ScannerPlugin **plugins = getScanners(); if (plugins == 0) { logger.qbsWarning() << Tr::tr("pluginmanager: no scanners " "returned from '%1'.").arg(QDir::toNativeSeparators(fileName)); continue; } logger.qbsTrace() << QString::fromLocal8Bit("pluginmanager: scanner plugin '%1' " "loaded.").arg(QDir::toNativeSeparators(fileName)); for (int i = 0; plugins[i] != 0; ++i) m_scannerPlugins[FileTag(plugins[i]->fileTag)] += plugins[i]; m_libs.append(lib.take()); } } } } // namespace Internal } // namespace qbs <commit_msg>show QLibrary::errorString if plugin loading fails<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/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 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "scannerpluginmanager.h" #include <logging/logger.h> #include <logging/translator.h> #include <tools/hostosinfo.h> #include <QCoreApplication> #include <QDirIterator> #include <QLibrary> namespace qbs { namespace Internal { ScannerPluginManager *ScannerPluginManager::instance() { static ScannerPluginManager *i = new ScannerPluginManager; return i; } ScannerPluginManager::ScannerPluginManager() { } QList<ScannerPlugin *> ScannerPluginManager::scannersForFileTag(const FileTag &fileTag) { return instance()->m_scannerPlugins.value(fileTag); } void ScannerPluginManager::loadPlugins(const QStringList &pluginPaths, const Logger &logger) { QStringList filters; if (HostOsInfo::isWindowsHost()) filters << "*.dll"; else if (HostOsInfo::isOsxHost()) filters << "*.dylib"; else filters << "*.so"; foreach (const QString &pluginPath, pluginPaths) { logger.qbsTrace() << QString::fromLocal8Bit("pluginmanager: loading plugins from '%1'.") .arg(QDir::toNativeSeparators(pluginPath)); QDirIterator it(pluginPath, filters, QDir::Files); while (it.hasNext()) { const QString fileName = it.next(); QScopedPointer<QLibrary> lib(new QLibrary(fileName)); if (!lib->load()) { logger.qbsWarning() << Tr::tr("pluginmanager: couldn't load plugin '%1': %2") .arg(QDir::toNativeSeparators(fileName), lib->errorString()); continue; } getScanners_f getScanners = reinterpret_cast<getScanners_f>(lib->resolve("getScanners")); if (!getScanners) { logger.qbsWarning() << Tr::tr("pluginmanager: couldn't resolve " "symbol in '%1'.").arg(QDir::toNativeSeparators(fileName)); continue; } ScannerPlugin **plugins = getScanners(); if (plugins == 0) { logger.qbsWarning() << Tr::tr("pluginmanager: no scanners " "returned from '%1'.").arg(QDir::toNativeSeparators(fileName)); continue; } logger.qbsTrace() << QString::fromLocal8Bit("pluginmanager: scanner plugin '%1' " "loaded.").arg(QDir::toNativeSeparators(fileName)); for (int i = 0; plugins[i] != 0; ++i) m_scannerPlugins[FileTag(plugins[i]->fileTag)] += plugins[i]; m_libs.append(lib.take()); } } } } // namespace Internal } // namespace qbs <|endoftext|>
<commit_before>// Copyright (c) 2007, 2008 libmv authors. // // 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 "testing/testing.h" #include "libmv/logging/logging.h" #include "libmv/numeric/numeric.h" #include "libmv/multiview/fundamental.h" #include "libmv/multiview/projection.h" #include "libmv/multiview/five_point.h" namespace { using namespace libmv; struct TestData { Mat3X X; Mat3 R; Vec3 t; Mat3 E; Mat34 P1, P2; Mat2X x1, x2; }; TestData SomeTestData() { TestData d; d.X = Mat3X::Random(3,5); d.X.row(0).cwise() -= .5; d.X.row(1).cwise() -= .5; d.X.row(2).cwise() += 3; d.R = RotationAroundZ(0.3) * RotationAroundX(0.1) * RotationAroundY(0.2); d.t = Vec3::Random(); EssentialFromRt(Mat3::Identity(), Vec3::Zero(), d.R, d.t, &d.E); P_From_KRt(Mat3::Identity(), Mat3::Identity(), Vec3::Zero(), &d.P1); P_From_KRt(Mat3::Identity(), d.R, d.t, &d.P2); Project(d.P1, d.X, &d.x1); Project(d.P2, d.X, &d.x2); return d; } TEST(FivePointsNullspaceBasis, SatisfyEpipolarConstraint) { TestData d = SomeTestData(); Mat E_basis = FivePointsNullspaceBasis(d.x1, d.x2); for (int s = 0; s < 4; ++s) { Mat3 E; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { E(i, j) = E_basis(3 * i + j, s); } } for (int i = 0; i < d.x1.cols(); ++i) { Vec3 x1(d.x1(0,i), d.x1(1,i), 1); Vec3 x2(d.x2(0,i), d.x2(1,i), 1); EXPECT_NEAR(0, x2.dot(E * x1), 1e-6); } } } double EvalPolynomial(Vec p, double x, double y, double z) { return p(coef_xxx) * x * x * x + p(coef_xxy) * x * x * y + p(coef_xxz) * x * x * z + p(coef_xyy) * x * y * y + p(coef_xyz) * x * y * z + p(coef_xzz) * x * z * z + p(coef_yyy) * y * y * y + p(coef_yyz) * y * y * z + p(coef_yzz) * y * z * z + p(coef_zzz) * z * z * z + p(coef_xx) * x * x + p(coef_xy) * x * y + p(coef_xz) * x * z + p(coef_yy) * y * y + p(coef_yz) * y * z + p(coef_zz) * z * z + p(coef_x) * x + p(coef_y) * y + p(coef_z) * z + p(coef_1) * 1; } TEST(o1, Evaluation) { Vec p1 = Vec::Zero(20), p2 = Vec::Zero(20); p1(coef_x) = double(rand()) / RAND_MAX; p1(coef_y) = double(rand()) / RAND_MAX; p1(coef_z) = double(rand()) / RAND_MAX; p1(coef_1) = double(rand()) / RAND_MAX; p2(coef_x) = double(rand()) / RAND_MAX; p2(coef_y) = double(rand()) / RAND_MAX; p2(coef_z) = double(rand()) / RAND_MAX; p2(coef_1) = double(rand()) / RAND_MAX; Vec p3 = o1(p1, p2); for (double z = -5; z < 5; ++z) { for (double y = -5; y < 5; ++y) { for (double x = -5; x < 5; ++x) { EXPECT_NEAR(EvalPolynomial(p3, x, y, z), EvalPolynomial(p1, x, y, z) * EvalPolynomial(p2, x, y, z), 1e-8); } } } } TEST(o2, Evaluation) { Vec p1 = Vec::Zero(20), p2 = Vec::Zero(20); p1(coef_xx) = double(rand()) / RAND_MAX; p1(coef_xy) = double(rand()) / RAND_MAX; p1(coef_xz) = double(rand()) / RAND_MAX; p1(coef_yy) = double(rand()) / RAND_MAX; p1(coef_yz) = double(rand()) / RAND_MAX; p1(coef_zz) = double(rand()) / RAND_MAX; p1(coef_x) = double(rand()) / RAND_MAX; p1(coef_y) = double(rand()) / RAND_MAX; p1(coef_z) = double(rand()) / RAND_MAX; p1(coef_1) = double(rand()) / RAND_MAX; p2(coef_x) = double(rand()) / RAND_MAX; p2(coef_y) = double(rand()) / RAND_MAX; p2(coef_z) = double(rand()) / RAND_MAX; p2(coef_1) = double(rand()) / RAND_MAX; Vec p3 = o2(p1, p2); for (double z = -5; z < 5; ++z) { for (double y = -5; y < 5; ++y) { for (double x = -5; x < 5; ++x) { EXPECT_NEAR(EvalPolynomial(p3, x, y, z), EvalPolynomial(p1, x, y, z) * EvalPolynomial(p2, x, y, z), 1e-8); } } } } TEST(FivePointsGaussJordan, RandomMatrix) { Mat M = Mat::Random(10, 20); FivePointsGaussJordan(&M); Mat I = Mat::Identity(10,10); Mat M1 = M.block<10,10>(0,0); EXPECT_MATRIX_NEAR(I, M1, 1e-8); } TEST(FivePointsRelativePose, Random) { TestData d = SomeTestData(); vector<Mat3> Es; vector<Mat3> Rs; vector<Vec3> ts; FivePointsRelativePose(d.x1, d.x2, &Es); // Recover rotation and translation from E Rs.resize(Es.size()); ts.resize(Es.size()); for (int s = 0; s < Es.size(); ++s) { MotionFromEssentialAndCorrespondence(Es[s], Mat3::Identity(), d.x1.col(0), Mat3::Identity(), d.x2.col(0), &Rs[s], &ts[s]); } bool solution_found = false; for (int i = 0; i < Rs.size(); ++i) { // Check that E holds the essential matrix constraints. Mat3 E = Es[i]; EXPECT_NEAR(0, E.determinant(), 1e-8); Mat3 O = 2 * E * E.transpose() * E - (E * E.transpose()).trace() * E; EXPECT_MATRIX_NEAR(Mat3::Zero(), O, 1e-8); // Check that we find the correct relative orientation. if (FrobeniusDistance(d.R, Rs[i]) < 1e-3 && (d.t / d.t.norm() - ts[i] / ts[i].norm()).norm() < 1e-3) { solution_found = true; break; } } EXPECT_TRUE(solution_found); } } // namespace <commit_msg>Alignment<commit_after>// Copyright (c) 2007, 2008 libmv authors. // // 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 "testing/testing.h" #include "libmv/logging/logging.h" #include "libmv/numeric/numeric.h" #include "libmv/multiview/fundamental.h" #include "libmv/multiview/projection.h" #include "libmv/multiview/five_point.h" namespace { using namespace libmv; struct TestData { Mat3X X; Mat3 R; Vec3 t; Mat3 E; Mat34 P1, P2; Mat2X x1, x2; }; TestData SomeTestData() { TestData d; d.X = Mat3X::Random(3,5); d.X.row(0).cwise() -= .5; d.X.row(1).cwise() -= .5; d.X.row(2).cwise() += 3; d.R = RotationAroundZ(0.3) * RotationAroundX(0.1) * RotationAroundY(0.2); d.t = Vec3::Random(); EssentialFromRt(Mat3::Identity(), Vec3::Zero(), d.R, d.t, &d.E); P_From_KRt(Mat3::Identity(), Mat3::Identity(), Vec3::Zero(), &d.P1); P_From_KRt(Mat3::Identity(), d.R, d.t, &d.P2); Project(d.P1, d.X, &d.x1); Project(d.P2, d.X, &d.x2); return d; } TEST(FivePointsNullspaceBasis, SatisfyEpipolarConstraint) { TestData d = SomeTestData(); Mat E_basis = FivePointsNullspaceBasis(d.x1, d.x2); for (int s = 0; s < 4; ++s) { Mat3 E; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { E(i, j) = E_basis(3 * i + j, s); } } for (int i = 0; i < d.x1.cols(); ++i) { Vec3 x1(d.x1(0,i), d.x1(1,i), 1); Vec3 x2(d.x2(0,i), d.x2(1,i), 1); EXPECT_NEAR(0, x2.dot(E * x1), 1e-6); } } } double EvalPolynomial(Vec p, double x, double y, double z) { return p(coef_xxx) * x * x * x + p(coef_xxy) * x * x * y + p(coef_xxz) * x * x * z + p(coef_xyy) * x * y * y + p(coef_xyz) * x * y * z + p(coef_xzz) * x * z * z + p(coef_yyy) * y * y * y + p(coef_yyz) * y * y * z + p(coef_yzz) * y * z * z + p(coef_zzz) * z * z * z + p(coef_xx) * x * x + p(coef_xy) * x * y + p(coef_xz) * x * z + p(coef_yy) * y * y + p(coef_yz) * y * z + p(coef_zz) * z * z + p(coef_x) * x + p(coef_y) * y + p(coef_z) * z + p(coef_1) * 1; } TEST(o1, Evaluation) { Vec p1 = Vec::Zero(20), p2 = Vec::Zero(20); p1(coef_x) = double(rand()) / RAND_MAX; p1(coef_y) = double(rand()) / RAND_MAX; p1(coef_z) = double(rand()) / RAND_MAX; p1(coef_1) = double(rand()) / RAND_MAX; p2(coef_x) = double(rand()) / RAND_MAX; p2(coef_y) = double(rand()) / RAND_MAX; p2(coef_z) = double(rand()) / RAND_MAX; p2(coef_1) = double(rand()) / RAND_MAX; Vec p3 = o1(p1, p2); for (double z = -5; z < 5; ++z) { for (double y = -5; y < 5; ++y) { for (double x = -5; x < 5; ++x) { EXPECT_NEAR(EvalPolynomial(p3, x, y, z), EvalPolynomial(p1, x, y, z) * EvalPolynomial(p2, x, y, z), 1e-8); } } } } TEST(o2, Evaluation) { Vec p1 = Vec::Zero(20), p2 = Vec::Zero(20); p1(coef_xx) = double(rand()) / RAND_MAX; p1(coef_xy) = double(rand()) / RAND_MAX; p1(coef_xz) = double(rand()) / RAND_MAX; p1(coef_yy) = double(rand()) / RAND_MAX; p1(coef_yz) = double(rand()) / RAND_MAX; p1(coef_zz) = double(rand()) / RAND_MAX; p1(coef_x) = double(rand()) / RAND_MAX; p1(coef_y) = double(rand()) / RAND_MAX; p1(coef_z) = double(rand()) / RAND_MAX; p1(coef_1) = double(rand()) / RAND_MAX; p2(coef_x) = double(rand()) / RAND_MAX; p2(coef_y) = double(rand()) / RAND_MAX; p2(coef_z) = double(rand()) / RAND_MAX; p2(coef_1) = double(rand()) / RAND_MAX; Vec p3 = o2(p1, p2); for (double z = -5; z < 5; ++z) { for (double y = -5; y < 5; ++y) { for (double x = -5; x < 5; ++x) { EXPECT_NEAR(EvalPolynomial(p3, x, y, z), EvalPolynomial(p1, x, y, z) * EvalPolynomial(p2, x, y, z), 1e-8); } } } } TEST(FivePointsGaussJordan, RandomMatrix) { Mat M = Mat::Random(10, 20); FivePointsGaussJordan(&M); Mat I = Mat::Identity(10,10); Mat M1 = M.block<10,10>(0,0); EXPECT_MATRIX_NEAR(I, M1, 1e-8); } TEST(FivePointsRelativePose, Random) { TestData d = SomeTestData(); vector<Mat3> Es; vector<Mat3> Rs; vector<Vec3> ts; FivePointsRelativePose(d.x1, d.x2, &Es); // Recover rotation and translation from E Rs.resize(Es.size()); ts.resize(Es.size()); for (int s = 0; s < Es.size(); ++s) { MotionFromEssentialAndCorrespondence(Es[s], Mat3::Identity(), d.x1.col(0), Mat3::Identity(), d.x2.col(0), &Rs[s], &ts[s]); } bool solution_found = false; for (int i = 0; i < Rs.size(); ++i) { // Check that E holds the essential matrix constraints. Mat3 E = Es[i]; EXPECT_NEAR(0, E.determinant(), 1e-8); Mat3 O = 2 * E * E.transpose() * E - (E * E.transpose()).trace() * E; EXPECT_MATRIX_NEAR(Mat3::Zero(), O, 1e-8); // Check that we find the correct relative orientation. if (FrobeniusDistance(d.R, Rs[i]) < 1e-3 && (d.t / d.t.norm() - ts[i] / ts[i].norm()).norm() < 1e-3) { solution_found = true; break; } } EXPECT_TRUE(solution_found); } } // namespace <|endoftext|>
<commit_before>#include <string.h> #include "pokeyDevice.h" PokeyDevice::PokeyDevice(sPoKeysNetworkDeviceSummary deviceSummary, uint8_t index) { _pokey = PK_ConnectToNetworkDevice(&deviceSummary); _index = index; _userId = deviceSummary.UserID; _serialNumber = std::to_string(deviceSummary.SerialNumber); _firwareVersionMajorMajor = (deviceSummary.FirmwareVersionMajor >> 4) + 1; _firwareVersionMajor = deviceSummary.FirmwareVersionMajor & 0x0F; _firwareVersionMinor = deviceSummary.FirmwareVersionMinor; memcpy(&_ipAddress, &deviceSummary.IPaddress, 4); _hardwareType = deviceSummary.HWtype; _dhcp = deviceSummary.DHCP; loadPinConfiguration(); } /** * @brief Default destructor for PokeyDevice * * @return nothing */ PokeyDevice::~PokeyDevice() { PK_DisconnectDevice(_pokey); } std::string PokeyDevice::hardwareTypeString() { if (_hardwareType == 31) { return "Pokey 57E"; } return "Unknown"; } bool PokeyDevice::validatePinCapability(int number, std::string type) { // assert(_pokey); bool retVal = true; return retVal; }<commit_msg>re-order header<commit_after>#include "pokeyDevice.h" #include <string.h> PokeyDevice::PokeyDevice(sPoKeysNetworkDeviceSummary deviceSummary, uint8_t index) { _pokey = PK_ConnectToNetworkDevice(&deviceSummary); _index = index; _userId = deviceSummary.UserID; _serialNumber = std::to_string(deviceSummary.SerialNumber); _firwareVersionMajorMajor = (deviceSummary.FirmwareVersionMajor >> 4) + 1; _firwareVersionMajor = deviceSummary.FirmwareVersionMajor & 0x0F; _firwareVersionMinor = deviceSummary.FirmwareVersionMinor; memcpy(&_ipAddress, &deviceSummary.IPaddress, 4); _hardwareType = deviceSummary.HWtype; _dhcp = deviceSummary.DHCP; loadPinConfiguration(); } /** * @brief Default destructor for PokeyDevice * * @return nothing */ PokeyDevice::~PokeyDevice() { PK_DisconnectDevice(_pokey); } std::string PokeyDevice::hardwareTypeString() { if (_hardwareType == 31) { return "Pokey 57E"; } return "Unknown"; } bool PokeyDevice::validatePinCapability(int number, std::string type) { // assert(_pokey); bool retVal = true; return retVal; }<|endoftext|>
<commit_before>/*************************************************************************** file : $URL: https://frepple.svn.sourceforge.net/svnroot/frepple/trunk/modules/forecast/forecastsolver.cpp $ version : $LastChangedRevision$ $LastChangedBy$ date : $LastChangedDate$ ***************************************************************************/ /*************************************************************************** * * * Copyright (C) 2007 by Johan De Taeye * * * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "forecast.h" namespace module_forecast { double Forecast::generateFutureValues(const double history[], unsigned int count, bool debug) { // Validate presence of history if (!history) throw RuntimeException("Null argument to forecast function"); // Create a list of forecasting methods. @todo list should be dynamic, based on availability of hsitory // We create the forecasting objects in stack memory for best performance. SingleExponential single_exp; DoubleExponential double_exp; int numberOfMethods = 2; ForecastMethod* methods[2]; methods[0] = &single_exp; methods[1] = &double_exp; // Evaluate each forecast method double best_error = DBL_MAX; int best_method = 0; double error; for (int i=0; i<numberOfMethods; ++i) { error = methods[i]->generateForecast(history, count, debug); if (error<best_error) { best_error = error; best_method = i; } } // Apply the most appropriate forecasting method return best_error; } double Forecast::SingleExponential::initial_alfa = 0.2; double Forecast::SingleExponential::min_alfa = 0.0; double Forecast::SingleExponential::max_alfa = 1.0; unsigned int Forecast::SingleExponential::skip = 7; double Forecast::SingleExponential::generateForecast (const double history[], unsigned int count, bool debug) { // Verify whether this is a valid forecast method. // - We need at least 10 buckets after the warmup period. if (count < skip + 10) return DBL_MAX; unsigned int iteration = 1; bool upperboundarytested = false; bool lowerboundarytested = false; double error_mad, delta, df_dalfa_i, sum_11, sum_12; for (; iteration <= Forecast::getForecastIterations(); ++iteration) { // Initialize the iteration f_i = history[0]; df_dalfa_i = 0; sum_11 = 0; sum_12 = 0; error_mad = 0; // Calculate the forecast and forecast error. // We also compute the sums required for the Marquardt optimization. for (unsigned long i = 0; i < count; ++i) { df_dalfa_i = history[i-1] - f_i + (1 - alfa) * df_dalfa_i; f_i = history[i-1] * alfa + (1 - alfa) * f_i; sum_12 += df_dalfa_i * (history[i] - f_i); sum_11 += df_dalfa_i * df_dalfa_i; if (i > skip) // Don't measure during the warmup period error_mad += fabs(f_i - history[i]); } // Calculate a delta for the alfa parameter delta = sum_11 ? sum_12 / sum_11 : sum_12; alfa += delta; // Stop when we repeatedly bounce against the limits. // Testing a limits once is allowed. if (alfa > max_alfa) { alfa = max_alfa; if (upperboundarytested) break; upperboundarytested = true; } else if (alfa < min_alfa) { alfa = min_alfa; if (lowerboundarytested) break; lowerboundarytested = true; } // Stop when we are close enough if (fabs(delta) < 0.01) break; } // Echo the result if (debug) logger << "single exponential" //"Forecast " << fcst.getName() xxx << ": alfa " << alfa << ", mad " << error_mad << ", " << iteration << " iterations" << ", delta alfa " << delta << ", forecast " << f_i << endl; return error_mad; } double Forecast::DoubleExponential::initial_alfa = 0.2; double Forecast::DoubleExponential::min_alfa = 0.0; double Forecast::DoubleExponential::max_alfa = 1.0; double Forecast::DoubleExponential::initial_gamma = 0.05; double Forecast::DoubleExponential::min_gamma = 0.0; double Forecast::DoubleExponential::max_gamma = 1.0; unsigned int Forecast::DoubleExponential::skip = 7; double Forecast::DoubleExponential::generateForecast /* @todo optimization not implemented yet*/ (const double history[], unsigned int count, bool debug) { // Verify whether this is a valid forecast method. // - We need at least 10 buckets after the warmup period. if (count < skip + 10) return DBL_MAX; unsigned int iteration = 1; double error_mad, trend_i, constant_i, constant_i_minus_1; //xxxfor (; iteration <= Forecast::getForecastIterations(); ++iteration) for (; iteration <= 1; ++iteration) { // Initialize the iteration constant_i = history[0]; trend_i = history[1] - history[0]; error_mad = 0; // Calculate the forecast and forecast error. // We also compute the sums required for the Marquardt optimization. for (unsigned long i = 0; i < count; ++i) { constant_i_minus_1 = constant_i; constant_i = history[i-1] * alfa + (1 - alfa) * (constant_i + trend_i); trend_i = gamma * (constant_i - constant_i_minus_1) + (1 - gamma) * trend_i; if (i > skip) // Don't measure during the warmup period error_mad += fabs(constant_i + trend_i - history[i]); } } // Echo the result if (debug) logger << "double exponential" //"Forecast " << fcst.getName() xxx << ": alfa " << alfa << ", gamma " << gamma << ", mad " << error_mad << ", " << iteration << " iterations" << ", constant " << constant_i << ", trend " << trend_i << ", forecast " << (trend_i + constant_i) << endl; return error_mad; } } // end namespace <commit_msg>- tune minimum alfa to increase the stability of the forecasting optimization <commit_after>/*************************************************************************** file : $URL: https://frepple.svn.sourceforge.net/svnroot/frepple/trunk/modules/forecast/forecastsolver.cpp $ version : $LastChangedRevision$ $LastChangedBy$ date : $LastChangedDate$ ***************************************************************************/ /*************************************************************************** * * * Copyright (C) 2007 by Johan De Taeye * * * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "forecast.h" namespace module_forecast { double Forecast::generateFutureValues(const double history[], unsigned int count, bool debug) { // Validate presence of history if (!history) throw RuntimeException("Null argument to forecast function"); // Create a list of forecasting methods. @todo list should be dynamic, based on availability of hsitory // We create the forecasting objects in stack memory for best performance. SingleExponential single_exp; DoubleExponential double_exp; int numberOfMethods = 2; ForecastMethod* methods[2]; methods[0] = &single_exp; methods[1] = &double_exp; // Evaluate each forecast method double best_error = DBL_MAX; int best_method = 0; double error; for (int i=0; i<numberOfMethods; ++i) { error = methods[i]->generateForecast(history, count, debug); if (error<best_error) { best_error = error; best_method = i; } } // Apply the most appropriate forecasting method return best_error; } double Forecast::SingleExponential::initial_alfa = 0.2; double Forecast::SingleExponential::min_alfa = 0.03; double Forecast::SingleExponential::max_alfa = 1.0; unsigned int Forecast::SingleExponential::skip = 7; double Forecast::SingleExponential::generateForecast (const double history[], unsigned int count, bool debug) { // Verify whether this is a valid forecast method. // - We need at least 10 buckets after the warmup period. if (count < skip + 10) return DBL_MAX; unsigned int iteration = 1; bool upperboundarytested = false; bool lowerboundarytested = false; double error_mad, delta, df_dalfa_i, sum_11, sum_12; for (; iteration <= Forecast::getForecastIterations(); ++iteration) { // Initialize the iteration f_i = history[0]; df_dalfa_i = 0; sum_11 = 0; sum_12 = 0; error_mad = 0; // Calculate the forecast and forecast error. // We also compute the sums required for the Marquardt optimization. for (unsigned long i = 0; i < count; ++i) { df_dalfa_i = history[i-1] - f_i + (1 - alfa) * df_dalfa_i; f_i = history[i-1] * alfa + (1 - alfa) * f_i; sum_12 += df_dalfa_i * (history[i] - f_i); sum_11 += df_dalfa_i * df_dalfa_i; if (i > skip) // Don't measure during the warmup period error_mad += fabs(f_i - history[i]); } // Calculate a delta for the alfa parameter delta = sum_11 ? sum_12 / sum_11 : sum_12; alfa += delta; // Stop when we repeatedly bounce against the limits. // Testing a limits once is allowed. if (alfa > max_alfa) { alfa = max_alfa; if (upperboundarytested) break; upperboundarytested = true; } else if (alfa < min_alfa) { alfa = min_alfa; if (lowerboundarytested) break; lowerboundarytested = true; } // Stop when we are close enough if (fabs(delta) < 0.01) break; } // Echo the result if (debug) logger << "single exponential" //"Forecast " << fcst.getName() xxx << ": alfa " << alfa << ", mad " << error_mad << ", " << iteration << " iterations" << ", delta alfa " << delta << ", forecast " << f_i << endl; return error_mad; } double Forecast::DoubleExponential::initial_alfa = 0.2; double Forecast::DoubleExponential::min_alfa = 0.03; double Forecast::DoubleExponential::max_alfa = 1.0; double Forecast::DoubleExponential::initial_gamma = 0.05; double Forecast::DoubleExponential::min_gamma = 0.0; double Forecast::DoubleExponential::max_gamma = 1.0; unsigned int Forecast::DoubleExponential::skip = 7; double Forecast::DoubleExponential::generateForecast /* @todo optimization not implemented yet*/ (const double history[], unsigned int count, bool debug) { // Verify whether this is a valid forecast method. // - We need at least 10 buckets after the warmup period. if (count < skip + 10) return DBL_MAX; unsigned int iteration = 1; double error_mad, trend_i, constant_i, constant_i_minus_1; //xxxfor (; iteration <= Forecast::getForecastIterations(); ++iteration) for (; iteration <= 1; ++iteration) { // Initialize the iteration constant_i = history[0]; trend_i = history[1] - history[0]; error_mad = 0; // Calculate the forecast and forecast error. // We also compute the sums required for the Marquardt optimization. for (unsigned long i = 0; i < count; ++i) { constant_i_minus_1 = constant_i; constant_i = history[i-1] * alfa + (1 - alfa) * (constant_i + trend_i); trend_i = gamma * (constant_i - constant_i_minus_1) + (1 - gamma) * trend_i; if (i > skip) // Don't measure during the warmup period error_mad += fabs(constant_i + trend_i - history[i]); } } // Echo the result if (debug) logger << "double exponential" //"Forecast " << fcst.getName() xxx << ": alfa " << alfa << ", gamma " << gamma << ", mad " << error_mad << ", " << iteration << " iterations" << ", constant " << constant_i << ", trend " << trend_i << ", forecast " << (trend_i + constant_i) << endl; return error_mad; } } // end namespace <|endoftext|>
<commit_before>// Program name: atomic++/Prad.cpp // Author: Thomas Body // Author email: tajb500@york.ac.uk // Date of creation: 17 July 2017 // // Program function: output the radiated power (Prad) // by using OpenADAS rates on output JSON from SD1D run // // Based on the TBody/atomic1D code, which is in turn based on the cfe316/atomic code // // Include declarations #include <ostream> #include <cstdio> //For print formatting (printf, fprintf, sprintf, snprintf) #include "atomicpp/ImpuritySpecies.hpp" #include "atomicpp/RateCoefficient.hpp" #include "atomicpp/SD1DData.hpp" #include "atomicpp/RateEquations.hpp" #include "atomicpp/ExternalModules/json.hpp" using json = nlohmann::json; // extern const double eV_to_J; //Conversion factor between electron-volts and joules (effective units J/eV) // extern const double amu_to_kg; ////Conversion factor between atomic-mass-units and kilograms (effective units kg/amu) //Only used for getting guess values for the impurity ionisation-stage densities -- not required for final code //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////// NOT FOR FINAL SIMULATION CODE ////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::vector<double> computeIonisationDistribution(atomicpp::ImpuritySpecies& impurity, double Te, double Ne, double Nz, double Nn){ int Z = impurity.get_atomic_number(); std::vector<double> iz_stage_distribution(Z+1); // std::set GS density equal to 1 (arbitrary) iz_stage_distribution[0] = 1; double sum_iz = 1; // Loop over 0, 1, ..., Z-1 // Each charge state is std::set in terms of the density of the previous for(int k=0; k<Z; ++k){ // Ionisation // Get the atomicpp::RateCoefficient from the rate_coefficient std::map (atrribute of impurity) std::shared_ptr<atomicpp::RateCoefficient> iz_rate_coefficient = impurity.get_rate_coefficient("ionisation"); // Evaluate the atomicpp::RateCoefficient at the point double k_iz_evaluated = iz_rate_coefficient->call0D(k, Te, Ne); // Recombination // Get the atomicpp::RateCoefficient from the rate_coefficient std::map (atrribute of impurity) std::shared_ptr<atomicpp::RateCoefficient> rec_rate_coefficient = impurity.get_rate_coefficient("recombination"); // Evaluate the atomicpp::RateCoefficient at the point double k_rec_evaluated = rec_rate_coefficient->call0D(k, Te, Ne); // The ratio of ionisation from the (k)th stage and recombination from the (k+1)th std::sets the equilibrium densities // of the (k+1)th stage in terms of the (k)th (since R = Nz * Ne * rate_coefficient) N.b. Since there is no // ionisation from the bare nucleus, and no recombination onto the neutral (ignoring anion formation) the 'k' // value of ionisation coeffs is shifted down by one relative to the recombination coeffs - therefore this // evaluation actually gives the balance iz_stage_distribution[k+1] = iz_stage_distribution[k] * (k_iz_evaluated/k_rec_evaluated); sum_iz += iz_stage_distribution[k+1]; } // # Normalise such that the sum over all ionisation stages is '1' at all points for(int k=0; k<=Z; ++k){ iz_stage_distribution[k] = iz_stage_distribution[k] / sum_iz; } return iz_stage_distribution; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////// NOT FOR FINAL SIMULATION CODE ////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main(){ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Setup the atomicpp::ImpuritySpecies object const std::string expt_results_json="sd1d-case-05.json"; std::string impurity_symbol="c"; std::string hydrogen_symbol="h"; atomicpp::ImpuritySpecies impurity(impurity_symbol); atomicpp::ImpuritySpecies hydrogen(hydrogen_symbol); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Process the expt_results_json to extract // density(s) = electron density (in m^-3) // temperature(s) = electron/ion temperature (in eV) // neutral_fraction(s) = neutral density/electron density (no units) // where s is 1D distance index. Time is already contracted (using final time-step) // Second argument is impurity fraction atomicpp::SD1DData experiment(expt_results_json, 1e-2); // N.b. This is only for training the data //Cast the SD1D data into a form which is like how the function will be called by SD1D //This is all not required for SD1D -- it's just to train the code with reasonable numbers // const double mz = impurity.get_mass(); //amu int constant_position_index = 0; double Te = experiment.get_temperature()[constant_position_index]; double Ne = experiment.get_density()[constant_position_index]; double Vi = 3.10080599e-01 * 69205.6142373; //Picked random values from SD1D output. Using rho_s0 * Omega_ci to normalise (probably wrong!!) double Vn = 1.32440666e-01 * 69205.6142373; //Picked random values from SD1D output. Using rho_s0 * Omega_ci to normalise (probably wrong!!) double neutral_fraction = experiment.get_neutral_fraction()[constant_position_index]; double Nn = Ne * neutral_fraction; double Nz = experiment.get_impurity_density()[constant_position_index]; // Compute the iz-stage-distribution to create the Nzk (charged-resolved impurity) density std::vector std::vector<double> iz_stage_distribution = computeIonisationDistribution(impurity, Te, Ne, Nz, Nn); std::vector<double> Nzk(impurity.get_atomic_number()+1); for(int k=0; k<=impurity.get_atomic_number(); ++k){ // Use the plasma temperature, and then add a scaling based on the charge so that there's different velocities for each charge // (so that momentum transfer results in an observable effect) Nzk[k] = Nz * iz_stage_distribution[k]; // std::printf("Nzk^%d: %e \n", k, Nzk[k]); //To train python data } std::vector<double> Vzk(impurity.get_atomic_number()+1); for(int k=0; k<=impurity.get_atomic_number(); ++k){ Vzk[k] = Vi; // sqrt(2 * Te * eV_to_J / (mz * amu_to_kg)); // std::printf("Vz_i^(%i): %+.2e [m/s]\n",k ,Vzk[k]); } std::vector<double> Nhk(hydrogen.get_atomic_number()+1); Nhk[0] = Nn; Nhk[1] = Ne; std::vector<double> Vhk(hydrogen.get_atomic_number()+1); for(int k=0; k<=hydrogen.get_atomic_number(); ++k){ Vhk[k] = Vi; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Time dependant solver code atomicpp::RateEquations impurity_derivatives(impurity); //Organised as a atomicpp::RateEquations object for cleanliness impurity_derivatives.setThresholdDensity(0); //Density threshold - ignore ionisation stages which don't have at least this density impurity_derivatives.setDominantIonMass(1.0); //Dominant ion mass in amu, for the stopping time calculation atomicpp::DerivStruct derivative_struct = impurity_derivatives.computeDerivs(6000, 1e19, Vi, Nn, Vn, Nzk, Vzk); // double Pcool = derivative_struct.Pcool; // double Prad = derivative_struct.Prad; // std::vector<double> dNzk = derivative_struct.dNzk; // std::vector<double> F_zk = derivative_struct.F_zk; // double dNe = derivative_struct.dNe; // double F_i = derivative_struct.F_i; // double dNn = derivative_struct.dNn; // double F_n = derivative_struct.F_n; std::printf("\nDerivatives for %s\n",impurity.get_name().c_str()); impurity_derivatives.printDerivativeStruct(derivative_struct); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // atomicpp::RateEquations hydrogen_derivatives(hydrogen); //Organised as a atomicpp::RateEquations object for cleanliness // hydrogen_derivatives.setThresholdDensity(0.0); //Density threshold - ignore ionisation stages which don't have at least this density // atomicpp::DerivStruct derivative_struct_H = hydrogen_derivatives.computeDerivsHydrogen(6309.573445, 1e19, Nhk, Vhk); // std::printf("\nDerivatives for %s\n",hydrogen.get_name().c_str()); // hydrogen_derivatives.printDerivativeStruct(derivative_struct_H); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Comparison to Post PSI // Ne = 1e18; // Te = 6; // Nn = 0; // total_power = computeRadiatedPower(impurity, Te, Ne, Nz, Nn); // std::cout << "Comparison to PSI paper:" << total_power << "W/m3" << std::endl; // std::cout << "Comparison to PSI paper:" << total_power/(Nz*Ne) << "Wm3" << std::endl; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // std::pair<int, double> Te_interp, Ne_interp; // Te_interp = findSharedInterpolation(impurity.get_rate_coefficient("blank")->get_log_temp(), Te); // Ne_interp = findSharedInterpolation(impurity.get_rate_coefficient("blank")->get_log_dens(), Ne); // int Z = impurity.get_atomic_number(); // const double eV_to_J = 1.60217662e-19; //J per eV // if (impurity.get_has_charge_exchange()){ // std::vector<double> dNn_from_stage(impurity.get_atomic_number(), 0.0); // std::vector<double> cx_rec_to_below(Z+1, 0.0); // std::vector<double> cx_rec_from_above(Z+1, 0.0); // std::shared_ptr<atomicpp::RateCoefficient> cx_recombination_coefficient = impurity.get_rate_coefficient("cx_rec"); // std::shared_ptr<atomicpp::RateCoefficient> cx_power_coefficient = impurity.get_rate_coefficient("cx_power"); // for(int k=0; k < Z; ++k){//N.b. iterating over all data indicies of the rate coefficient, hence the < // // m^-3 s^-1 // double cx_recombination_coefficient_evaluated = cx_recombination_coefficient->call0D(k, Te_interp, Ne_interp); // double cx_recombination_rate = cx_recombination_coefficient_evaluated * Nn * Nzk[k+1]; // // W m^-3 // double cx_power_coefficient_evaluated = cx_power_coefficient->call0D(k, Te_interp, Ne_interp); // double cx_power_rate = cx_power_coefficient_evaluated * Nn * Nzk[k+1] / eV_to_J; // std::printf("cx: %e [m^-3 s^-1], cx_power: %e [eV m^-3 s^-1], per transition: %e [eV] \n", cx_recombination_rate, cx_power_rate, cx_power_rate/cx_recombination_rate); // } // } } <commit_msg>Changed Prad back to sensible Te<commit_after>// Program name: atomic++/Prad.cpp // Author: Thomas Body // Author email: tajb500@york.ac.uk // Date of creation: 17 July 2017 // // Program function: output the radiated power (Prad) // by using OpenADAS rates on output JSON from SD1D run // // Based on the TBody/atomic1D code, which is in turn based on the cfe316/atomic code // // Include declarations #include <ostream> #include <cstdio> //For print formatting (printf, fprintf, sprintf, snprintf) #include "atomicpp/ImpuritySpecies.hpp" #include "atomicpp/RateCoefficient.hpp" #include "atomicpp/SD1DData.hpp" #include "atomicpp/RateEquations.hpp" #include "atomicpp/ExternalModules/json.hpp" using json = nlohmann::json; // extern const double eV_to_J; //Conversion factor between electron-volts and joules (effective units J/eV) // extern const double amu_to_kg; ////Conversion factor between atomic-mass-units and kilograms (effective units kg/amu) //Only used for getting guess values for the impurity ionisation-stage densities -- not required for final code //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////// NOT FOR FINAL SIMULATION CODE ////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::vector<double> computeIonisationDistribution(atomicpp::ImpuritySpecies& impurity, double Te, double Ne, double Nz, double Nn){ int Z = impurity.get_atomic_number(); std::vector<double> iz_stage_distribution(Z+1); // std::set GS density equal to 1 (arbitrary) iz_stage_distribution[0] = 1; double sum_iz = 1; // Loop over 0, 1, ..., Z-1 // Each charge state is std::set in terms of the density of the previous for(int k=0; k<Z; ++k){ // Ionisation // Get the atomicpp::RateCoefficient from the rate_coefficient std::map (atrribute of impurity) std::shared_ptr<atomicpp::RateCoefficient> iz_rate_coefficient = impurity.get_rate_coefficient("ionisation"); // Evaluate the atomicpp::RateCoefficient at the point double k_iz_evaluated = iz_rate_coefficient->call0D(k, Te, Ne); // Recombination // Get the atomicpp::RateCoefficient from the rate_coefficient std::map (atrribute of impurity) std::shared_ptr<atomicpp::RateCoefficient> rec_rate_coefficient = impurity.get_rate_coefficient("recombination"); // Evaluate the atomicpp::RateCoefficient at the point double k_rec_evaluated = rec_rate_coefficient->call0D(k, Te, Ne); // The ratio of ionisation from the (k)th stage and recombination from the (k+1)th std::sets the equilibrium densities // of the (k+1)th stage in terms of the (k)th (since R = Nz * Ne * rate_coefficient) N.b. Since there is no // ionisation from the bare nucleus, and no recombination onto the neutral (ignoring anion formation) the 'k' // value of ionisation coeffs is shifted down by one relative to the recombination coeffs - therefore this // evaluation actually gives the balance iz_stage_distribution[k+1] = iz_stage_distribution[k] * (k_iz_evaluated/k_rec_evaluated); sum_iz += iz_stage_distribution[k+1]; } // # Normalise such that the sum over all ionisation stages is '1' at all points for(int k=0; k<=Z; ++k){ iz_stage_distribution[k] = iz_stage_distribution[k] / sum_iz; } return iz_stage_distribution; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////// NOT FOR FINAL SIMULATION CODE ////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main(){ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Setup the atomicpp::ImpuritySpecies object const std::string expt_results_json="sd1d-case-05.json"; std::string impurity_symbol="c"; std::string hydrogen_symbol="h"; atomicpp::ImpuritySpecies impurity(impurity_symbol); atomicpp::ImpuritySpecies hydrogen(hydrogen_symbol); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Process the expt_results_json to extract // density(s) = electron density (in m^-3) // temperature(s) = electron/ion temperature (in eV) // neutral_fraction(s) = neutral density/electron density (no units) // where s is 1D distance index. Time is already contracted (using final time-step) // Second argument is impurity fraction atomicpp::SD1DData experiment(expt_results_json, 1e-2); // N.b. This is only for training the data //Cast the SD1D data into a form which is like how the function will be called by SD1D //This is all not required for SD1D -- it's just to train the code with reasonable numbers // const double mz = impurity.get_mass(); //amu int constant_position_index = 0; double Te = experiment.get_temperature()[constant_position_index]; double Ne = experiment.get_density()[constant_position_index]; double Vi = 3.10080599e-01 * 69205.6142373; //Picked random values from SD1D output. Using rho_s0 * Omega_ci to normalise (probably wrong!!) double Vn = 1.32440666e-01 * 69205.6142373; //Picked random values from SD1D output. Using rho_s0 * Omega_ci to normalise (probably wrong!!) double neutral_fraction = experiment.get_neutral_fraction()[constant_position_index]; double Nn = Ne * neutral_fraction; double Nz = experiment.get_impurity_density()[constant_position_index]; // Compute the iz-stage-distribution to create the Nzk (charged-resolved impurity) density std::vector std::vector<double> iz_stage_distribution = computeIonisationDistribution(impurity, Te, Ne, Nz, Nn); std::vector<double> Nzk(impurity.get_atomic_number()+1); for(int k=0; k<=impurity.get_atomic_number(); ++k){ // Use the plasma temperature, and then add a scaling based on the charge so that there's different velocities for each charge // (so that momentum transfer results in an observable effect) Nzk[k] = Nz * iz_stage_distribution[k]; // std::printf("Nzk^%d: %e \n", k, Nzk[k]); //To train python data } std::vector<double> Vzk(impurity.get_atomic_number()+1); for(int k=0; k<=impurity.get_atomic_number(); ++k){ Vzk[k] = Vi; // sqrt(2 * Te * eV_to_J / (mz * amu_to_kg)); // std::printf("Vz_i^(%i): %+.2e [m/s]\n",k ,Vzk[k]); } std::vector<double> Nhk(hydrogen.get_atomic_number()+1); Nhk[0] = Nn; Nhk[1] = Ne; std::vector<double> Vhk(hydrogen.get_atomic_number()+1); for(int k=0; k<=hydrogen.get_atomic_number(); ++k){ Vhk[k] = Vi; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Time dependant solver code atomicpp::RateEquations impurity_derivatives(impurity); //Organised as a atomicpp::RateEquations object for cleanliness impurity_derivatives.setThresholdDensity(0); //Density threshold - ignore ionisation stages which don't have at least this density impurity_derivatives.setDominantIonMass(1.0); //Dominant ion mass in amu, for the stopping time calculation atomicpp::DerivStruct derivative_struct = impurity_derivatives.computeDerivs(50, 1e19, Vi, Nn, Vn, Nzk, Vzk); // double Pcool = derivative_struct.Pcool; // double Prad = derivative_struct.Prad; // std::vector<double> dNzk = derivative_struct.dNzk; // std::vector<double> F_zk = derivative_struct.F_zk; // double dNe = derivative_struct.dNe; // double F_i = derivative_struct.F_i; // double dNn = derivative_struct.dNn; // double F_n = derivative_struct.F_n; std::printf("\nDerivatives for %s\n",impurity.get_name().c_str()); impurity_derivatives.printDerivativeStruct(derivative_struct); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // atomicpp::RateEquations hydrogen_derivatives(hydrogen); //Organised as a atomicpp::RateEquations object for cleanliness // hydrogen_derivatives.setThresholdDensity(0.0); //Density threshold - ignore ionisation stages which don't have at least this density // atomicpp::DerivStruct derivative_struct_H = hydrogen_derivatives.computeDerivsHydrogen(6309.573445, 1e19, Nhk, Vhk); // std::printf("\nDerivatives for %s\n",hydrogen.get_name().c_str()); // hydrogen_derivatives.printDerivativeStruct(derivative_struct_H); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Comparison to Post PSI // Ne = 1e18; // Te = 6; // Nn = 0; // total_power = computeRadiatedPower(impurity, Te, Ne, Nz, Nn); // std::cout << "Comparison to PSI paper:" << total_power << "W/m3" << std::endl; // std::cout << "Comparison to PSI paper:" << total_power/(Nz*Ne) << "Wm3" << std::endl; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // std::pair<int, double> Te_interp, Ne_interp; // Te_interp = findSharedInterpolation(impurity.get_rate_coefficient("blank")->get_log_temp(), Te); // Ne_interp = findSharedInterpolation(impurity.get_rate_coefficient("blank")->get_log_dens(), Ne); // int Z = impurity.get_atomic_number(); // const double eV_to_J = 1.60217662e-19; //J per eV // if (impurity.get_has_charge_exchange()){ // std::vector<double> dNn_from_stage(impurity.get_atomic_number(), 0.0); // std::vector<double> cx_rec_to_below(Z+1, 0.0); // std::vector<double> cx_rec_from_above(Z+1, 0.0); // std::shared_ptr<atomicpp::RateCoefficient> cx_recombination_coefficient = impurity.get_rate_coefficient("cx_rec"); // std::shared_ptr<atomicpp::RateCoefficient> cx_power_coefficient = impurity.get_rate_coefficient("cx_power"); // for(int k=0; k < Z; ++k){//N.b. iterating over all data indicies of the rate coefficient, hence the < // // m^-3 s^-1 // double cx_recombination_coefficient_evaluated = cx_recombination_coefficient->call0D(k, Te_interp, Ne_interp); // double cx_recombination_rate = cx_recombination_coefficient_evaluated * Nn * Nzk[k+1]; // // W m^-3 // double cx_power_coefficient_evaluated = cx_power_coefficient->call0D(k, Te_interp, Ne_interp); // double cx_power_rate = cx_power_coefficient_evaluated * Nn * Nzk[k+1] / eV_to_J; // std::printf("cx: %e [m^-3 s^-1], cx_power: %e [eV m^-3 s^-1], per transition: %e [eV] \n", cx_recombination_rate, cx_power_rate, cx_power_rate/cx_recombination_rate); // } // } } <|endoftext|>
<commit_before><commit_msg>Plot SDD calibration history also for single sides<commit_after><|endoftext|>
<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__) #include <TFile.h> #include <TH1F.h> #include <TGraph.h> #include <TGraphErrors.h> #include <TStyle.h> #include <TGrid.h> #include <TCanvas.h> #include <TSystem.h> #include <TLatex.h> #include <TLegend.h> #include <TLegendEntry.h> #include <TObjArray.h> #include "AliCDBEntry.h" #include "AliITSCalibrationSDD.h" #endif /* $Id: PlotCalibSDDVsTime.C 41568 2010-06-03 09:08:39Z prino $ */ // Macro to plot the calibration parameters from the OCDB files // created from PEDESTAL and PULSER runs vs. Time // Origin: F. Prino (prino@to.infn.it) void PlotCalibSDDVsTime(Int_t year=2011, Int_t firstRun=142600, Int_t lastRun=999999999, Int_t selectedMod=-1){ gStyle->SetOptTitle(0); gStyle->SetOptStat(0); gStyle->SetPadLeftMargin(0.14); gStyle->SetTitleOffset(1.4,"Y"); TGrid::Connect("alien:",0,0,"t"); gSystem->Exec(Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/CalibSDD\" \"Run*.root\" > runCalibAlien.txt",year)); FILE* listruns=fopen("runCalibAlien.txt","r"); TH1F* hbase=new TH1F("hbase","",60,0.5,120.5); TH1F* hnoise=new TH1F("hnoise","",100,0.,7.); TH1F* hgain=new TH1F("hgain","",100,0.,4.); TH1F* hchstatus=new TH1F("hchstatus","",2,-0.5,1.5); TH1F* hchstatus3=new TH1F("hchstatus3","",2,-0.5,1.5); TH1F* hchstatus4=new TH1F("hchstatus4","",2,-0.5,1.5); TGraphErrors* gbasevstim=new TGraphErrors(0); TGraphErrors* gnoisevstim=new TGraphErrors(0); TGraphErrors* ggainvstim=new TGraphErrors(0); TGraphErrors* gstatvstim=new TGraphErrors(0); TGraphErrors* gfracvstim=new TGraphErrors(0); TGraphErrors* gfrac3vstim=new TGraphErrors(0); TGraphErrors* gfrac4vstim=new TGraphErrors(0); gbasevstim->SetName("gbasevstim"); gnoisevstim->SetName("gnoisevstim"); ggainvstim->SetName("ggainvstim"); gstatvstim->SetName("gstatvstim"); gfracvstim->SetName("gfracvstim"); gfrac3vstim->SetName("gfrac3vstim"); gfrac4vstim->SetName("gfrac4vstim"); gbasevstim->SetTitle("Baseline vs. run"); gnoisevstim->SetTitle("Noise vs. run"); ggainvstim->SetTitle("Gain vs. run"); gstatvstim->SetTitle("Good Anodes vs. run"); gfracvstim->SetTitle("Fraction of Good Anodes vs. run"); gfrac3vstim->SetTitle("Fraction of Good Anodes vs. run"); gfrac4vstim->SetTitle("Fraction of Good Anodes vs. run"); Char_t filnam[200],filnamalien[200]; Int_t iPoint=0; Int_t nrun,nrun2,nv,ns; while(!feof(listruns)){ hbase->Reset(); hnoise->Reset(); hgain->Reset(); hchstatus->Reset(); hchstatus3->Reset(); hchstatus4->Reset(); fscanf(listruns,"%s\n",filnam); Char_t directory[100]; sprintf(directory,"/alice/data/%d",year); if(!strstr(filnam,directory)) continue; sscanf(filnam,"/alice/data/%d/OCDB/ITS/Calib/CalibSDD/Run%d_%d_v%d_s%d.root",&year,&nrun,&nrun2,&nv,&ns); if(year==2009 && (nrun<85639 && nrun2> 85639)) continue; // protection for files with swapped ladders 4-5 of layer 3 if(year==2009 && (nrun>100000 && nv< 184)) continue; // protection for files with swapped ladder 0-1 of layer 4 if(year==2010 && (nrun>=114603 && nv< 98)) continue; // protection for files without treatment of masked hybrids if(year==2011 && (nrun>=145349 && nrun2> 148978)) continue; // protection for files affected by problem in second DA if(nrun<firstRun) continue; if(nrun>lastRun) continue; sprintf(filnamalien,"alien://%s",filnam); printf("Open file: %s\n",filnam); TFile *f= TFile::Open(filnamalien); AliCDBEntry *ent=(AliCDBEntry*)f->Get("AliCDBEntry"); TObjArray *calSDD = (TObjArray *)ent->GetObject(); printf("Run %d Entries in array=%d \n",nrun,calSDD->GetEntriesFast()); AliITSCalibrationSDD *cal; for(Int_t iMod=0; iMod<260;iMod++){ if(selectedMod>=240 && (iMod+240)!=selectedMod) continue; cal=(AliITSCalibrationSDD*)calSDD->At(iMod); if(cal==0) continue; for(Int_t iAn=0; iAn<512; iAn++){ Int_t ic=cal->GetChip(iAn); Float_t base=cal->GetBaseline(iAn); Float_t noise=cal->GetNoiseAfterElectronics(iAn); Float_t gain=cal->GetChannelGain(iAn); if(cal->IsBadChannel(iAn)){ hchstatus->Fill(0); if(iMod<84) hchstatus3->Fill(0); else hchstatus4->Fill(0); } if(!cal->IsBadChannel(iAn) && !cal->IsChipBad(ic) && !cal->IsBad() ){ hbase->Fill(base); hchstatus->Fill(1); if(iMod<84) hchstatus3->Fill(1); else hchstatus4->Fill(1); hnoise->Fill(noise); hgain->Fill(gain); } } } printf("Run %d <Base> = %f <Noise> =%f Entries = %d\n",nrun,hbase->GetMean(),hnoise->GetMean(),(Int_t)hbase->GetEntries()); if(selectedMod==-1 && (Int_t)hbase->GetEntries()==0) continue; gbasevstim->SetPoint(iPoint,(Double_t)nrun,hbase->GetMean()); gbasevstim->SetPointError(iPoint,0.,hbase->GetRMS()); gnoisevstim->SetPoint(iPoint,(Double_t)nrun,hnoise->GetMean()); gnoisevstim->SetPointError(iPoint,0.,hnoise->GetRMS()); ggainvstim->SetPoint(iPoint,(Double_t)nrun,hgain->GetMean()); ggainvstim->SetPointError(iPoint,0.,hgain->GetRMS()); gstatvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2)); Float_t normMod=260.; if(selectedMod!=-1) normMod=1.; gfracvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2)/normMod/512.); gfrac3vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus3->GetBinContent(2)/84./512.); gfrac4vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus4->GetBinContent(2)/176./512.); iPoint++; f->Close(); } TFile *ofil=new TFile(Form("Calib%dVsTime.root",year),"recreate"); gbasevstim->Write(); gnoisevstim->Write(); ggainvstim->Write(); gstatvstim->Write(); ofil->Close(); TCanvas* cbase=new TCanvas("cbase","Baselines"); gbasevstim->SetFillColor(kOrange-2); gbasevstim->SetMarkerStyle(20); gbasevstim->Draw("AP3"); gbasevstim->Draw("PLXSAME"); gbasevstim->SetMinimum(0.); gbasevstim->SetMaximum(70.); gbasevstim->GetXaxis()->SetTitle("Run number"); gbasevstim->GetYaxis()->SetTitle("<Baseline> (ADC counts)"); cbase->SaveAs(Form("BaseRun%d.gif",year)); TCanvas* cnoise=new TCanvas("cnoise","Noise"); gnoisevstim->SetFillColor(kOrange-2); gnoisevstim->SetMarkerStyle(20); gnoisevstim->Draw("AP3"); gnoisevstim->Draw("PLXSAME"); gnoisevstim->SetMinimum(0.); gnoisevstim->SetMaximum(4.); gnoisevstim->GetXaxis()->SetTitle("Run number"); gnoisevstim->GetYaxis()->SetTitle("<Noise> (ADC counts)"); cnoise->SaveAs(Form("NoiseRun%d.gif",year)); TCanvas* cgain=new TCanvas("cgain","Gain"); ggainvstim->SetFillColor(kOrange-2); ggainvstim->SetMarkerStyle(20); ggainvstim->Draw("AP3"); ggainvstim->Draw("PLXSAME"); ggainvstim->SetMinimum(0.); ggainvstim->SetMaximum(4.); ggainvstim->GetXaxis()->SetTitle("Run number"); ggainvstim->GetYaxis()->SetTitle("<Gain> (ADC/DAC)"); cgain->SaveAs(Form("GainRun%d.gif",year)); TCanvas* cstatus=new TCanvas("cstatus","Good channels"); gstatvstim->SetFillColor(kOrange-2); gstatvstim->SetMarkerStyle(20); gstatvstim->Draw("AP3"); gstatvstim->Draw("PLXSAME"); if(selectedMod==-1){ gstatvstim->SetMinimum(100000.); gstatvstim->SetMaximum(133000.); }else{ gstatvstim->SetMinimum(0.); gstatvstim->SetMaximum(512.); } gstatvstim->GetXaxis()->SetTitle("Run number"); if(selectedMod==-1){ gstatvstim->GetYaxis()->SetTitle("Number of good anodes in acquisition"); }else{ gstatvstim->GetYaxis()->SetTitle(Form("Number of good anodes in od %d",selectedMod)); } cstatus->SaveAs(Form("GoodAnodesRun%d.gif",year)); TCanvas* cfrac=new TCanvas("cfrac","Fraction of Good"); gfracvstim->SetMarkerStyle(20); gfrac3vstim->SetMarkerStyle(22); gfrac3vstim->SetMarkerColor(2); gfrac3vstim->SetLineColor(2); gfrac4vstim->SetMarkerStyle(23); gfrac4vstim->SetMarkerColor(4); gfrac4vstim->SetLineColor(4); gfracvstim->Draw("APL"); gfracvstim->SetMinimum(0.7); gfracvstim->SetMaximum(1.05); gfracvstim->GetXaxis()->SetTitle("Run number"); if(selectedMod==-1){ gfracvstim->GetYaxis()->SetTitle("Fraction of good anodes in acquisition"); gfrac3vstim->Draw("PLSAME"); gfrac4vstim->Draw("PLSAME"); TLegend* leg=new TLegend(0.2,0.15,0.45,0.35); leg->SetFillColor(0); TLegendEntry* entr=leg->AddEntry(gfrac3vstim,"Layer 3","P"); entr->SetTextColor(2); entr=leg->AddEntry(gfrac4vstim,"Layer 4","P"); entr->SetTextColor(4); entr=leg->AddEntry(gfracvstim,"All","P"); entr->SetTextColor(1); leg->Draw(); }else{ gfracvstim->GetYaxis()->SetTitle(Form("Fraction of good anodes in mod %d",selectedMod)); } cfrac->SaveAs(Form("FractionGoodRun%d.gif",year)); } <commit_msg>Minor fix in macro to plot SDD calibs<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__) #include <TFile.h> #include <TH1F.h> #include <TGraph.h> #include <TGraphErrors.h> #include <TStyle.h> #include <TGrid.h> #include <TCanvas.h> #include <TSystem.h> #include <TLatex.h> #include <TLegend.h> #include <TLegendEntry.h> #include <TObjArray.h> #include "AliCDBEntry.h" #include "AliITSCalibrationSDD.h" #endif /* $Id: PlotCalibSDDVsTime.C 41568 2010-06-03 09:08:39Z prino $ */ // Macro to plot the calibration parameters from the OCDB files // created from PEDESTAL and PULSER runs vs. Time // Origin: F. Prino (prino@to.infn.it) void PlotCalibSDDVsTime(Int_t year=2011, Int_t firstRun=142600, Int_t lastRun=999999999, Int_t selectedMod=-1){ gStyle->SetOptTitle(0); gStyle->SetOptStat(0); gStyle->SetPadLeftMargin(0.14); gStyle->SetTitleOffset(1.4,"Y"); TGrid::Connect("alien:",0,0,"t"); gSystem->Exec(Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/CalibSDD\" \"Run*.root\" > runCalibAlien.txt",year)); FILE* listruns=fopen("runCalibAlien.txt","r"); TH1F* hbase=new TH1F("hbase","",60,0.5,120.5); TH1F* hnoise=new TH1F("hnoise","",100,0.,7.); TH1F* hgain=new TH1F("hgain","",100,0.,4.); TH1F* hchstatus=new TH1F("hchstatus","",2,-0.5,1.5); TH1F* hchstatus3=new TH1F("hchstatus3","",2,-0.5,1.5); TH1F* hchstatus4=new TH1F("hchstatus4","",2,-0.5,1.5); TGraphErrors* gbasevstim=new TGraphErrors(0); TGraphErrors* gnoisevstim=new TGraphErrors(0); TGraphErrors* ggainvstim=new TGraphErrors(0); TGraphErrors* gstatvstim=new TGraphErrors(0); TGraphErrors* gfracvstim=new TGraphErrors(0); TGraphErrors* gfrac3vstim=new TGraphErrors(0); TGraphErrors* gfrac4vstim=new TGraphErrors(0); gbasevstim->SetName("gbasevstim"); gnoisevstim->SetName("gnoisevstim"); ggainvstim->SetName("ggainvstim"); gstatvstim->SetName("gstatvstim"); gfracvstim->SetName("gfracvstim"); gfrac3vstim->SetName("gfrac3vstim"); gfrac4vstim->SetName("gfrac4vstim"); gbasevstim->SetTitle("Baseline vs. run"); gnoisevstim->SetTitle("Noise vs. run"); ggainvstim->SetTitle("Gain vs. run"); gstatvstim->SetTitle("Good Anodes vs. run"); gfracvstim->SetTitle("Fraction of Good Anodes vs. run"); gfrac3vstim->SetTitle("Fraction of Good Anodes vs. run"); gfrac4vstim->SetTitle("Fraction of Good Anodes vs. run"); Char_t filnam[200],filnamalien[200]; Int_t iPoint=0; Int_t nrun,nrun2,nv,ns; while(!feof(listruns)){ hbase->Reset(); hnoise->Reset(); hgain->Reset(); hchstatus->Reset(); hchstatus3->Reset(); hchstatus4->Reset(); fscanf(listruns,"%s\n",filnam); Char_t directory[100]; sprintf(directory,"/alice/data/%d",year); if(!strstr(filnam,directory)) continue; sscanf(filnam,"/alice/data/%d/OCDB/ITS/Calib/CalibSDD/Run%d_%d_v%d_s%d.root",&year,&nrun,&nrun2,&nv,&ns); if(year==2009 && (nrun<85639 && nrun2> 85639)) continue; // protection for files with swapped ladders 4-5 of layer 3 if(year==2009 && (nrun>100000 && nv< 184)) continue; // protection for files with swapped ladder 0-1 of layer 4 if(year==2010 && (nrun>=114603 && nv< 98)) continue; // protection for files without treatment of masked hybrids if(year==2011 && (nrun>=145349 && nrun<=148978) && nrun2> 148978) continue; // protection for files affected by problem in second DA if(nrun<firstRun) continue; if(nrun>lastRun) continue; sprintf(filnamalien,"alien://%s",filnam); printf("Open file: %s\n",filnam); TFile *f= TFile::Open(filnamalien); AliCDBEntry *ent=(AliCDBEntry*)f->Get("AliCDBEntry"); TObjArray *calSDD = (TObjArray *)ent->GetObject(); printf("Run %d Entries in array=%d \n",nrun,calSDD->GetEntriesFast()); AliITSCalibrationSDD *cal; for(Int_t iMod=0; iMod<260;iMod++){ if(selectedMod>=240 && (iMod+240)!=selectedMod) continue; cal=(AliITSCalibrationSDD*)calSDD->At(iMod); if(cal==0) continue; for(Int_t iAn=0; iAn<512; iAn++){ Int_t ic=cal->GetChip(iAn); Float_t base=cal->GetBaseline(iAn); Float_t noise=cal->GetNoiseAfterElectronics(iAn); Float_t gain=cal->GetChannelGain(iAn); if(cal->IsBadChannel(iAn)){ hchstatus->Fill(0); if(iMod<84) hchstatus3->Fill(0); else hchstatus4->Fill(0); } if(!cal->IsBadChannel(iAn) && !cal->IsChipBad(ic) && !cal->IsBad() ){ hbase->Fill(base); hchstatus->Fill(1); if(iMod<84) hchstatus3->Fill(1); else hchstatus4->Fill(1); hnoise->Fill(noise); hgain->Fill(gain); } } } printf("Run %d <Base> = %f <Noise> =%f Entries = %d\n",nrun,hbase->GetMean(),hnoise->GetMean(),(Int_t)hbase->GetEntries()); if(selectedMod==-1 && (Int_t)hbase->GetEntries()==0) continue; gbasevstim->SetPoint(iPoint,(Double_t)nrun,hbase->GetMean()); gbasevstim->SetPointError(iPoint,0.,hbase->GetRMS()); gnoisevstim->SetPoint(iPoint,(Double_t)nrun,hnoise->GetMean()); gnoisevstim->SetPointError(iPoint,0.,hnoise->GetRMS()); ggainvstim->SetPoint(iPoint,(Double_t)nrun,hgain->GetMean()); ggainvstim->SetPointError(iPoint,0.,hgain->GetRMS()); gstatvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2)); Float_t normMod=260.; if(selectedMod!=-1) normMod=1.; gfracvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2)/normMod/512.); gfrac3vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus3->GetBinContent(2)/84./512.); gfrac4vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus4->GetBinContent(2)/176./512.); iPoint++; f->Close(); } TFile *ofil=new TFile(Form("Calib%dVsTime.root",year),"recreate"); gbasevstim->Write(); gnoisevstim->Write(); ggainvstim->Write(); gstatvstim->Write(); ofil->Close(); TCanvas* cbase=new TCanvas("cbase","Baselines"); gbasevstim->SetFillColor(kOrange-2); gbasevstim->SetMarkerStyle(20); gbasevstim->Draw("AP3"); gbasevstim->Draw("PLXSAME"); gbasevstim->SetMinimum(0.); gbasevstim->SetMaximum(70.); gbasevstim->GetXaxis()->SetTitle("Run number"); gbasevstim->GetYaxis()->SetTitle("<Baseline> (ADC counts)"); cbase->SaveAs(Form("BaseRun%d.gif",year)); TCanvas* cnoise=new TCanvas("cnoise","Noise"); gnoisevstim->SetFillColor(kOrange-2); gnoisevstim->SetMarkerStyle(20); gnoisevstim->Draw("AP3"); gnoisevstim->Draw("PLXSAME"); gnoisevstim->SetMinimum(0.); gnoisevstim->SetMaximum(4.); gnoisevstim->GetXaxis()->SetTitle("Run number"); gnoisevstim->GetYaxis()->SetTitle("<Noise> (ADC counts)"); cnoise->SaveAs(Form("NoiseRun%d.gif",year)); TCanvas* cgain=new TCanvas("cgain","Gain"); ggainvstim->SetFillColor(kOrange-2); ggainvstim->SetMarkerStyle(20); ggainvstim->Draw("AP3"); ggainvstim->Draw("PLXSAME"); ggainvstim->SetMinimum(0.); ggainvstim->SetMaximum(4.); ggainvstim->GetXaxis()->SetTitle("Run number"); ggainvstim->GetYaxis()->SetTitle("<Gain> (ADC/DAC)"); cgain->SaveAs(Form("GainRun%d.gif",year)); TCanvas* cstatus=new TCanvas("cstatus","Good channels"); gstatvstim->SetFillColor(kOrange-2); gstatvstim->SetMarkerStyle(20); gstatvstim->Draw("AP3"); gstatvstim->Draw("PLXSAME"); if(selectedMod==-1){ gstatvstim->SetMinimum(100000.); gstatvstim->SetMaximum(133000.); }else{ gstatvstim->SetMinimum(0.); gstatvstim->SetMaximum(512.); } gstatvstim->GetXaxis()->SetTitle("Run number"); if(selectedMod==-1){ gstatvstim->GetYaxis()->SetTitle("Number of good anodes in acquisition"); }else{ gstatvstim->GetYaxis()->SetTitle(Form("Number of good anodes in od %d",selectedMod)); } cstatus->SaveAs(Form("GoodAnodesRun%d.gif",year)); TCanvas* cfrac=new TCanvas("cfrac","Fraction of Good"); gfracvstim->SetMarkerStyle(20); gfrac3vstim->SetMarkerStyle(22); gfrac3vstim->SetMarkerColor(2); gfrac3vstim->SetLineColor(2); gfrac4vstim->SetMarkerStyle(23); gfrac4vstim->SetMarkerColor(4); gfrac4vstim->SetLineColor(4); gfracvstim->Draw("APL"); gfracvstim->SetMinimum(0.7); gfracvstim->SetMaximum(1.05); gfracvstim->GetXaxis()->SetTitle("Run number"); if(selectedMod==-1){ gfracvstim->GetYaxis()->SetTitle("Fraction of good anodes in acquisition"); gfrac3vstim->Draw("PLSAME"); gfrac4vstim->Draw("PLSAME"); TLegend* leg=new TLegend(0.2,0.15,0.45,0.35); leg->SetFillColor(0); TLegendEntry* entr=leg->AddEntry(gfrac3vstim,"Layer 3","P"); entr->SetTextColor(2); entr=leg->AddEntry(gfrac4vstim,"Layer 4","P"); entr->SetTextColor(4); entr=leg->AddEntry(gfracvstim,"All","P"); entr->SetTextColor(1); leg->Draw(); }else{ gfracvstim->GetYaxis()->SetTitle(Form("Fraction of good anodes in mod %d",selectedMod)); } cfrac->SaveAs(Form("FractionGoodRun%d.gif",year)); } <|endoftext|>
<commit_before>/* * Author: Jeff Thompson * * BSD license, See the LICENSE file for more information. */ #ifndef BINARYXMLSTRUCTUREDECODER_HPP #define BINARYXMLSTRUCTUREDECODER_HPP #include <stdexcept> #include "../c/encoding/BinaryXMLStructureDecoder.h" namespace ndn { /** * A BinaryXMLStructureDecoder wraps a C ndn_BinaryXMLStructureDecoder struct and related functions. */ class BinaryXMLStructureDecoder { public: BinaryXMLStructureDecoder() { ndn_BinaryXMLStructureDecoder_init(&base_); } /** * Continue scanning input starting from getOffset() to find the element end. * If the end of the element which started at offset 0 is found, then return true and getOffset() is the length of * the element. Otherwise return false, which means you should read more into input and call again. * @param input the input buffer. You have to pass in input each time because the buffer could be reallocated. * @param inputLength the number of bytes in input. * @return true if found the element end, false if need to read more. (This is the same as returning gotElementEnd().) */ bool findElementEnd(unsigned char *input, unsigned int inputLength) { char *error; if (error = ndn_BinaryXMLStructureDecoder_findElementEnd(&base_, input, inputLength)) throw std::runtime_error(error); return gotElementEnd(); } unsigned int getOffset() { return base_._offset; } bool gotElementEnd() { return base_.gotElementEnd != 0; } private: struct ndn_BinaryXMLStructureDecoder base_; }; } #endif /* BINARYXMLSTRUCTUREDECODER_HPP */ <commit_msg>Fix code style.<commit_after>/* * Author: Jeff Thompson * * BSD license, See the LICENSE file for more information. */ #ifndef BINARYXMLSTRUCTUREDECODER_HPP #define BINARYXMLSTRUCTUREDECODER_HPP #include <stdexcept> #include "../c/encoding/BinaryXMLStructureDecoder.h" namespace ndn { /** * A BinaryXMLStructureDecoder wraps a C ndn_BinaryXMLStructureDecoder struct and related functions. */ class BinaryXMLStructureDecoder { public: BinaryXMLStructureDecoder() { ndn_BinaryXMLStructureDecoder_init(&base_); } /** * Continue scanning input starting from getOffset() to find the element end. * If the end of the element which started at offset 0 is found, then return true and getOffset() is the length of * the element. Otherwise return false, which means you should read more into input and call again. * @param input the input buffer. You have to pass in input each time because the buffer could be reallocated. * @param inputLength the number of bytes in input. * @return true if found the element end, false if need to read more. (This is the same as returning gotElementEnd().) */ bool findElementEnd(unsigned char *input, unsigned int inputLength) { char *error; if (error = ndn_BinaryXMLStructureDecoder_findElementEnd(&base_, input, inputLength)) throw std::runtime_error(error); return gotElementEnd(); } unsigned int getOffset() { return base_._offset; } bool gotElementEnd() { return base_.gotElementEnd != 0; } private: struct ndn_BinaryXMLStructureDecoder base_; }; } #endif /* BINARYXMLSTRUCTUREDECODER_HPP */ <|endoftext|>
<commit_before>// Copyright (c) 2022 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "errors.hh" #include "scanner.hh" namespace loxpp { Scanner::Scanner(ErrorReporter& error_repoter, const str_t& source_bytes, const str_t& filename) noexcept : error_repoter_(error_repoter) , source_bytes_(source_bytes) , filename_(filename) { } std::vector<Token>& Scanner::scan_tokens() noexcept { while (!is_at_end()) { // TODO: start_pos_ = current_pos_; scan_token(); } tokens_.push_back(Token::make_from_details(TokenType::TK_EOF, "", lineno_)); return tokens_; } void Scanner::scan_token() noexcept { char c = advance(); switch (c) { case '(': add_token(TokenType::TK_LPAREN); break; case ')': add_token(TokenType::TK_RPAREN); break; case '{': add_token(TokenType::TK_LBRACE); break; case '}': add_token(TokenType::TK_RBRACE); break; case ',': add_token(TokenType::TK_COMMA); break; case '.': add_token(TokenType::TK_DOT); break; case '-': add_token(TokenType::TK_MINUS); break; case '+': add_token(TokenType::TK_PLUS); break; case ';': add_token(TokenType::TK_SEMI); break; case '*': add_token(TokenType::TK_STAR); break; case '!': add_token(match('=') ? TokenType::TK_NE : TokenType::TK_NOT); break; case '=': add_token(match('=') ? TokenType::TK_EQEQ : TokenType::TK_EQ); break; case '<': add_token(match('=') ? TokenType::TK_LE : TokenType::TK_LT); break; case '>': add_token(match('=') ? TokenType::TK_GE : TokenType::TK_GT); break; case '/': if (match('/')) { // a comment goes until the end of the line. while (!is_at_end() && peek() != '\n') advance(); } else { add_token(TokenType::TK_SLASH); } break; default: error_repoter_.error("", lineno_, "Unexpected character."); break; } } } <commit_msg>:construction: chore(scanner): updated the implementation of scanner module<commit_after>// Copyright (c) 2022 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "errors.hh" #include "scanner.hh" namespace loxpp { Scanner::Scanner(ErrorReporter& error_repoter, const str_t& source_bytes, const str_t& filename) noexcept : error_repoter_(error_repoter) , source_bytes_(source_bytes) , filename_(filename) { } std::vector<Token>& Scanner::scan_tokens() noexcept { while (!is_at_end()) { // TODO: start_pos_ = current_pos_; scan_token(); } tokens_.push_back(Token::make_from_details(TokenType::TK_EOF, "", lineno_)); return tokens_; } void Scanner::scan_token() noexcept { char c = advance(); switch (c) { case '(': add_token(TokenType::TK_LPAREN); break; case ')': add_token(TokenType::TK_RPAREN); break; case '{': add_token(TokenType::TK_LBRACE); break; case '}': add_token(TokenType::TK_RBRACE); break; case ',': add_token(TokenType::TK_COMMA); break; case '.': add_token(TokenType::TK_DOT); break; case '-': add_token(TokenType::TK_MINUS); break; case '+': add_token(TokenType::TK_PLUS); break; case ';': add_token(TokenType::TK_SEMI); break; case '*': add_token(TokenType::TK_STAR); break; case '!': add_token(match('=') ? TokenType::TK_NE : TokenType::TK_NOT); break; case '=': add_token(match('=') ? TokenType::TK_EQEQ : TokenType::TK_EQ); break; case '<': add_token(match('=') ? TokenType::TK_LE : TokenType::TK_LT); break; case '>': add_token(match('=') ? TokenType::TK_GE : TokenType::TK_GT); break; case '/': if (match('/')) { // a comment goes until the end of the line. while (!is_at_end() && peek() != '\n') advance(); } else { add_token(TokenType::TK_SLASH); } break; case ' ': case '\r': case '\t': // Ignore whitespace break; case '\n': ++lineno_; break; case '"': string(); break; default: error_repoter_.error("", lineno_, "Unexpected character."); break; } } void Scanner::string() noexcept { while (!is_at_end() && peek() != '"') { if (peek() == '\n') ++lineno_; advance(); } if (is_at_end()) { error_repoter_.error("", lineno_, "Unterminated string."); return; } // The closing ". advance(); str_t literal = gen_literal(start_pos_ + 1, current_pos_ - 1); add_token(TokenType::TK_STRING, literal); } } <|endoftext|>
<commit_before>/** \file add_publication_year_to_serials.cc * \brief Add reasonable publication year to serials provided by an external list * \author Johannes Riedl */ /* Copyright (C) 2016-2018, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Background: Serials (i.e. "Schriftenreihen") do not in general provide a reasonable Sorting date, since the 008 is not properly filled. To circumvent this, we derive the sorting date from the the subordinate works and provide it as an (external) list. Based on this list, we insert the publication year to reasonable fields here */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MARC.h" #include "StringUtil.h" #include "util.h" namespace { typedef std::map<std::string, std::string> SortList; [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " sort_year_list title_data_marc_input title_date_marc_output\n"; std::exit(EXIT_FAILURE); } void SetupPublicationYearMap(File * const sort_year_list, SortList * const sort_year_map) { while (not sort_year_list->eof()) { std::string line(sort_year_list->getline()); std::vector<std::string> ppns_and_sort_year; if (unlikely(StringUtil::SplitThenTrim(line, ":", " ", &ppns_and_sort_year) != 2)) { LOG_WARNING("Invalid line: " + line); continue; } const std::string ppn(ppns_and_sort_year[0]); const std::string sort_year(ppns_and_sort_year[1]); sort_year_map->insert(std::make_pair(ppn, sort_year)); } } static unsigned modified_count(0); void ProcessRecord(MARC::Record * const record, const SortList &sort_year_map) { SortList::const_iterator iter(sort_year_map.find(record->getControlNumber())); if (iter == sort_year_map.cend()) return; std::string sort_year(iter->second); // We insert in 190j // Case 1: If there is no 190 tag yet, insert subfield j and we are done if (not record->hasTag("190")) { record->insertField("190", { { 'j', sort_year } }); ++modified_count; return; } // Case 2: There is a 190 tag MARC::Record::Range range(record->getTagRange("190")); for (auto &field : range) { MARC::Subfields subfields = field.getSubfields(); if (subfields.hasSubfield('j')) LOG_ERROR("We already have a 190j subfield for PPN " + record->getControlNumber()); // If there is no 190j subfield yet, we insert at the last field occurence if (field == *(range.end() - 1)) { subfields.appendSubfield('j', sort_year); ++modified_count; } } } void AddPublicationYearField(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer, const SortList &sort_year_map) { unsigned record_count(0); while (MARC::Record record = marc_reader->read()) { ProcessRecord(&record, sort_year_map); marc_writer->write(record); ++record_count; } std::cout << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } } // unnamed namespace int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string sort_year_list_filename(argv[1]); const std::string marc_input_filename(argv[2]); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) LOG_ERROR("Marc input filename equals marc output filename"); if (unlikely(marc_input_filename == sort_year_list_filename || marc_output_filename == sort_year_list_filename)) LOG_ERROR("Either marc input filename or marc output filename equals the sort list filename"); try { std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename, MARC::FileType::BINARY)); std::unique_ptr<File> sort_year_list(FileUtil::OpenInputFileOrDie(sort_year_list_filename)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename, MARC::FileType::BINARY)); SortList sort_year_map; SetupPublicationYearMap(sort_year_list.get(), &sort_year_map); AddPublicationYearField(marc_reader.get(), marc_writer.get(), sort_year_map); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } } <commit_msg>add_publication_year_to_serials.cc: use range.back()<commit_after>/** \file add_publication_year_to_serials.cc * \brief Add reasonable publication year to serials provided by an external list * \author Johannes Riedl */ /* Copyright (C) 2016-2018, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Background: Serials (i.e. "Schriftenreihen") do not in general provide a reasonable Sorting date, since the 008 is not properly filled. To circumvent this, we derive the sorting date from the the subordinate works and provide it as an (external) list. Based on this list, we insert the publication year to reasonable fields here */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MARC.h" #include "StringUtil.h" #include "util.h" namespace { typedef std::map<std::string, std::string> SortList; [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " sort_year_list title_data_marc_input title_date_marc_output\n"; std::exit(EXIT_FAILURE); } void SetupPublicationYearMap(File * const sort_year_list, SortList * const sort_year_map) { while (not sort_year_list->eof()) { std::string line(sort_year_list->getline()); std::vector<std::string> ppns_and_sort_year; if (unlikely(StringUtil::SplitThenTrim(line, ":", " ", &ppns_and_sort_year) != 2)) { LOG_WARNING("Invalid line: " + line); continue; } const std::string ppn(ppns_and_sort_year[0]); const std::string sort_year(ppns_and_sort_year[1]); sort_year_map->insert(std::make_pair(ppn, sort_year)); } } static unsigned modified_count(0); void ProcessRecord(MARC::Record * const record, const SortList &sort_year_map) { SortList::const_iterator iter(sort_year_map.find(record->getControlNumber())); if (iter == sort_year_map.cend()) return; std::string sort_year(iter->second); // We insert in 190j // Case 1: If there is no 190 tag yet, insert subfield j and we are done if (not record->hasTag("190")) { record->insertField("190", { { 'j', sort_year } }); ++modified_count; return; } // Case 2: There is a 190 tag MARC::Record::Range range(record->getTagRange("190")); for (auto &field : range) { MARC::Subfields subfields = field.getSubfields(); if (subfields.hasSubfield('j')) LOG_ERROR("We already have a 190j subfield for PPN " + record->getControlNumber()); // If there is no 190j subfield yet, we insert at the last field occurence if (field == range.back()) { subfields.appendSubfield('j', sort_year); ++modified_count; } } } void AddPublicationYearField(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer, const SortList &sort_year_map) { unsigned record_count(0); while (MARC::Record record = marc_reader->read()) { ProcessRecord(&record, sort_year_map); marc_writer->write(record); ++record_count; } std::cout << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } } // unnamed namespace int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string sort_year_list_filename(argv[1]); const std::string marc_input_filename(argv[2]); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) LOG_ERROR("Marc input filename equals marc output filename"); if (unlikely(marc_input_filename == sort_year_list_filename || marc_output_filename == sort_year_list_filename)) LOG_ERROR("Either marc input filename or marc output filename equals the sort list filename"); try { std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename, MARC::FileType::BINARY)); std::unique_ptr<File> sort_year_list(FileUtil::OpenInputFileOrDie(sort_year_list_filename)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename, MARC::FileType::BINARY)); SortList sort_year_map; SetupPublicationYearMap(sort_year_list.get(), &sort_year_map); AddPublicationYearField(marc_reader.get(), marc_writer.get(), sort_year_map); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>/** \brief Tool for generating reasonable input for the FulltextImporter if only a PDF fulltext is available * \author Johannes Riedl * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <stdexcept> #include <cstdio> #include <cstdlib> #include <vector> #include "FileUtil.h" #include "FullTextImport.h" #include "HtmlUtil.h" #include "PdfUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" // Try to derive relevant information to guess the PPN // Strategy 1: Try to find an ISBN string // Strategy 2: Extract pages at the beginning and try to identify information at // the bottom of the first page and try to guess author and title namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--min-log-level=min_verbosity] pdf_input full_text_output\n" << ::progname << " [--min-log-level=min_verbosity] --output_dir output_dir pdf_input1 pdf_input2 ...\n\n"; std::exit(EXIT_FAILURE); } std::string GuessLastParagraph(const std::string &first_page_text) { const std::string first_page_text_trimmed(StringUtil::Trim(first_page_text, '\n')); const std::size_t last_paragraph_start(first_page_text_trimmed.rfind("\n\n")); std::string last_paragraph(last_paragraph_start != std::string::npos ? first_page_text_trimmed.substr(last_paragraph_start) : ""); StringUtil::Map(&last_paragraph, '\n', ' '); return TextUtil::NormaliseDashes(&last_paragraph); } bool GuessISSN(const std::string &first_page_text, std::string * const issn) { const std::string last_paragraph(GuessLastParagraph(first_page_text)); static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*ISSN\\s*([\\d\\-X]+).*")); if (matcher->matched(last_paragraph)) { *issn = (*matcher)[1]; return true; } return false; } bool GuessDOI(const std::string &first_page_text, std::string * const doi) { const std::string last_paragraph(GuessLastParagraph(first_page_text)); static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*DOI[\\s:]*([\\d/.X]+).*", RegexMatcher::CASE_INSENSITIVE)); if (matcher->matched(last_paragraph)) { *doi = (*matcher)[1]; return true; } return false; } bool GuessISBN(const std::string &extracted_text, std::string * const isbn) { static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*(?<!e-)ISBN\\s*([\\d\\-X]+).*", RegexMatcher::CASE_INSENSITIVE)); if (matcher->matched(extracted_text)) { *isbn = (*matcher)[1]; return true; } return false; } void GuessAuthorAndTitle(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) { std::string pdfinfo_output; PdfUtil::ExtractPDFInfo(pdf_document, &pdfinfo_output); static RegexMatcher * const authors_matcher(RegexMatcher::RegexMatcherFactoryOrDie("Author:\\s*(.*)", RegexMatcher::CASE_INSENSITIVE)); std::vector<std::string> authors; if (authors_matcher->matched(pdfinfo_output)) { StringUtil::Split((*authors_matcher)[1], std::set<char>{ ';', '|' }, &authors); for (auto &author : authors) author = HtmlUtil::ReplaceEntities(author); std::copy(authors.cbegin(), authors.cend(), std::inserter(fulltext_data->authors_, fulltext_data->authors_.end())); } static RegexMatcher * const title_matcher(RegexMatcher::RegexMatcherFactoryOrDie("^Title:?\\s*(.*)", RegexMatcher::CASE_INSENSITIVE)); if (title_matcher->matched(pdfinfo_output)) { std::string title_candidate((*title_matcher)[1]); // Try to detect invalid encoding if (not TextUtil::IsValidUTF8(title_candidate)) LOG_WARNING("Apparently incorrect encoding for " + title_candidate); // Some cleanup title_candidate = StringUtil::ReplaceString("<ger>", "", title_candidate); title_candidate = StringUtil::ReplaceString("</ger>", "", title_candidate); title_candidate = HtmlUtil::ReplaceEntities(title_candidate); fulltext_data->title_ = title_candidate; } } void ConvertFulltextMetadataFromAssumedLatin1OriginalEncoding(FullTextImport::FullTextData * const fulltext_data) { std::string error_msg; static auto UTF8ToLatin1_converter(TextUtil::EncodingConverter::Factory("utf-8", "ISO-8859-1", &error_msg)); UTF8ToLatin1_converter->convert(fulltext_data->title_, &(fulltext_data->title_)); } bool GuessPDFMetadata(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) { ControlNumberGuesser control_number_guesser; // Try to find an ISBN in the first pages std::string first_pages_text; PdfUtil::ExtractText(pdf_document, &first_pages_text, "1", "10" ); std::string isbn; GuessISBN(TextUtil::NormaliseDashes(&first_pages_text), &isbn); if (not isbn.empty()) { LOG_DEBUG("Extracted ISBN: " + isbn); std::set<std::string> control_numbers; control_number_guesser.lookupISBN(isbn, &control_numbers); if (control_numbers.size() != 1) { LOG_WARNING("We got more than one control number for ISBN \"" + isbn + "\" - falling back to title and author"); GuessAuthorAndTitle(pdf_document, fulltext_data); fulltext_data->isbn_ = isbn; if (unlikely(not FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_numbers))) { LOG_WARNING("Could not correlate full text data for ISBN \"" + isbn + "\""); return false; } if (control_numbers.size() != 1) LOG_WARNING("Unable to determine unique control number for ISBN \"" + isbn + "\": " + StringUtil::Join(control_numbers, ", ")); } const std::string control_number(*(control_numbers.begin())); LOG_DEBUG("Determined control number \"" + control_number + "\" for ISBN \"" + isbn + "\"\n"); return true; } // Guess control number by DOI, author, title and and possibly ISSN std::string first_page_text; PdfUtil::ExtractText(pdf_document, &first_page_text, "1", "1"); // Get only first page std::string control_number; if (GuessDOI(first_page_text, &(fulltext_data->doi_)) and FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_number)) return true; GuessISSN(first_page_text, &(fulltext_data->issn_)); GuessAuthorAndTitle(pdf_document, fulltext_data); if (not FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_number)) // We frequently have the case that author and title extracted we encoded in Latin-1 in some time in the past such that our search fails // so force normalisation and make another attempt. ConvertFulltextMetadataFromAssumedLatin1OriginalEncoding(fulltext_data); return FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_number); } void CreateFulltextImportFile(const std::string &fulltext_pdf, const std::string &fulltext_txt) { std::cout << "Processing \"" << fulltext_pdf << "\"\n"; FullTextImport::FullTextData fulltext_data; std::string pdf_document; if (not FileUtil::ReadString(fulltext_pdf, &pdf_document)) LOG_ERROR("Could not read \"" + fulltext_pdf + "\""); if (PdfUtil::PdfDocContainsNoText(pdf_document)) LOG_ERROR("Apparently no text in \"" + fulltext_pdf + "\""); if (unlikely(not GuessPDFMetadata(pdf_document, &fulltext_data))) LOG_ERROR("Unable to determine metadata for \"" + fulltext_pdf + "\""); if (unlikely(not PdfUtil::ExtractText(pdf_document, &(fulltext_data.full_text_)))) LOG_ERROR("Unable to extract fulltext from \"" + fulltext_pdf + "\""); auto plain_text_output(FileUtil::OpenOutputFileOrDie(fulltext_txt)); FullTextImport::WriteExtractedTextToDisk(fulltext_data.full_text_, fulltext_data.title_, fulltext_data.authors_, fulltext_data.doi_, fulltext_data.year_, fulltext_data.issn_, fulltext_data.isbn_, fulltext_data.text_type_, plain_text_output.get()); } std::string DeriveOutputFilename(const std::string &pdf_filename) { return (StringUtil::ASCIIToLower(FileUtil::GetExtension(pdf_filename)) == "pdf") ? FileUtil::GetFilenameWithoutExtensionOrDie(pdf_filename) + ".txt" : pdf_filename + ".txt"; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 3) Usage(); bool use_output_dir(false); std::string output_dir("."); if (argc > 2 and StringUtil::StartsWith(argv[1], "--output-dir=")) { use_output_dir = true; output_dir = argv[1] + __builtin_strlen("--output-dir="); --argc; ++argv; } if (argc < 2) Usage(); if (not use_output_dir and argc < 3) Usage(); if (not use_output_dir) { const std::string fulltext_pdf(argv[1]); CreateFulltextImportFile(fulltext_pdf, argv[2]); return EXIT_SUCCESS; } for (int arg_no(1); arg_no < argc; ++arg_no) CreateFulltextImportFile(argv[arg_no], output_dir + '/' + DeriveOutputFilename(argv[arg_no])); return EXIT_SUCCESS; } <commit_msg>Fix typo<commit_after>/** \brief Tool for generating reasonable input for the FulltextImporter if only a PDF fulltext is available * \author Johannes Riedl * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <stdexcept> #include <cstdio> #include <cstdlib> #include <vector> #include "FileUtil.h" #include "FullTextImport.h" #include "HtmlUtil.h" #include "PdfUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" // Try to derive relevant information to guess the PPN // Strategy 1: Try to find an ISBN string // Strategy 2: Extract pages at the beginning and try to identify information at // the bottom of the first page and try to guess author and title namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--min-log-level=min_verbosity] pdf_input full_text_output\n" << ::progname << " [--min-log-level=min_verbosity] --output-dir output_dir pdf_input1 pdf_input2 ...\n\n"; std::exit(EXIT_FAILURE); } std::string GuessLastParagraph(const std::string &first_page_text) { const std::string first_page_text_trimmed(StringUtil::Trim(first_page_text, '\n')); const std::size_t last_paragraph_start(first_page_text_trimmed.rfind("\n\n")); std::string last_paragraph(last_paragraph_start != std::string::npos ? first_page_text_trimmed.substr(last_paragraph_start) : ""); StringUtil::Map(&last_paragraph, '\n', ' '); return TextUtil::NormaliseDashes(&last_paragraph); } bool GuessISSN(const std::string &first_page_text, std::string * const issn) { const std::string last_paragraph(GuessLastParagraph(first_page_text)); static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*ISSN\\s*([\\d\\-X]+).*")); if (matcher->matched(last_paragraph)) { *issn = (*matcher)[1]; return true; } return false; } bool GuessDOI(const std::string &first_page_text, std::string * const doi) { const std::string last_paragraph(GuessLastParagraph(first_page_text)); static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*DOI[\\s:]*([\\d/.X]+).*", RegexMatcher::CASE_INSENSITIVE)); if (matcher->matched(last_paragraph)) { *doi = (*matcher)[1]; return true; } return false; } bool GuessISBN(const std::string &extracted_text, std::string * const isbn) { static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactoryOrDie(".*(?<!e-)ISBN\\s*([\\d\\-X]+).*", RegexMatcher::CASE_INSENSITIVE)); if (matcher->matched(extracted_text)) { *isbn = (*matcher)[1]; return true; } return false; } void GuessAuthorAndTitle(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) { std::string pdfinfo_output; PdfUtil::ExtractPDFInfo(pdf_document, &pdfinfo_output); static RegexMatcher * const authors_matcher(RegexMatcher::RegexMatcherFactoryOrDie("Author:\\s*(.*)", RegexMatcher::CASE_INSENSITIVE)); std::vector<std::string> authors; if (authors_matcher->matched(pdfinfo_output)) { StringUtil::Split((*authors_matcher)[1], std::set<char>{ ';', '|' }, &authors); for (auto &author : authors) author = HtmlUtil::ReplaceEntities(author); std::copy(authors.cbegin(), authors.cend(), std::inserter(fulltext_data->authors_, fulltext_data->authors_.end())); } static RegexMatcher * const title_matcher(RegexMatcher::RegexMatcherFactoryOrDie("^Title:?\\s*(.*)", RegexMatcher::CASE_INSENSITIVE)); if (title_matcher->matched(pdfinfo_output)) { std::string title_candidate((*title_matcher)[1]); // Try to detect invalid encoding if (not TextUtil::IsValidUTF8(title_candidate)) LOG_WARNING("Apparently incorrect encoding for " + title_candidate); // Some cleanup title_candidate = StringUtil::ReplaceString("<ger>", "", title_candidate); title_candidate = StringUtil::ReplaceString("</ger>", "", title_candidate); title_candidate = HtmlUtil::ReplaceEntities(title_candidate); fulltext_data->title_ = title_candidate; } } void ConvertFulltextMetadataFromAssumedLatin1OriginalEncoding(FullTextImport::FullTextData * const fulltext_data) { std::string error_msg; static auto UTF8ToLatin1_converter(TextUtil::EncodingConverter::Factory("utf-8", "ISO-8859-1", &error_msg)); UTF8ToLatin1_converter->convert(fulltext_data->title_, &(fulltext_data->title_)); } bool GuessPDFMetadata(const std::string &pdf_document, FullTextImport::FullTextData * const fulltext_data) { ControlNumberGuesser control_number_guesser; // Try to find an ISBN in the first pages std::string first_pages_text; PdfUtil::ExtractText(pdf_document, &first_pages_text, "1", "10" ); std::string isbn; GuessISBN(TextUtil::NormaliseDashes(&first_pages_text), &isbn); if (not isbn.empty()) { LOG_DEBUG("Extracted ISBN: " + isbn); std::set<std::string> control_numbers; control_number_guesser.lookupISBN(isbn, &control_numbers); if (control_numbers.size() != 1) { LOG_WARNING("We got more than one control number for ISBN \"" + isbn + "\" - falling back to title and author"); GuessAuthorAndTitle(pdf_document, fulltext_data); fulltext_data->isbn_ = isbn; if (unlikely(not FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_numbers))) { LOG_WARNING("Could not correlate full text data for ISBN \"" + isbn + "\""); return false; } if (control_numbers.size() != 1) LOG_WARNING("Unable to determine unique control number for ISBN \"" + isbn + "\": " + StringUtil::Join(control_numbers, ", ")); } const std::string control_number(*(control_numbers.begin())); LOG_DEBUG("Determined control number \"" + control_number + "\" for ISBN \"" + isbn + "\"\n"); return true; } // Guess control number by DOI, author, title and and possibly ISSN std::string first_page_text; PdfUtil::ExtractText(pdf_document, &first_page_text, "1", "1"); // Get only first page std::string control_number; if (GuessDOI(first_page_text, &(fulltext_data->doi_)) and FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_number)) return true; GuessISSN(first_page_text, &(fulltext_data->issn_)); GuessAuthorAndTitle(pdf_document, fulltext_data); if (not FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_number)) // We frequently have the case that author and title extracted we encoded in Latin-1 in some time in the past such that our search fails // so force normalisation and make another attempt. ConvertFulltextMetadataFromAssumedLatin1OriginalEncoding(fulltext_data); return FullTextImport::CorrelateFullTextData(control_number_guesser, *(fulltext_data), &control_number); } void CreateFulltextImportFile(const std::string &fulltext_pdf, const std::string &fulltext_txt) { std::cout << "Processing \"" << fulltext_pdf << "\"\n"; FullTextImport::FullTextData fulltext_data; std::string pdf_document; if (not FileUtil::ReadString(fulltext_pdf, &pdf_document)) LOG_ERROR("Could not read \"" + fulltext_pdf + "\""); if (PdfUtil::PdfDocContainsNoText(pdf_document)) LOG_ERROR("Apparently no text in \"" + fulltext_pdf + "\""); if (unlikely(not GuessPDFMetadata(pdf_document, &fulltext_data))) LOG_ERROR("Unable to determine metadata for \"" + fulltext_pdf + "\""); if (unlikely(not PdfUtil::ExtractText(pdf_document, &(fulltext_data.full_text_)))) LOG_ERROR("Unable to extract fulltext from \"" + fulltext_pdf + "\""); auto plain_text_output(FileUtil::OpenOutputFileOrDie(fulltext_txt)); FullTextImport::WriteExtractedTextToDisk(fulltext_data.full_text_, fulltext_data.title_, fulltext_data.authors_, fulltext_data.doi_, fulltext_data.year_, fulltext_data.issn_, fulltext_data.isbn_, fulltext_data.text_type_, plain_text_output.get()); } std::string DeriveOutputFilename(const std::string &pdf_filename) { return (StringUtil::ASCIIToLower(FileUtil::GetExtension(pdf_filename)) == "pdf") ? FileUtil::GetFilenameWithoutExtensionOrDie(pdf_filename) + ".txt" : pdf_filename + ".txt"; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 3) Usage(); bool use_output_dir(false); std::string output_dir("."); if (argc > 2 and StringUtil::StartsWith(argv[1], "--output-dir=")) { use_output_dir = true; output_dir = argv[1] + __builtin_strlen("--output-dir="); --argc; ++argv; } if (argc < 2) Usage(); if (not use_output_dir and argc < 3) Usage(); if (not use_output_dir) { const std::string fulltext_pdf(argv[1]); CreateFulltextImportFile(fulltext_pdf, argv[2]); return EXIT_SUCCESS; } for (int arg_no(1); arg_no < argc; ++arg_no) CreateFulltextImportFile(argv[arg_no], output_dir + '/' + DeriveOutputFilename(argv[arg_no])); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: MeshCellVisitor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // Cells are stored in the \code{itk::Mesh} as pointers to a generic cell. // This implies that only the virtual methods defined on this base cell class // can be invoked. In order to use methods that are specific of each cell type // it is necessary to down-cast the pointer to the actual type of the cell. // This can be done safely by taking advantage of the C++ RTTI mechanism // \footnote{RTTI stands for Run Time Type Information}. // // Let's start by assuming a mesh defined with one tetrahedron and all its // boundary faces. That is, four triangles, six edges and four vertices. // // \index{RTTI} // // Software Guide : EndLatex #include "itkMesh.h" #include "itkVertexCell.h" #include "itkLineCell.h" #include "itkTriangleCell.h" #include "itkTetrahedronCell.h" int main() { typedef float PixelType; typedef itk::Mesh< PixelType, 3 > MeshType; typedef MeshType::CellType CellType; typedef itk::VertexCell< CellType > VertexType; typedef itk::LineCell< CellType > LineType; typedef itk::TriangleCell< CellType > TriangleType; typedef itk::TetrahedronCell< CellType > TetrahedronType; MeshType::Pointer mesh = MeshType::New(); // // Creating the points and inserting them in the mesh // MeshType::PointType point0; MeshType::PointType point1; MeshType::PointType point2; MeshType::PointType point3; point0[0] = -1; point0[1] = -1; point0[2] = -1; point1[0] = 1; point1[1] = 1; point1[2] = -1; point2[0] = 1; point2[1] = -1; point2[2] = 1; point3[0] = -1; point3[1] = 1; point3[2] = 1; mesh->SetPoint( 0, point0 ); mesh->SetPoint( 1, point1 ); mesh->SetPoint( 2, point2 ); mesh->SetPoint( 3, point3 ); // // Creating and associating the Tetrahedron // CellType::CellAutoPointer cellpointer; cellpointer.TakeOwnership( new TetrahedronType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 1 ); cellpointer->SetPointId( 2, 2 ); cellpointer->SetPointId( 3, 3 ); mesh->SetCell( 0, cellpointer ); // // Creating and associating the Triangles // cellpointer.TakeOwnership( new TriangleType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 1 ); cellpointer->SetPointId( 2, 2 ); mesh->SetCell( 1, cellpointer ); cellpointer.TakeOwnership( new TriangleType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 2 ); cellpointer->SetPointId( 2, 3 ); mesh->SetCell( 2, cellpointer ); cellpointer.TakeOwnership( new TriangleType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 3 ); cellpointer->SetPointId( 2, 1 ); mesh->SetCell( 3, cellpointer ); cellpointer.TakeOwnership( new TriangleType ); cellpointer->SetPointId( 0, 3 ); cellpointer->SetPointId( 1, 2 ); cellpointer->SetPointId( 2, 1 ); mesh->SetCell( 4, cellpointer ); // // Creating and associating the Edges // cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 1 ); mesh->SetCell( 5, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 1 ); cellpointer->SetPointId( 1, 2 ); mesh->SetCell( 6, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 2 ); cellpointer->SetPointId( 1, 0 ); mesh->SetCell( 7, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 1 ); cellpointer->SetPointId( 1, 3 ); mesh->SetCell( 8, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 3 ); cellpointer->SetPointId( 1, 2 ); mesh->SetCell( 9, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 3 ); cellpointer->SetPointId( 1, 0 ); mesh->SetCell( 10, cellpointer ); // // Creating and associating the Vertices // cellpointer.TakeOwnership( new VertexType ); cellpointer->SetPointId( 0, 0 ); mesh->SetCell( 11, cellpointer ); cellpointer.TakeOwnership( new VertexType ); cellpointer->SetPointId( 0, 1 ); mesh->SetCell( 12, cellpointer ); cellpointer.TakeOwnership( new VertexType ); cellpointer->SetPointId( 0, 2 ); mesh->SetCell( 13, cellpointer ); cellpointer.TakeOwnership( new VertexType ); cellpointer->SetPointId( 0, 3 ); mesh->SetCell( 14, cellpointer ); std::cout << "# Points= " << mesh->GetNumberOfPoints() << std::endl; std::cout << "# Cell = " << mesh->GetNumberOfCells() << std::endl; // Software Guide : BeginLatex // // The cells can be visited using CellsContainer iterators . The iterator // \code{Value()} corresponds to a raw pointer to the \code{CellType} base // class. // // \index{itk::Mesh!CellsContainer} // \index{itk::Mesh!CellsIterators} // \index{itk::Mesh!GetCells()} // \index{CellsContainer!Begin()} // \index{CellsContainer!End()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef MeshType::CellsContainer::ConstIterator CellIterator; CellIterator cellIterator = mesh->GetCells()->Begin(); CellIterator cellEnd = mesh->GetCells()->End(); while( cellIterator != cellEnd ) { CellType * cell = cellIterator.Value(); std::cout << cell->GetNumberOfPoints() << std::endl; ++cellIterator; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Two mechanisms can be used to safely down-cast the pointer to the actual // cell type. The first is a built-in mechanism in ITK that allows the user // to query the type of the Cell. Codes for the cell types have been defined // with an \code{enum} type on the \code{itkCellInterface.h} header file. // These codes are : VERTEX\_CELL, LINE\_CELL, TRIANGLE\_CELL, // QUADRILATERAL\_CELL, POLYGON\_CELL, TETRAHEDRON\_CELL, HEXAHEDRON\_CELL, // QUADRATIC\_EDGE\_CELL, QUADRATIC\_TRIANGLE\_CELL. The Cell type is returned // by the method \code{GetType()}. It is then possible to test the type of // the cell before down-casting its pointer to the actual type. For example, // the following code visits all the cells in the mesh and test which ones // are actually of type LINE\_CELL. Only those cells are down-casted to // LineType cells and a method specific for the LineType are invoked. // // Software Guide : EndLatex std::cout << "Visiting the Line cells : " << std::endl; // Software Guide : BeginCodeSnippet cellIterator = mesh->GetCells()->Begin(); cellEnd = mesh->GetCells()->End(); while( cellIterator != cellEnd ) { CellType * cell = cellIterator.Value(); if( cell->GetType() == CellType::LINE_CELL ) { LineType * line = static_cast<LineType *>( cell ); std::cout << "dimension = " << line->GetDimension() << std::endl; std::cout << "# points = " << line->GetNumberOfPoints() << std::endl; } ++cellIterator; } // Software Guide : EndCodeSnippet return 0; } <commit_msg>ENH: CellInterfaceVisitor introduced. The text needs to be reworked now.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: MeshCellVisitor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // Cells are stored in the \code{itk::Mesh} as pointers to a generic cell. // This implies that only the virtual methods defined on this base cell class // can be invoked. In order to use methods that are specific of each cell type // it is necessary to down-cast the pointer to the actual type of the cell. // This can be done safely by taking advantage of the C++ RTTI mechanism // \footnote{RTTI stands for Run Time Type Information}. // // Let's start by assuming a mesh defined with one tetrahedron and all its // boundary faces. That is, four triangles, six edges and four vertices. // // \index{RTTI} // // Software Guide : EndLatex #include "itkMesh.h" #include "itkVertexCell.h" #include "itkLineCell.h" #include "itkTriangleCell.h" #include "itkTetrahedronCell.h" // Software Guide : BeginCodeSnippet #include "itkCellInterfaceVisitor.h" // Software Guide : EndCodeSnippet typedef float PixelType; typedef itk::Mesh< PixelType, 3 > MeshType; typedef MeshType::CellType CellType; typedef itk::VertexCell< CellType > VertexType; typedef itk::LineCell< CellType > LineType; typedef itk::TriangleCell< CellType > TriangleType; typedef itk::TetrahedronCell< CellType > TetrahedronType; // Software Guide : BeginCodeSnippet class CustomTriangleVisitor { public: typedef itk::TriangleCell<CellType> TriangleType; public: void Visit(unsigned long cellId, TriangleType * t ) { CellType::PointIdIterator pit = t->PointIdsBegin(); CellType::PointIdIterator end = t->PointIdsEnd(); std::cout << t->GetNumberOfPoints() << " points = "; while( pit != end ) { std::cout << *pit << " "; ++pit; } std::cout << std::endl; } }; // Software Guide : EndCodeSnippet int main() { MeshType::Pointer mesh = MeshType::New(); // // Creating the points and inserting them in the mesh // MeshType::PointType point0; MeshType::PointType point1; MeshType::PointType point2; MeshType::PointType point3; point0[0] = -1; point0[1] = -1; point0[2] = -1; point1[0] = 1; point1[1] = 1; point1[2] = -1; point2[0] = 1; point2[1] = -1; point2[2] = 1; point3[0] = -1; point3[1] = 1; point3[2] = 1; mesh->SetPoint( 0, point0 ); mesh->SetPoint( 1, point1 ); mesh->SetPoint( 2, point2 ); mesh->SetPoint( 3, point3 ); // // Creating and associating the Tetrahedron // CellType::CellAutoPointer cellpointer; cellpointer.TakeOwnership( new TetrahedronType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 1 ); cellpointer->SetPointId( 2, 2 ); cellpointer->SetPointId( 3, 3 ); mesh->SetCell( 0, cellpointer ); // // Creating and associating the Triangles // cellpointer.TakeOwnership( new TriangleType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 1 ); cellpointer->SetPointId( 2, 2 ); mesh->SetCell( 1, cellpointer ); cellpointer.TakeOwnership( new TriangleType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 2 ); cellpointer->SetPointId( 2, 3 ); mesh->SetCell( 2, cellpointer ); cellpointer.TakeOwnership( new TriangleType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 3 ); cellpointer->SetPointId( 2, 1 ); mesh->SetCell( 3, cellpointer ); cellpointer.TakeOwnership( new TriangleType ); cellpointer->SetPointId( 0, 3 ); cellpointer->SetPointId( 1, 2 ); cellpointer->SetPointId( 2, 1 ); mesh->SetCell( 4, cellpointer ); // // Creating and associating the Edges // cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 0 ); cellpointer->SetPointId( 1, 1 ); mesh->SetCell( 5, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 1 ); cellpointer->SetPointId( 1, 2 ); mesh->SetCell( 6, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 2 ); cellpointer->SetPointId( 1, 0 ); mesh->SetCell( 7, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 1 ); cellpointer->SetPointId( 1, 3 ); mesh->SetCell( 8, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 3 ); cellpointer->SetPointId( 1, 2 ); mesh->SetCell( 9, cellpointer ); cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 3 ); cellpointer->SetPointId( 1, 0 ); mesh->SetCell( 10, cellpointer ); // // Creating and associating the Vertices // cellpointer.TakeOwnership( new VertexType ); cellpointer->SetPointId( 0, 0 ); mesh->SetCell( 11, cellpointer ); cellpointer.TakeOwnership( new VertexType ); cellpointer->SetPointId( 0, 1 ); mesh->SetCell( 12, cellpointer ); cellpointer.TakeOwnership( new VertexType ); cellpointer->SetPointId( 0, 2 ); mesh->SetCell( 13, cellpointer ); cellpointer.TakeOwnership( new VertexType ); cellpointer->SetPointId( 0, 3 ); mesh->SetCell( 14, cellpointer ); std::cout << "# Points= " << mesh->GetNumberOfPoints() << std::endl; std::cout << "# Cell = " << mesh->GetNumberOfCells() << std::endl; // Software Guide : BeginLatex // // The cells can be visited using CellsContainer iterators . The iterator // \code{Value()} corresponds to a raw pointer to the \code{CellType} base // class. // // \index{itk::Mesh!CellsContainer} // \index{itk::Mesh!CellsIterators} // \index{itk::Mesh!GetCells()} // \index{CellsContainer!Begin()} // \index{CellsContainer!End()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef MeshType::CellsContainer::ConstIterator CellIterator; CellIterator cellIterator = mesh->GetCells()->Begin(); CellIterator cellEnd = mesh->GetCells()->End(); while( cellIterator != cellEnd ) { CellType * cell = cellIterator.Value(); std::cout << cell->GetNumberOfPoints() << std::endl; ++cellIterator; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Two mechanisms can be used to safely down-cast the pointer to the actual // cell type. The first is a built-in mechanism in ITK that allows the user // to query the type of the Cell. Codes for the cell types have been defined // with an \code{enum} type on the \code{itkCellInterface.h} header file. // These codes are : VERTEX\_CELL, LINE\_CELL, TRIANGLE\_CELL, // QUADRILATERAL\_CELL, POLYGON\_CELL, TETRAHEDRON\_CELL, HEXAHEDRON\_CELL, // QUADRATIC\_EDGE\_CELL, QUADRATIC\_TRIANGLE\_CELL. The Cell type is returned // by the method \code{GetType()}. It is then possible to test the type of // the cell before down-casting its pointer to the actual type. For example, // the following code visits all the cells in the mesh and test which ones // are actually of type LINE\_CELL. Only those cells are down-casted to // LineType cells and a method specific for the LineType are invoked. // // Software Guide : EndLatex std::cout << "Visiting the Line cells : " << std::endl; // Software Guide : BeginCodeSnippet cellIterator = mesh->GetCells()->Begin(); cellEnd = mesh->GetCells()->End(); while( cellIterator != cellEnd ) { CellType * cell = cellIterator.Value(); if( cell->GetType() == CellType::LINE_CELL ) { LineType * line = static_cast<LineType *>( cell ); std::cout << "dimension = " << line->GetDimension() << std::endl; std::cout << "# points = " << line->GetNumberOfPoints() << std::endl; } ++cellIterator; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // A more convinient approach for visiting the cells in the mesh is provided // by the implementation of the \emph{Visitor Pattern} discussed in // \cite{Gamma1995}. The visitor pattern is designed to facilitate to walk // through an heterogeneous list of object sharing a common base class. A // visitor class is defined and passed to the Mesh.The mesh will iterate // through its cells and attempt to pass every cell to the visitor. The // visitor class is capable of recognizing the cells of its interest and // operation only on them. // // \index{itk::Mesh!CellInterfaceVisitorImplementation} // \index{itk::Mesh!CellInterfaceVisitor} // \index{itk::Mesh!CellVisitor} // \index{CellVisitor} // // The following code illustrates how to define a cell visitor. In this // particular example we create a class \code{CustomTriangleVisitor} which // will be invoked each time a triangle cell is found while the mesh // iterates over the cells. // // Software Guide : EndLatex typedef CustomTriangleVisitor CustomVisitorType; // Software Guide : BeginCodeSnippet typedef itk::CellInterfaceVisitorImplementation< PixelType, MeshType::CellTraits, TriangleType, CustomVisitorType > TriangleVisitorInterfaceType; // Software Guide : EndCodeSnippet // Software Guide : BeginCodeSnippet TriangleVisitorInterfaceType::Pointer triangleVisitor = TriangleVisitorInterfaceType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // A multivisitor class must be instantiated // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef CellType::MultiVisitor CellMultiVisitorType; CellMultiVisitorType::Pointer multiVisitor = CellMultiVisitorType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The visitor is registered with the Mesh using the \code{AddVisitor()} // method. // // \index{itk::Mesh!AddVisitor()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet multiVisitor->AddVisitor( triangleVisitor ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The iteration over the cells is triggered by calling the method // \code{Accept()} on the \code{itk::Mesh}. // // \index{itk::Mesh!Accept()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet mesh->Accept( multiVisitor ); // Software Guide : EndCodeSnippet return 0; } <|endoftext|>
<commit_before>// // Created by necator on 8/4/17. // #include <iostream> #include "chat_channel.h" #include "easylogging++.h" #include "chat_user.h" #include "chat_server.h" chat_channel::chat_channel(chat_server &server, chat_user_manager &manager, const std::string &name) : server_(server), manager_(manager), name_(name) { LOG(INFO) << "channel: " << name_ << " is created."; } void chat_channel::publish(const message &msg) { LOG(INFO) << "publish: " + msg.debug_string(); for (auto u : users_) u->write(msg); } std::string chat_channel::name() const { return name_; } std::vector<std::string> chat_channel::user_names() const { std::vector<std::string> ret; std::transform(users_.begin(), users_.end(), std::back_inserter(ret), [](const chat_user_ptr u) { return u->name(); }); return ret; } void chat_channel::join(chat_user_ptr c) { LOG(INFO) << "user: " << c->name() << " joined: " << name_; users_.insert(c); } void chat_channel::leave(chat_user_ptr c) { LOG(INFO) << "user: " << c->name() << " left: " << name_; users_.erase(c); if (users_.empty()) { server_.remove_channel(name_); } } void chat_channel::leave_all() { if(!users_.empty()) { LOG(INFO) << name_ << " all users are forced to leave."; users_.clear(); server_.remove_channel(name_); } } <commit_msg>added chan id to debug msg<commit_after>// // Created by necator on 8/4/17. // #include <iostream> #include "chat_channel.h" #include "easylogging++.h" #include "chat_user.h" #include "chat_server.h" chat_channel::chat_channel(chat_server &server, chat_user_manager &manager, const std::string &name) : server_(server), manager_(manager), name_(name) { LOG(INFO) << "channel: " << name_ << " is created."; } void chat_channel::publish(const message &msg) { LOG(INFO) << "channel: " << name_ << "publish: " << msg; for (auto u : users_) u->write(msg); } std::string chat_channel::name() const { return name_; } std::vector<std::string> chat_channel::user_names() const { std::vector<std::string> ret; std::transform(users_.begin(), users_.end(), std::back_inserter(ret), [](const chat_user_ptr u) { return u->name(); }); return ret; } void chat_channel::join(chat_user_ptr c) { LOG(INFO) << "user: " << c->name() << " joined: " << name_; users_.insert(c); } void chat_channel::leave(chat_user_ptr c) { LOG(INFO) << "user: " << c->name() << " left: " << name_; users_.erase(c); if (users_.empty()) { server_.remove_channel(name_); } } void chat_channel::leave_all() { if(!users_.empty()) { LOG(INFO) << name_ << " all users are forced to leave."; users_.clear(); server_.remove_channel(name_); } } <|endoftext|>
<commit_before>/******************************************************************** * AUTHORS: Trevor Hansen, Vijay Ganesh * * BEGIN DATE: July, 2009 * * LICENSE: Please view LICENSE file in the home dir of this Program ********************************************************************/ // -*- c++ -*- #include "printers.h" #include <cassert> #include <cctype> // Outputs in the SMTLIB format. If you want something that can be parsed by other tools call // SMTLIB_PrintBack(). SMTLIB_Print() prints just an expression. // Wierdly is seems that only terms, not formulas can be LETized. namespace printer { using std::string; using namespace BEEV; string functionToSMTLIBName(const BEEV::Kind k); void SMTLIB_Print1(ostream& os, const BEEV::ASTNode n, int indentation, bool letize); void printVarDeclsToStream(ASTNodeSet& symbols, ostream& os); static string tolower(const char * name) { string s(name); for (size_t i = 0; i < s.size(); ++i) s[i] = ::tolower(s[i]); return s; } //Map from ASTNodes to LetVars ASTNodeMap NodeLetVarMap; //This is a vector which stores the Node to LetVars pairs. It //allows for sorted printing, as opposed to NodeLetVarMap std::vector<pair<ASTNode, ASTNode> > NodeLetVarVec; //a partial Map from ASTNodes to LetVars. Needed in order to //correctly print shared subterms inside the LET itself ASTNodeMap NodeLetVarMap1; // Initial version intended to print the whole thing back. void SMTLIB_PrintBack(ostream &os, const ASTNode& n) { os << "(" << endl; os << "benchmark blah" << endl; os << ":logic QF_AUFBV" << endl; ASTNodeSet visited, symbols; buildListOfSymbols(n, visited, symbols); printVarDeclsToStream(symbols, os); os << ":formula "; SMTLIB_Print(os, n, 0); os << ")" << endl; } void printVarDeclsToStream(ASTNodeSet& symbols, ostream& os) { for (ASTNodeSet::const_iterator i = symbols.begin(), iend = symbols.end(); i != iend; i++) { const BEEV::ASTNode& a = *i; // Should be a symbol. assert(a.GetKind()== SYMBOL); switch (a.GetType()) { case BEEV::BITVECTOR_TYPE: os << ":extrafuns (( "; a.nodeprint(os); os << " BitVec[" << a.GetValueWidth() << "]"; os << " ))" << endl; break; case BEEV::ARRAY_TYPE: os << ":extrafuns (( "; a.nodeprint(os); os << " Array[" << a.GetIndexWidth(); os << ":" << a.GetValueWidth() << "] ))" << endl; break; case BEEV::BOOLEAN_TYPE: os << ":extrapreds (( "; a.nodeprint(os); os << "))" << endl; break; default: BEEV::FatalError("printVarDeclsToStream: Unsupported type",a); break; } } } //printVarDeclsToStream void outputBitVec(const ASTNode n, ostream& os) { const Kind k = n.GetKind(); const ASTVec &c = n.GetChildren(); ASTNode op; if (BITVECTOR == k) { op = c[0]; } else if (BVCONST == k) { op = n; } else FatalError("nsadfsdaf"); // CONSTANTBV::BitVector_to_Dec returns a signed representation by default. // Prepend with zero to convert to unsigned. os << "bv"; CBV unsign = CONSTANTBV::BitVector_Concat( n.GetSTPMgr()->CreateZeroConst(1).GetBVConst(), op.GetBVConst()); unsigned char * str = CONSTANTBV::BitVector_to_Dec(unsign); CONSTANTBV::BitVector_Destroy(unsign); os << str << "[" << op.GetValueWidth() << "]"; CONSTANTBV::BitVector_Dispose(str); } void SMTLIB_Print1(ostream& os, const ASTNode n, int indentation, bool letize) { //os << spaces(indentation); //os << endl << spaces(indentation); if (!n.IsDefined()) { os << "<undefined>"; return; } //if this node is present in the letvar Map, then print the letvar //this is to print letvars for shared subterms inside the printing //of "(LET v0 = term1, v1=term1@term2,... if ((NodeLetVarMap1.find(n) != NodeLetVarMap1.end()) && !letize) { SMTLIB_Print1(os, (NodeLetVarMap1[n]), indentation, letize); return; } //this is to print letvars for shared subterms inside the actual //term to be printed if ((NodeLetVarMap.find(n) != NodeLetVarMap.end()) && letize) { SMTLIB_Print1(os, (NodeLetVarMap[n]), indentation, letize); return; } //otherwise print it normally const Kind kind = n.GetKind(); const ASTVec &c = n.GetChildren(); switch (kind) { case BITVECTOR: case BVCONST: outputBitVec(n, os); break; case SYMBOL: n.nodeprint(os); break; case FALSE: os << "false"; break; case NAND: // No NAND in smtlib format. assert(c.size() ==2); os << "(" << "not "; os << "(" << "and "; SMTLIB_Print1(os, c[0], 0, letize); os << " " ; SMTLIB_Print1(os, c[1], 0, letize); os << "))"; break; case TRUE: os << "true"; break; case BVSX: case BVZX: { unsigned int amount = GetUnsignedConst(c[1]); if (BVZX == kind) os << "(zero_extend["; else os << "(sign_extend["; os << (amount - c[0].GetValueWidth()) << "]"; SMTLIB_Print1(os, c[0], indentation, letize); os << ")"; } break; case BVEXTRACT: { unsigned int upper = GetUnsignedConst(c[1]); unsigned int lower = GetUnsignedConst(c[2]); assert(upper >= lower); os << "(extract[" << upper << ":" << lower << "] "; SMTLIB_Print1(os, c[0], indentation, letize); os << ")"; } break; default: { // SMT-LIB only allows arithmetic functions to have two parameters. if (BVPLUS == kind && n.Degree() > 2) { string close = ""; for (int i =0; i < c.size()-1; i++) { os << "(" << functionToSMTLIBName(kind); os << " "; SMTLIB_Print1(os, c[i], 0, letize); os << " "; close += ")"; } SMTLIB_Print1(os, c[c.size()-1], 0, letize); os << close; } else { os << "(" << functionToSMTLIBName(kind); ASTVec::const_iterator iend = c.end(); for (ASTVec::const_iterator i = c.begin(); i != iend; i++) { os << " "; SMTLIB_Print1(os, *i, 0, letize); } os << ")"; } } } } void LetizeNode(const ASTNode& n, ASTNodeSet& PLPrintNodeSet) { const Kind kind = n.GetKind(); if (kind == SYMBOL || kind == BVCONST || kind == FALSE || kind == TRUE) return; const ASTVec &c = n.GetChildren(); for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend; it++) { const ASTNode& ccc = *it; const Kind k = ccc.GetKind(); if (k == SYMBOL || k == BVCONST || k == FALSE || k == TRUE) continue; if (PLPrintNodeSet.find(ccc) == PLPrintNodeSet.end()) { //If branch: if *it is not in NodeSet then, // //1. add it to NodeSet // //2. Letize its childNodes PLPrintNodeSet.insert(ccc); LetizeNode(ccc, PLPrintNodeSet); } else { //0. Else branch: Node has been seen before // //1. Check if the node has a corresponding letvar in the //1. NodeLetVarMap. // //2. if no, then create a new var and add it to the //2. NodeLetVarMap if (ccc.GetType() == BITVECTOR_TYPE && NodeLetVarMap.find(ccc) == NodeLetVarMap.end()) { //Create a new symbol. Get some name. if it conflicts with a //declared name, too bad. int sz = NodeLetVarMap.size(); ostringstream oss; oss << "?let_k_" << sz; ASTNode CurrentSymbol = n.GetSTPMgr()->CreateSymbol( oss.str().c_str()); CurrentSymbol.SetValueWidth(n.GetValueWidth()); CurrentSymbol.SetIndexWidth(n.GetIndexWidth()); /* If for some reason the variable being created here is * already declared by the user then the printed output will * not be a legal input to the system. too bad. I refuse to * check for this. [Vijay is the author of this comment.] */ NodeLetVarMap[ccc] = CurrentSymbol; std::pair<ASTNode, ASTNode> node_letvar_pair(CurrentSymbol, ccc); NodeLetVarVec.push_back(node_letvar_pair); } } } } //end of LetizeNode() // copied from Presentation Langauge printer. ostream& SMTLIB_Print(ostream &os, const ASTNode n, const int indentation) { // Clear the maps NodeLetVarMap.clear(); NodeLetVarVec.clear(); NodeLetVarMap1.clear(); //pass 1: letize the node { ASTNodeSet PLPrintNodeSet; LetizeNode(n, PLPrintNodeSet); } //pass 2: // //2. print all the let variables and their counterpart expressions //2. as follows (LET var1 = expr1, var2 = expr2, ... // //3. Then print the Node itself, replacing every occurence of //3. expr1 with var1, expr2 with var2, ... //os << "("; if (0 < NodeLetVarMap.size()) { std::vector<pair<ASTNode, ASTNode> >::iterator it = NodeLetVarVec.begin(); const std::vector<pair<ASTNode, ASTNode> >::iterator itend = NodeLetVarVec.end(); os << "(let ("; //print the let var first SMTLIB_Print1(os, it->first, indentation, false); os << " "; //print the expr SMTLIB_Print1(os, it->second, indentation, false); os << " )"; //update the second map for proper printing of LET NodeLetVarMap1[it->second] = it->first; string closing = ""; for (it++; it != itend; it++) { os << " " << endl; os << "(let ("; //print the let var first SMTLIB_Print1(os, it->first, indentation, false); os << " "; //print the expr SMTLIB_Print1(os, it->second, indentation, false); os << ")"; //update the second map for proper printing of LET NodeLetVarMap1[it->second] = it->first; closing += ")"; } os << " ( " << endl; SMTLIB_Print1(os, n, indentation, true); os << closing; os << " ) ) "; } else SMTLIB_Print1(os, n, indentation, false); os << endl; return os; } string functionToSMTLIBName(const Kind k) { switch (k) { case AND: case BVAND: case BVNAND: case BVNOR: case BVOR: case BVSGE: case BVSGT: case BVSLE: case BVSLT: case BVSUB: case BVXOR: case ITE: case NAND: case NOR: case NOT: case OR: case XOR: case IFF: case IMPLIES: { return tolower(_kind_names[k]); } case BVCONCAT: return "concat"; case BVDIV: return "bvudiv"; case BVGT: return "bvugt"; case BVGE: return "bvuge"; case BVLE: return "bvule"; case BVLEFTSHIFT: return "bvshl"; case BVLT: return "bvult"; case BVMOD: return "bvurem"; case BVMULT: return "bvmul"; case BVNEG: return "bvnot"; // CONFUSSSSINNG. (1/2) case BVPLUS: return "bvadd"; case BVRIGHTSHIFT: return "bvlshr"; // logical case BVSRSHIFT: return "bvashr"; // arithmetic. case BVUMINUS: return "bvneg"; // CONFUSSSSINNG. (2/2) case EQ: return "="; case READ: return "select"; case WRITE: return "store"; case SBVDIV: return "bvsdiv"; case SBVREM: return "bvsrem"; default: { cerr << "Unknown name when outputting:"; FatalError(_kind_names[k]); return ""; // to quieten compiler/ } } } } <commit_msg>When outputting to SMTLIB format handle properly some cases when the number of arguments > 2.<commit_after>/******************************************************************** * AUTHORS: Trevor Hansen, Vijay Ganesh * * BEGIN DATE: July, 2009 * * LICENSE: Please view LICENSE file in the home dir of this Program ********************************************************************/ // -*- c++ -*- #include "printers.h" #include <cassert> #include <cctype> // Outputs in the SMTLIB format. If you want something that can be parsed by other tools call // SMTLIB_PrintBack(). SMTLIB_Print() prints just an expression. // Wierdly is seems that only terms, not formulas can be LETized. namespace printer { using std::string; using namespace BEEV; string functionToSMTLIBName(const BEEV::Kind k); void SMTLIB_Print1(ostream& os, const BEEV::ASTNode n, int indentation, bool letize); void printVarDeclsToStream(ASTNodeSet& symbols, ostream& os); static string tolower(const char * name) { string s(name); for (size_t i = 0; i < s.size(); ++i) s[i] = ::tolower(s[i]); return s; } //Map from ASTNodes to LetVars ASTNodeMap NodeLetVarMap; //This is a vector which stores the Node to LetVars pairs. It //allows for sorted printing, as opposed to NodeLetVarMap std::vector<pair<ASTNode, ASTNode> > NodeLetVarVec; //a partial Map from ASTNodes to LetVars. Needed in order to //correctly print shared subterms inside the LET itself ASTNodeMap NodeLetVarMap1; // Initial version intended to print the whole thing back. void SMTLIB_PrintBack(ostream &os, const ASTNode& n) { os << "(" << endl; os << "benchmark blah" << endl; os << ":logic QF_AUFBV" << endl; ASTNodeSet visited, symbols; buildListOfSymbols(n, visited, symbols); printVarDeclsToStream(symbols, os); os << ":formula "; SMTLIB_Print(os, n, 0); os << ")" << endl; } void printVarDeclsToStream(ASTNodeSet& symbols, ostream& os) { for (ASTNodeSet::const_iterator i = symbols.begin(), iend = symbols.end(); i != iend; i++) { const BEEV::ASTNode& a = *i; // Should be a symbol. assert(a.GetKind()== SYMBOL); switch (a.GetType()) { case BEEV::BITVECTOR_TYPE: os << ":extrafuns (( "; a.nodeprint(os); os << " BitVec[" << a.GetValueWidth() << "]"; os << " ))" << endl; break; case BEEV::ARRAY_TYPE: os << ":extrafuns (( "; a.nodeprint(os); os << " Array[" << a.GetIndexWidth(); os << ":" << a.GetValueWidth() << "] ))" << endl; break; case BEEV::BOOLEAN_TYPE: os << ":extrapreds (( "; a.nodeprint(os); os << "))" << endl; break; default: BEEV::FatalError("printVarDeclsToStream: Unsupported type",a); break; } } } //printVarDeclsToStream void outputBitVec(const ASTNode n, ostream& os) { const Kind k = n.GetKind(); const ASTVec &c = n.GetChildren(); ASTNode op; if (BITVECTOR == k) { op = c[0]; } else if (BVCONST == k) { op = n; } else FatalError("nsadfsdaf"); // CONSTANTBV::BitVector_to_Dec returns a signed representation by default. // Prepend with zero to convert to unsigned. os << "bv"; CBV unsign = CONSTANTBV::BitVector_Concat( n.GetSTPMgr()->CreateZeroConst(1).GetBVConst(), op.GetBVConst()); unsigned char * str = CONSTANTBV::BitVector_to_Dec(unsign); CONSTANTBV::BitVector_Destroy(unsign); os << str << "[" << op.GetValueWidth() << "]"; CONSTANTBV::BitVector_Dispose(str); } void SMTLIB_Print1(ostream& os, const ASTNode n, int indentation, bool letize) { //os << spaces(indentation); //os << endl << spaces(indentation); if (!n.IsDefined()) { os << "<undefined>"; return; } //if this node is present in the letvar Map, then print the letvar //this is to print letvars for shared subterms inside the printing //of "(LET v0 = term1, v1=term1@term2,... if ((NodeLetVarMap1.find(n) != NodeLetVarMap1.end()) && !letize) { SMTLIB_Print1(os, (NodeLetVarMap1[n]), indentation, letize); return; } //this is to print letvars for shared subterms inside the actual //term to be printed if ((NodeLetVarMap.find(n) != NodeLetVarMap.end()) && letize) { SMTLIB_Print1(os, (NodeLetVarMap[n]), indentation, letize); return; } //otherwise print it normally const Kind kind = n.GetKind(); const ASTVec &c = n.GetChildren(); switch (kind) { case BITVECTOR: case BVCONST: outputBitVec(n, os); break; case SYMBOL: n.nodeprint(os); break; case FALSE: os << "false"; break; case NAND: // No NAND, NOR in smtlib format. case NOR: assert(c.size() ==2); os << "(" << "not "; if (NAND == kind ) os << "(" << "and "; else os << "(" << "or "; SMTLIB_Print1(os, c[0], 0, letize); os << " " ; SMTLIB_Print1(os, c[1], 0, letize); os << "))"; break; case TRUE: os << "true"; break; case BVSX: case BVZX: { unsigned int amount = GetUnsignedConst(c[1]); if (BVZX == kind) os << "(zero_extend["; else os << "(sign_extend["; os << (amount - c[0].GetValueWidth()) << "]"; SMTLIB_Print1(os, c[0], indentation, letize); os << ")"; } break; case BVEXTRACT: { unsigned int upper = GetUnsignedConst(c[1]); unsigned int lower = GetUnsignedConst(c[2]); assert(upper >= lower); os << "(extract[" << upper << ":" << lower << "] "; SMTLIB_Print1(os, c[0], indentation, letize); os << ")"; } break; default: { // SMT-LIB only allows these functions to have two parameters. if ((BVPLUS == kind || kind == BVOR || kind == BVAND) && n.Degree() > 2) { string close = ""; for (int i =0; i < c.size()-1; i++) { os << "(" << functionToSMTLIBName(kind); os << " "; SMTLIB_Print1(os, c[i], 0, letize); os << " "; close += ")"; } SMTLIB_Print1(os, c[c.size()-1], 0, letize); os << close; } else { os << "(" << functionToSMTLIBName(kind); ASTVec::const_iterator iend = c.end(); for (ASTVec::const_iterator i = c.begin(); i != iend; i++) { os << " "; SMTLIB_Print1(os, *i, 0, letize); } os << ")"; } } } } void LetizeNode(const ASTNode& n, ASTNodeSet& PLPrintNodeSet) { const Kind kind = n.GetKind(); if (kind == SYMBOL || kind == BVCONST || kind == FALSE || kind == TRUE) return; const ASTVec &c = n.GetChildren(); for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend; it++) { const ASTNode& ccc = *it; const Kind k = ccc.GetKind(); if (k == SYMBOL || k == BVCONST || k == FALSE || k == TRUE) continue; if (PLPrintNodeSet.find(ccc) == PLPrintNodeSet.end()) { //If branch: if *it is not in NodeSet then, // //1. add it to NodeSet // //2. Letize its childNodes PLPrintNodeSet.insert(ccc); LetizeNode(ccc, PLPrintNodeSet); } else { //0. Else branch: Node has been seen before // //1. Check if the node has a corresponding letvar in the //1. NodeLetVarMap. // //2. if no, then create a new var and add it to the //2. NodeLetVarMap if (ccc.GetType() == BITVECTOR_TYPE && NodeLetVarMap.find(ccc) == NodeLetVarMap.end()) { //Create a new symbol. Get some name. if it conflicts with a //declared name, too bad. int sz = NodeLetVarMap.size(); ostringstream oss; oss << "?let_k_" << sz; ASTNode CurrentSymbol = n.GetSTPMgr()->CreateSymbol( oss.str().c_str()); CurrentSymbol.SetValueWidth(n.GetValueWidth()); CurrentSymbol.SetIndexWidth(n.GetIndexWidth()); /* If for some reason the variable being created here is * already declared by the user then the printed output will * not be a legal input to the system. too bad. I refuse to * check for this. [Vijay is the author of this comment.] */ NodeLetVarMap[ccc] = CurrentSymbol; std::pair<ASTNode, ASTNode> node_letvar_pair(CurrentSymbol, ccc); NodeLetVarVec.push_back(node_letvar_pair); } } } } //end of LetizeNode() // copied from Presentation Langauge printer. ostream& SMTLIB_Print(ostream &os, const ASTNode n, const int indentation) { // Clear the maps NodeLetVarMap.clear(); NodeLetVarVec.clear(); NodeLetVarMap1.clear(); //pass 1: letize the node { ASTNodeSet PLPrintNodeSet; LetizeNode(n, PLPrintNodeSet); } //pass 2: // //2. print all the let variables and their counterpart expressions //2. as follows (LET var1 = expr1, var2 = expr2, ... // //3. Then print the Node itself, replacing every occurence of //3. expr1 with var1, expr2 with var2, ... //os << "("; if (0 < NodeLetVarMap.size()) { std::vector<pair<ASTNode, ASTNode> >::iterator it = NodeLetVarVec.begin(); const std::vector<pair<ASTNode, ASTNode> >::iterator itend = NodeLetVarVec.end(); os << "(let ("; //print the let var first SMTLIB_Print1(os, it->first, indentation, false); os << " "; //print the expr SMTLIB_Print1(os, it->second, indentation, false); os << " )"; //update the second map for proper printing of LET NodeLetVarMap1[it->second] = it->first; string closing = ""; for (it++; it != itend; it++) { os << " " << endl; os << "(let ("; //print the let var first SMTLIB_Print1(os, it->first, indentation, false); os << " "; //print the expr SMTLIB_Print1(os, it->second, indentation, false); os << ")"; //update the second map for proper printing of LET NodeLetVarMap1[it->second] = it->first; closing += ")"; } os << " ( " << endl; SMTLIB_Print1(os, n, indentation, true); os << closing; os << " ) ) "; } else SMTLIB_Print1(os, n, indentation, false); os << endl; return os; } string functionToSMTLIBName(const Kind k) { switch (k) { case AND: case BVAND: case BVNAND: case BVNOR: case BVOR: case BVSGE: case BVSGT: case BVSLE: case BVSLT: case BVSUB: case BVXOR: case ITE: case NAND: case NOR: case NOT: case OR: case XOR: case IFF: case IMPLIES: { return tolower(_kind_names[k]); } case BVCONCAT: return "concat"; case BVDIV: return "bvudiv"; case BVGT: return "bvugt"; case BVGE: return "bvuge"; case BVLE: return "bvule"; case BVLEFTSHIFT: return "bvshl"; case BVLT: return "bvult"; case BVMOD: return "bvurem"; case BVMULT: return "bvmul"; case BVNEG: return "bvnot"; // CONFUSSSSINNG. (1/2) case BVPLUS: return "bvadd"; case BVRIGHTSHIFT: return "bvlshr"; // logical case BVSRSHIFT: return "bvashr"; // arithmetic. case BVUMINUS: return "bvneg"; // CONFUSSSSINNG. (2/2) case EQ: return "="; case READ: return "select"; case WRITE: return "store"; case SBVDIV: return "bvsdiv"; case SBVREM: return "bvsrem"; default: { cerr << "Unknown name when outputting:"; FatalError(_kind_names[k]); return ""; // to quieten compiler/ } } } } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2019 Intel Corporation. All Rights Reserved. #include <fstream> #include "../common/decompress-huffman.h" #include "proc/depth-decompress.h" #include "environment.h" namespace librealsense { depth_decompression_huffman::depth_decompression_huffman(): functional_processing_block("Depth Huffman Decoder", RS2_FORMAT_Z16, RS2_STREAM_DEPTH, RS2_EXTENSION_DEPTH_FRAME) { get_option(RS2_OPTION_STREAM_FILTER).set(RS2_STREAM_DEPTH); get_option(RS2_OPTION_STREAM_FORMAT_FILTER).set(RS2_FORMAT_Z16H); }; void depth_decompression_huffman::process_function(byte* const dest[], const byte* source, int width, int height, int actual_size, int input_size) { if (!unhuffimage4(reinterpret_cast<uint32_t*>(const_cast<byte*>(source)), uint32_t(input_size >> 2), width << 1, height, const_cast<byte*>(*dest))) { std::stringstream ss; ss << "Depth_huffman_decode_error_input_ts_" << static_cast<uint64_t>(environment::get_instance().get_time_service()->get_time()) << "_" << input_size << "_output_" << actual_size << ".raw"; std::string filename = ss.str().c_str(); LOG_ERROR("Depth decompression error, binary dump: " << filename); std::ofstream file(filename, std::ios::binary | std::ios::trunc); if (!file.good()) throw std::runtime_error(to_string() << "Invalid binary file specified " << filename << " verify the target path and location permissions"); file.write((const char*)source, input_size); } } } <commit_msg>Remove debugging section<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2019 Intel Corporation. All Rights Reserved. #include <fstream> #include "../common/decompress-huffman.h" #include "proc/depth-decompress.h" #include "environment.h" namespace librealsense { depth_decompression_huffman::depth_decompression_huffman(): functional_processing_block("Depth Huffman Decoder", RS2_FORMAT_Z16, RS2_STREAM_DEPTH, RS2_EXTENSION_DEPTH_FRAME) { get_option(RS2_OPTION_STREAM_FILTER).set(RS2_STREAM_DEPTH); get_option(RS2_OPTION_STREAM_FORMAT_FILTER).set(RS2_FORMAT_Z16H); } void depth_decompression_huffman::process_function(byte* const dest[], const byte* source, int width, int height, int actual_size, int input_size) { if (!unhuffimage4(reinterpret_cast<uint32_t*>(const_cast<byte*>(source)), uint32_t(input_size >> 2), width << 1, height, const_cast<byte*>(*dest))) { LOG_WARNING("Depth decompression failed, ts: " << static_cast<uint64_t>(environment::get_instance().get_time_service()->get_time()) << " , compressed size: " << input_size); } } } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2018 Intel Corporation. All Rights Reserved. #include "../include/librealsense2/rs.hpp" #include "../include/librealsense2/rsutil.h" #include "proc/synthetic-stream.h" #include "proc/occlusion-filter.h" #include "../../common/tiny-profiler.h" #include <vector> #include <cmath> #define ROTATION_BUFFER_SIZE 8 #define VERTICAL_SCAN_WINDOW_SIZE 64 #define DEPTH_OCCLUSION_THRESHOLD 1 namespace librealsense { occlusion_filter::occlusion_filter() : _occlusion_filter(occlusion_monotonic_scan) , _occlusion_scanning(horizontal) { } void occlusion_filter::set_texel_intrinsics(const rs2_intrinsics& in) { _texels_intrinsics = in; _texels_depth.resize(_texels_intrinsics.value().width*_texels_intrinsics.value().height); } void occlusion_filter::process(float3* points, float2* uv_map, const std::vector<float2> & pix_coord, const rs2::depth_frame& depth) const { switch (_occlusion_filter) { case occlusion_none: break; case occlusion_monotonic_scan: monotonic_heuristic_invalidation(points, uv_map, pix_coord, depth); break; default: throw std::runtime_error(to_string() << "Unsupported occlusion filter type " << _occlusion_filter << " requested"); break; } } template<size_t SIZE> void rotate_image_counterclockwise(byte* dest[], const byte* source, int width, int height) { { scoped_timer t1("Rotation Time - counterclockwise"); auto width_out = height; auto height_out = width; auto out = dest[0]; byte buffer[ROTATION_BUFFER_SIZE][ROTATION_BUFFER_SIZE * SIZE]; // = { 0 }; for (int i = 0; i <= height - ROTATION_BUFFER_SIZE; i = i + ROTATION_BUFFER_SIZE) { for (int j = 0; j <= width - ROTATION_BUFFER_SIZE; j = j + ROTATION_BUFFER_SIZE) { for (int ii = 0; ii < ROTATION_BUFFER_SIZE; ++ii) { auto out_index = (((height_out - ROTATION_BUFFER_SIZE - j + 1) * width_out) - i - ROTATION_BUFFER_SIZE + (ii)*width_out); memcpy(&(buffer[ii]), &source[(out_index)*SIZE], ROTATION_BUFFER_SIZE * SIZE); } for (int ii = 0; ii < ROTATION_BUFFER_SIZE; ++ii) { for (int jj = 0; jj < ROTATION_BUFFER_SIZE; ++jj) { auto source_index = ((j + jj) + (width * (i + ii))) * SIZE; memcpy(&out[source_index], (void*)(&buffer[ROTATION_BUFFER_SIZE - 1 - jj][(ROTATION_BUFFER_SIZE - 1 - ii) * SIZE]), SIZE); } } } } } } // IMPORTANT! This implementation is based on the assumption that the RGB sensor is positioned strictly to the left of the depth sensor. // namely D415/D435 and SR300. The implementation WILL NOT work properly for different setups // Heuristic occlusion invalidation algorithm: // - Use the uv texels calculated when projecting depth to color // - Scan each line from left to right and check the the U coordinate in the mapping is raising monotonically. // - The occlusion is designated as U coordinate for a given pixel is less than the U coordinate of the predecessing pixel. // - The UV mapping for the occluded pixel is reset to (0,0). Later on the (0,0) coordinate in the texture map is overwritten // with a invalidation color such as black/magenta according to the purpose (production/debugging) void occlusion_filter::monotonic_heuristic_invalidation(float3* points, float2* uv_map, const std::vector<float2>& pix_coord, const rs2::depth_frame& depth) const { float occZTh = 0.1f; //meters int occDilationSz = 1; auto points_width = _depth_intrinsics->width; auto points_height = _depth_intrinsics->height; auto pixels_ptr = pix_coord.data(); auto points_ptr = points; auto uv_map_ptr = uv_map; float maxInLine = -1; float maxZ = 0; auto frame_size = static_cast<int>(_depth_intrinsics->width * _depth_intrinsics->height); std::allocator<byte> alloc; byte* depth_planes[1]; if (_occlusion_scanning == horizontal) { { scoped_timer t1("Horizontal Scan"); for (size_t y = 0; y < points_height; ++y) { maxInLine = -1; maxZ = 0; int occDilationLeft = 0; for (size_t x = 0; x < points_width; ++x) { if (points_ptr->z) { //Occlusion detection if (pixels_ptr->x < maxInLine || (pixels_ptr->x == maxInLine && (points_ptr->z - maxZ) > occZTh)) { *points_ptr = { 0, 0, 0 }; occDilationLeft = occDilationSz; } else { maxInLine = pixels_ptr->x; maxZ = points_ptr->z; if (occDilationLeft > 0) { *points_ptr = { 0, 0, 0 }; occDilationLeft--; } } } ++points_ptr; ++uv_map_ptr; ++pixels_ptr; } } } } else if (_occlusion_scanning == vertical) { depth_planes[0] = (byte*)alloc.allocate(depth.get_bytes_per_pixel() * frame_size); int bpp = depth.get_bytes_per_pixel(); rotate_image_counterclockwise<2>(depth_planes, (const byte*)(depth.get_data()), points_width, points_height); // scan depth frame after clockwise rotation: check if there is a significant jump between adjacen pixels in Z-axis (depth), it means there could be occlusion. // scan over a small window so that points depth is the same // save suspected points and run occlusion-invalidation vertical scan only on them // after rotation : height = points_width , width = points_height auto rotated_depth_width = _depth_intrinsics->height; auto rotated_depth_height = _depth_intrinsics->width; for (int i = 0; i < rotated_depth_height; i++) { for (int j = 0; j < rotated_depth_width - VERTICAL_SCAN_WINDOW_SIZE; j = j + VERTICAL_SCAN_WINDOW_SIZE) { // before rotation: occlusion detected in the positive direction of Y // after counterclockwise rotation : scan from right to left (positive direction of X) to detect occlusion // compare depth each pixel only with the pixel on its right (i,j+1) auto index = i * rotated_depth_width + j; auto uv_i = j; auto uv_j = rotated_depth_height - i; auto uv_index = uv_i * rotated_depth_height + uv_j; // 90 degrees rotation transform from rotated depth auto index_right = index + 1; float diff_right = abs((depth_planes[0])[index] - (depth_planes[0])[index_right]); if ((diff_right > DEPTH_OCCLUSION_THRESHOLD)) { pixels_ptr = pix_coord.data() + uv_index; points_ptr = points + uv_index; uv_map_ptr = uv_map + uv_index; maxInLine = -1; maxZ = 0; int occDilationUp = 0; for (size_t y = 0; y <= VERTICAL_SCAN_WINDOW_SIZE; ++y) { if (((pixels_ptr + y * points_width)->y < maxInLine)) { *(points_ptr + y * points_width) = { 0.f, 0.f, 0.f }; } else { maxInLine = (pixels_ptr + y * points_width)->y; } } } } } } } // Prepare texture map without occlusion that for every texture coordinate there no more than one depth point that is mapped to it // i.e. for every (u,v) map coordinate we select the depth point with minimum Z. all other points that are mapped to this texel will be invalidated // Algo input data: // Vector of 3D [xyz] coordinates of depth_width*depth_height size // Vector of 2D [i,j] coordinates where the val[i,j] stores the texture coordinate (s,t) for the corresponding (i,j) pixel in depth frame // Algo intermediate data: // Vector of depth values (floats) in size of the mapped texture (different from depth width*height) where // each (i,j) cell holds the minimal Z among all the depth pixels that are mapped to the specific texel void occlusion_filter::comprehensive_invalidation(float3* points, float2* uv_map, const std::vector<float2> & pix_coord) const { auto depth_points = points; auto mapped_pix = pix_coord.data(); size_t mapped_tex_width = _texels_intrinsics->width; size_t mapped_tex_height = _texels_intrinsics->height; size_t points_width = _depth_intrinsics->width; size_t points_height = _depth_intrinsics->height; static const float z_threshold = 0.05f; // Compensate for temporal noise when comparing Z values // Clear previous data memset((void*)(_texels_depth.data()), 0, _texels_depth.size() * sizeof(float)); // Pass1 -generate texels mapping with minimal depth for each texel involved for (size_t i = 0; i < points_height; i++) { for (size_t j = 0; j < points_width; j++) { if ((depth_points->z > 0.0001f) && (mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) && (mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height)) { size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x); if ((_texels_depth[texel_index] < 0.0001f) || ((_texels_depth[texel_index] + z_threshold) > depth_points->z)) { _texels_depth[texel_index] = depth_points->z; } } ++depth_points; ++mapped_pix; } } mapped_pix = pix_coord.data(); depth_points = points; auto uv_ptr = uv_map; // Pass2 -invalidate depth texels with occlusion traits for (size_t i = 0; i < points_height; i++) { for (size_t j = 0; j < points_width; j++) { if ((depth_points->z > 0.0001f) && (mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) && (mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height)) { size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x); if ((_texels_depth[texel_index] > 0.0001f) && ((_texels_depth[texel_index] + z_threshold) < depth_points->z)) { *uv_ptr = { 0.f, 0.f }; } } ++depth_points; ++mapped_pix; ++uv_ptr; } } } } <commit_msg>L500 oclusion invalidation performance improvement<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2018 Intel Corporation. All Rights Reserved. #include "../include/librealsense2/rs.hpp" #include "../include/librealsense2/rsutil.h" #include "proc/synthetic-stream.h" #include "proc/occlusion-filter.h" #include "../../common/tiny-profiler.h" #include <vector> #include <cmath> #define ROTATION_BUFFER_SIZE 8 #define VERTICAL_SCAN_WINDOW_SIZE 64 #define DEPTH_OCCLUSION_THRESHOLD 1 namespace librealsense { occlusion_filter::occlusion_filter() : _occlusion_filter(occlusion_monotonic_scan) , _occlusion_scanning(horizontal) { } void occlusion_filter::set_texel_intrinsics(const rs2_intrinsics& in) { _texels_intrinsics = in; _texels_depth.resize(_texels_intrinsics.value().width*_texels_intrinsics.value().height); } void occlusion_filter::process(float3* points, float2* uv_map, const std::vector<float2> & pix_coord, const rs2::depth_frame& depth) const { switch (_occlusion_filter) { case occlusion_none: break; case occlusion_monotonic_scan: monotonic_heuristic_invalidation(points, uv_map, pix_coord, depth); break; default: throw std::runtime_error(to_string() << "Unsupported occlusion filter type " << _occlusion_filter << " requested"); break; } } template<size_t SIZE> void rotate_image_counterclockwise(byte* dest[], const byte* source, int width, int height) { { scoped_timer t1("Rotation Time - counterclockwise"); auto width_out = height; auto height_out = width; auto out = dest[0]; byte buffer[ROTATION_BUFFER_SIZE][ROTATION_BUFFER_SIZE * SIZE]; for (int i = 0; i <= height - ROTATION_BUFFER_SIZE; i = i + ROTATION_BUFFER_SIZE) { for (int j = 0; j <= width - ROTATION_BUFFER_SIZE; j = j + ROTATION_BUFFER_SIZE) { for (int ii = 0; ii < ROTATION_BUFFER_SIZE; ++ii) { auto out_index = (((height_out - ROTATION_BUFFER_SIZE - j + 1) * width_out) - i - ROTATION_BUFFER_SIZE + (ii)*width_out); memcpy(&(buffer[ii]), &source[(out_index)*SIZE], ROTATION_BUFFER_SIZE * SIZE); } for (int ii = 0; ii < ROTATION_BUFFER_SIZE; ++ii) { for (int jj = 0; jj < ROTATION_BUFFER_SIZE; ++jj) { auto source_index = ((j + jj) + (width * (i + ii))) * SIZE; memcpy(&out[source_index], (void*)(&buffer[ROTATION_BUFFER_SIZE - 1 - jj][(ROTATION_BUFFER_SIZE - 1 - ii) * SIZE]), SIZE); } } } } } } // IMPORTANT! This implementation is based on the assumption that the RGB sensor is positioned strictly to the left of the depth sensor. // namely D415/D435 and SR300. The implementation WILL NOT work properly for different setups // Heuristic occlusion invalidation algorithm: // - Use the uv texels calculated when projecting depth to color // - Scan each line from left to right and check the the U coordinate in the mapping is raising monotonically. // - The occlusion is designated as U coordinate for a given pixel is less than the U coordinate of the predecessing pixel. // - The UV mapping for the occluded pixel is reset to (0,0). Later on the (0,0) coordinate in the texture map is overwritten // with a invalidation color such as black/magenta according to the purpose (production/debugging) void occlusion_filter::monotonic_heuristic_invalidation(float3* points, float2* uv_map, const std::vector<float2>& pix_coord, const rs2::depth_frame& depth) const { float occZTh = 0.1f; //meters int occDilationSz = 1; auto points_width = _depth_intrinsics->width; auto points_height = _depth_intrinsics->height; auto pixels_ptr = pix_coord.data(); auto points_ptr = points; auto uv_map_ptr = uv_map; float maxInLine = -1; float maxZ = 0; auto frame_size = static_cast<int>(_depth_intrinsics->width * _depth_intrinsics->height); std::allocator<byte> alloc; byte* depth_planes[1]; if (_occlusion_scanning == horizontal) { { scoped_timer t1("Horizontal Scan"); for (size_t y = 0; y < points_height; ++y) { maxInLine = -1; maxZ = 0; int occDilationLeft = 0; for (size_t x = 0; x < points_width; ++x) { if (points_ptr->z) { //Occlusion detection if (pixels_ptr->x < maxInLine || (pixels_ptr->x == maxInLine && (points_ptr->z - maxZ) > occZTh)) { *points_ptr = { 0, 0, 0 }; occDilationLeft = occDilationSz; } else { maxInLine = pixels_ptr->x; maxZ = points_ptr->z; if (occDilationLeft > 0) { *points_ptr = { 0, 0, 0 }; occDilationLeft--; } } } ++points_ptr; ++uv_map_ptr; ++pixels_ptr; } } } } else if (_occlusion_scanning == vertical) { depth_planes[0] = (byte*)alloc.allocate(depth.get_bytes_per_pixel() * frame_size); int bpp = depth.get_bytes_per_pixel(); rotate_image_counterclockwise<2>(depth_planes, (const byte*)(depth.get_data()), points_width, points_height); // scan depth frame after clockwise rotation: check if there is a significant jump between adjacen pixels in Z-axis (depth), it means there could be occlusion. // scan over a small window so that points depth is the same // save suspected points and run occlusion-invalidation vertical scan only on them // after rotation : height = points_width , width = points_height auto rotated_depth_width = _depth_intrinsics->height; auto rotated_depth_height = _depth_intrinsics->width; for (int i = 0; i < rotated_depth_height; i++) { for (int j = 0; j < rotated_depth_width - VERTICAL_SCAN_WINDOW_SIZE; j = j + VERTICAL_SCAN_WINDOW_SIZE) { // before rotation: occlusion detected in the positive direction of Y // after counterclockwise rotation : scan from right to left (positive direction of X) to detect occlusion // compare depth each pixel only with the pixel on its right (i,j+1) auto index = i * rotated_depth_width + j; auto uv_i = j; auto uv_j = rotated_depth_height - i; auto uv_index = uv_i * rotated_depth_height + uv_j; // 90 degrees rotation transform from rotated depth auto index_right = index + 1; float diff_right = abs((depth_planes[0])[index] - (depth_planes[0])[index_right]); if ((diff_right > DEPTH_OCCLUSION_THRESHOLD)) { pixels_ptr = pix_coord.data() + uv_index; points_ptr = points + uv_index; uv_map_ptr = uv_map + uv_index; maxInLine = -1; maxZ = 0; int occDilationUp = 0; for (size_t y = 0; y <= VERTICAL_SCAN_WINDOW_SIZE; ++y) { if (((pixels_ptr + y * points_width)->y < maxInLine)) { *(points_ptr + y * points_width) = { 0.f, 0.f, 0.f }; } else { maxInLine = (pixels_ptr + y * points_width)->y; } } } } } } } // Prepare texture map without occlusion that for every texture coordinate there no more than one depth point that is mapped to it // i.e. for every (u,v) map coordinate we select the depth point with minimum Z. all other points that are mapped to this texel will be invalidated // Algo input data: // Vector of 3D [xyz] coordinates of depth_width*depth_height size // Vector of 2D [i,j] coordinates where the val[i,j] stores the texture coordinate (s,t) for the corresponding (i,j) pixel in depth frame // Algo intermediate data: // Vector of depth values (floats) in size of the mapped texture (different from depth width*height) where // each (i,j) cell holds the minimal Z among all the depth pixels that are mapped to the specific texel void occlusion_filter::comprehensive_invalidation(float3* points, float2* uv_map, const std::vector<float2> & pix_coord) const { auto depth_points = points; auto mapped_pix = pix_coord.data(); size_t mapped_tex_width = _texels_intrinsics->width; size_t mapped_tex_height = _texels_intrinsics->height; size_t points_width = _depth_intrinsics->width; size_t points_height = _depth_intrinsics->height; static const float z_threshold = 0.05f; // Compensate for temporal noise when comparing Z values // Clear previous data memset((void*)(_texels_depth.data()), 0, _texels_depth.size() * sizeof(float)); // Pass1 -generate texels mapping with minimal depth for each texel involved for (size_t i = 0; i < points_height; i++) { for (size_t j = 0; j < points_width; j++) { if ((depth_points->z > 0.0001f) && (mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) && (mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height)) { size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x); if ((_texels_depth[texel_index] < 0.0001f) || ((_texels_depth[texel_index] + z_threshold) > depth_points->z)) { _texels_depth[texel_index] = depth_points->z; } } ++depth_points; ++mapped_pix; } } mapped_pix = pix_coord.data(); depth_points = points; auto uv_ptr = uv_map; // Pass2 -invalidate depth texels with occlusion traits for (size_t i = 0; i < points_height; i++) { for (size_t j = 0; j < points_width; j++) { if ((depth_points->z > 0.0001f) && (mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) && (mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height)) { size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x); if ((_texels_depth[texel_index] > 0.0001f) && ((_texels_depth[texel_index] + z_threshold) < depth_points->z)) { *uv_ptr = { 0.f, 0.f }; } } ++depth_points; ++mapped_pix; ++uv_ptr; } } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outline.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 09:55:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _OUTLINE_HXX #define _OUTLINE_HXX #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SV_MENU_HXX //autogen #include <vcl/menu.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _FIELD_HXX //autogen #include <vcl/field.hxx> #endif #include "swtypes.hxx" //fuer MAXLEVEL #ifndef _NUMPREVW_HXX #include <numprevw.hxx> #endif #ifndef _NUMBERINGTYPELISTBOX_HXX #include <numberingtypelistbox.hxx> #endif class SwWrtShell; class SwTxtFmtColl; class SwNumRule; class SwChapterNumRules; /* -----------------07.07.98 13:38------------------- * * --------------------------------------------------*/ class SwOutlineTabDialog : public SfxTabDialog { static USHORT nNumLevel; String aNullStr; String aCollNames[MAXLEVEL]; PopupMenu aFormMenu; SwWrtShell& rWrtSh; SwNumRule* pNumRule; SwChapterNumRules* pChapterNumRules; BOOL bModified : 1; protected: DECL_LINK( CancelHdl, Button * ); DECL_LINK( FormHdl, Button * ); DECL_LINK( MenuSelectHdl, Menu * ); virtual void PageCreated(USHORT nPageId, SfxTabPage& rPage); virtual short Ok(); public: SwOutlineTabDialog(Window* pParent, const SfxItemSet* pSwItemSet, SwWrtShell &); ~SwOutlineTabDialog(); SwNumRule* GetNumRule() {return pNumRule;} USHORT GetLevel(const String &rFmtName) const; String* GetCollNames() {return aCollNames;} static USHORT GetActNumLevel() {return nNumLevel;} static void SetActNumLevel(USHORT nSet) {nNumLevel = nSet;} }; /* -----------------07.07.98 13:47------------------- * * --------------------------------------------------*/ class SwOutlineSettingsTabPage : public SfxTabPage { ListBox aLevelLB; FixedLine aLevelFL; FixedText aCollLbl; ListBox aCollBox; FixedText aNumberLbl; SwNumberingTypeListBox aNumberBox; FixedText aCharFmtFT; ListBox aCharFmtLB; FixedText aAllLevelFT; NumericField aAllLevelNF; FixedText aDelim; FixedText aPrefixFT; Edit aPrefixED; FixedText aSuffixFT; Edit aSuffixED; FixedText aStartLbl; NumericField aStartEdit; FixedLine aNumberFL; NumberingPreview aPreviewWIN; String aNoFmtName; String aSaveCollNames[MAXLEVEL]; SwWrtShell* pSh; SwNumRule* pNumRule; String* pCollNames; USHORT nActLevel; DECL_LINK( LevelHdl, ListBox * ); DECL_LINK( ToggleComplete, NumericField * ); DECL_LINK( CollSelect, ListBox * ); DECL_LINK( CollSelectGetFocus, ListBox * ); DECL_LINK( NumberSelect, SwNumberingTypeListBox * ); DECL_LINK( DelimModify, Edit * ); DECL_LINK( StartModified, NumericField * ); DECL_LINK( CharFmtHdl, ListBox * ); void Update(); void SetModified(){aPreviewWIN.Invalidate();} void CheckForStartValue_Impl(sal_uInt16 nNumberingType); public: SwOutlineSettingsTabPage(Window* pParent, const SfxItemSet& rSet); ~SwOutlineSettingsTabPage(); void SetWrtShell(SwWrtShell* pShell); virtual void ActivatePage(const SfxItemSet& rSet); virtual int DeactivatePage(SfxItemSet *pSet); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); }; #endif <commit_msg>INTEGRATION: CWS writercorehandoff (1.5.156); FILE MERGED 2005/09/13 17:38:36 tra 1.5.156.2: RESYNC: (1.5-1.6); FILE MERGED 2005/06/07 14:15:46 fme 1.5.156.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outline.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-08-14 17:44:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _OUTLINE_HXX #define _OUTLINE_HXX #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SV_MENU_HXX //autogen #include <vcl/menu.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _FIELD_HXX //autogen #include <vcl/field.hxx> #endif #include "swtypes.hxx" //fuer MAXLEVEL #ifndef _NUMPREVW_HXX #include <numprevw.hxx> #endif #ifndef _NUMBERINGTYPELISTBOX_HXX #include <numberingtypelistbox.hxx> #endif class SwWrtShell; class SwNumRule; class SwChapterNumRules; /* -----------------07.07.98 13:38------------------- * * --------------------------------------------------*/ class SwOutlineTabDialog : public SfxTabDialog { static USHORT nNumLevel; String aNullStr; String aCollNames[MAXLEVEL]; PopupMenu aFormMenu; SwWrtShell& rWrtSh; SwNumRule* pNumRule; SwChapterNumRules* pChapterNumRules; BOOL bModified : 1; protected: DECL_LINK( CancelHdl, Button * ); DECL_LINK( FormHdl, Button * ); DECL_LINK( MenuSelectHdl, Menu * ); virtual void PageCreated(USHORT nPageId, SfxTabPage& rPage); virtual short Ok(); public: SwOutlineTabDialog(Window* pParent, const SfxItemSet* pSwItemSet, SwWrtShell &); ~SwOutlineTabDialog(); SwNumRule* GetNumRule() {return pNumRule;} USHORT GetLevel(const String &rFmtName) const; String* GetCollNames() {return aCollNames;} static USHORT GetActNumLevel() {return nNumLevel;} static void SetActNumLevel(USHORT nSet) {nNumLevel = nSet;} }; /* -----------------07.07.98 13:47------------------- * * --------------------------------------------------*/ class SwOutlineSettingsTabPage : public SfxTabPage { ListBox aLevelLB; FixedLine aLevelFL; FixedText aCollLbl; ListBox aCollBox; FixedText aNumberLbl; SwNumberingTypeListBox aNumberBox; FixedText aCharFmtFT; ListBox aCharFmtLB; FixedText aAllLevelFT; NumericField aAllLevelNF; FixedText aDelim; FixedText aPrefixFT; Edit aPrefixED; FixedText aSuffixFT; Edit aSuffixED; FixedText aStartLbl; NumericField aStartEdit; FixedLine aNumberFL; NumberingPreview aPreviewWIN; String aNoFmtName; String aSaveCollNames[MAXLEVEL]; SwWrtShell* pSh; SwNumRule* pNumRule; String* pCollNames; USHORT nActLevel; DECL_LINK( LevelHdl, ListBox * ); DECL_LINK( ToggleComplete, NumericField * ); DECL_LINK( CollSelect, ListBox * ); DECL_LINK( CollSelectGetFocus, ListBox * ); DECL_LINK( NumberSelect, SwNumberingTypeListBox * ); DECL_LINK( DelimModify, Edit * ); DECL_LINK( StartModified, NumericField * ); DECL_LINK( CharFmtHdl, ListBox * ); void Update(); void SetModified(){aPreviewWIN.Invalidate();} void CheckForStartValue_Impl(sal_uInt16 nNumberingType); public: SwOutlineSettingsTabPage(Window* pParent, const SfxItemSet& rSet); ~SwOutlineSettingsTabPage(); void SetWrtShell(SwWrtShell* pShell); virtual void ActivatePage(const SfxItemSet& rSet); virtual int DeactivatePage(SfxItemSet *pSet); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); }; #endif <|endoftext|>
<commit_before>/** * @author : xiaozhuai * @date : 17/1/3 */ #include "UrlEncode.h" namespace CXXUrl { unsigned char UrlEncode::ToHex(unsigned char x) { return x > 9 ? x + 55 : x + 48; } unsigned char UrlEncode::FromHex(unsigned char x) { unsigned char y; if (x >= 'A' && x <= 'Z') y = x - 'A' + 10; else if (x >= 'a' && x <= 'z') y = x - 'a' + 10; else if (x >= '0' && x <= '9') y = x - '0'; else assert(0); return y; } std::string UrlEncode::encode(const std::string &str) { std::string strTemp; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (isalnum((unsigned char)str[i]) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '~')) strTemp += str[i]; else if (str[i] == ' ') strTemp += "+"; else { strTemp += '%'; strTemp += ToHex((unsigned char)(str[i] >> 4)); strTemp += ToHex((unsigned char)(str[i] % 16)); } } return strTemp; } std::string UrlEncode::decode(const std::string &str) { std::string strTemp; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (str[i] == '+') strTemp += ' '; else if (str[i] == '%') { assert(i + 2 < length); unsigned char high = FromHex((unsigned char)str[++i]); unsigned char low = FromHex((unsigned char)str[++i]); strTemp += high*16 + low; } else strTemp += str[i]; } return strTemp; } }<commit_msg>fix a bug in urlencode<commit_after>/** * @author : xiaozhuai * @date : 17/1/3 */ #include "UrlEncode.h" namespace CXXUrl { unsigned char UrlEncode::ToHex(unsigned char x) { return x > 9 ? x + 55 : x + 48; } unsigned char UrlEncode::FromHex(unsigned char x) { unsigned char y; if (x >= 'A' && x <= 'Z') y = x - 'A' + 10; else if (x >= 'a' && x <= 'z') y = x - 'a' + 10; else if (x >= '0' && x <= '9') y = x - '0'; else assert(0); return y; } std::string UrlEncode::encode(const std::string &str) { std::string strTemp; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (isalnum((unsigned char)str[i]) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '~')) strTemp += str[i]; else if (str[i] == ' ') strTemp += "+"; else { strTemp += '%'; strTemp += ToHex((unsigned char)str[i] >> 4); strTemp += ToHex((unsigned char)str[i] % 16); } } return strTemp; } std::string UrlEncode::decode(const std::string &str) { std::string strTemp; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (str[i] == '+') strTemp += ' '; else if (str[i] == '%') { assert(i + 2 < length); unsigned char high = FromHex((unsigned char)str[++i]); unsigned char low = FromHex((unsigned char)str[++i]); strTemp += high*16 + low; } else strTemp += str[i]; } return strTemp; } }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PositionAndSizeHelper.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:08:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "PositionAndSizeHelper.hxx" #include "macros.hxx" #include "ChartModelHelper.hxx" #include "ControllerLockGuard.hxx" #ifndef _COM_SUN_STAR_CHART2_LEGENDPOSITION_HPP_ #include <com/sun/star/chart2/LegendPosition.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_RELATIVEPOSITION_HPP_ #include <com/sun/star/chart2/RelativePosition.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_RELATIVESIZE_HPP_ #include <com/sun/star/chart2/RelativeSize.hpp> #endif #include "chartview/ExplicitValueProvider.hxx" // header for class Rectangle #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; bool PositionAndSizeHelper::moveObject( ObjectType eObjectType , const uno::Reference< beans::XPropertySet >& xObjectProp , const awt::Rectangle& rNewPositionAndSize , const awt::Rectangle& rPageRectangle ) { if(!xObjectProp.is()) return false; Rectangle aObjectRect( Point(rNewPositionAndSize.X,rNewPositionAndSize.Y), Size(rNewPositionAndSize.Width,rNewPositionAndSize.Height) ); Rectangle aPageRect( Point(rPageRectangle.X,rPageRectangle.Y), Size(rPageRectangle.Width,rPageRectangle.Height) ); if( OBJECTTYPE_TITLE==eObjectType ) { //@todo decide wether x is primary or secondary chart2::RelativePosition aRelativePosition; aRelativePosition.Anchor = drawing::Alignment_TOP; //the anchor point at the title object is top/middle Point aPos = aObjectRect.TopLeft(); aRelativePosition.Primary = (double(aPos.X())+double(aObjectRect.getWidth())/2.0)/double(aPageRect.getWidth()); aRelativePosition.Secondary = double(aPos.Y())/double(aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativePosition" ), uno::makeAny(aRelativePosition) ); } else if(OBJECTTYPE_LEGEND==eObjectType) { LegendPosition ePos = LegendPosition_LINE_END; xObjectProp->getPropertyValue( C2U( "AnchorPosition" )) >>= ePos; chart2::RelativePosition aRelativePosition; Point aAnchor = aObjectRect.TopLeft(); switch( ePos ) { case LegendPosition_LINE_START: { //@todo language dependent positions ... aRelativePosition.Anchor = drawing::Alignment_LEFT; aAnchor = aObjectRect.LeftCenter(); } break; case LegendPosition_LINE_END: { //@todo language dependent positions ... aRelativePosition.Anchor = drawing::Alignment_RIGHT; aAnchor = aObjectRect.RightCenter(); } break; case LegendPosition_PAGE_START: { //@todo language dependent positions ... aRelativePosition.Anchor = drawing::Alignment_TOP; aAnchor = aObjectRect.TopCenter(); } break; case LegendPosition_PAGE_END: //@todo language dependent positions ... { aRelativePosition.Anchor = drawing::Alignment_BOTTOM; aAnchor = aObjectRect.BottomCenter(); } break; case LegendPosition_CUSTOM: { //@todo language dependent positions ... aRelativePosition.Anchor = drawing::Alignment_TOP_LEFT; } break; case LegendPosition_MAKE_FIXED_SIZE: OSL_ASSERT( false ); break; } aRelativePosition.Primary = static_cast< double >( aAnchor.X()) / static_cast< double >( aPageRect.getWidth() ); aRelativePosition.Secondary = static_cast< double >( aAnchor.Y()) / static_cast< double >( aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativePosition" ), uno::makeAny(aRelativePosition) ); } else if(OBJECTTYPE_DIAGRAM==eObjectType || OBJECTTYPE_DIAGRAM_WALL==eObjectType || OBJECTTYPE_DIAGRAM_FLOOR==eObjectType) { //@todo decide wether x is primary or secondary //xChartView //set position: chart2::RelativePosition aRelativePosition; aRelativePosition.Anchor = drawing::Alignment_CENTER; Point aPos = aObjectRect.Center(); aRelativePosition.Primary = double(aPos.X())/double(aPageRect.getWidth()); aRelativePosition.Secondary = double(aPos.Y())/double(aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativePosition" ), uno::makeAny(aRelativePosition) ); //set size: RelativeSize aRelativeSize; //the anchor points for the diagram are in the middle of the diagram //and in the middle of the page aRelativeSize.Primary = double(aObjectRect.getWidth())/double(aPageRect.getWidth()); aRelativeSize.Secondary = double(aObjectRect.getHeight())/double(aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativeSize" ), uno::makeAny(aRelativeSize) ); } else return false; return true; } bool PositionAndSizeHelper::moveObject( const rtl::OUString& rObjectCID , const uno::Reference< frame::XModel >& xChartModel , const awt::Rectangle& rNewPositionAndSize , const awt::Rectangle& rPageRectangle , uno::Reference< uno::XInterface > xChartView ) { ControllerLockGuard aLockedControllers( xChartModel ); awt::Rectangle aNewPositionAndSize( rNewPositionAndSize ); uno::Reference< beans::XPropertySet > xObjectProp = ObjectIdentifier::getObjectPropertySet( rObjectCID, xChartModel ); ObjectType eObjectType( ObjectIdentifier::getObjectType( rObjectCID ) ); if(OBJECTTYPE_DIAGRAM==eObjectType || OBJECTTYPE_DIAGRAM_WALL==eObjectType || OBJECTTYPE_DIAGRAM_FLOOR==eObjectType) { xObjectProp = uno::Reference< beans::XPropertySet >( ObjectIdentifier::getDiagramForCID( rObjectCID, xChartModel ), uno::UNO_QUERY ); if(!xObjectProp.is()) return false; //add axis title sizes to the diagram size aNewPositionAndSize = ExplicitValueProvider::calculateDiagramPositionAndSizeInclusiveTitle( xChartModel, xChartView, rNewPositionAndSize ); } return moveObject( eObjectType, xObjectProp, aNewPositionAndSize, rPageRectangle ); } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS chart17 (1.5.66); FILE MERGED 2007/10/12 12:35:08 bm 1.5.66.1: #i7998# equations for regression curves<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PositionAndSizeHelper.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: ihi $ $Date: 2007-11-23 11:55:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "PositionAndSizeHelper.hxx" #include "macros.hxx" #include "ChartModelHelper.hxx" #include "ControllerLockGuard.hxx" #ifndef _COM_SUN_STAR_CHART2_LEGENDPOSITION_HPP_ #include <com/sun/star/chart2/LegendPosition.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_RELATIVEPOSITION_HPP_ #include <com/sun/star/chart2/RelativePosition.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_RELATIVESIZE_HPP_ #include <com/sun/star/chart2/RelativeSize.hpp> #endif #include "chartview/ExplicitValueProvider.hxx" // header for class Rectangle #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; bool PositionAndSizeHelper::moveObject( ObjectType eObjectType , const uno::Reference< beans::XPropertySet >& xObjectProp , const awt::Rectangle& rNewPositionAndSize , const awt::Rectangle& rPageRectangle ) { if(!xObjectProp.is()) return false; Rectangle aObjectRect( Point(rNewPositionAndSize.X,rNewPositionAndSize.Y), Size(rNewPositionAndSize.Width,rNewPositionAndSize.Height) ); Rectangle aPageRect( Point(rPageRectangle.X,rPageRectangle.Y), Size(rPageRectangle.Width,rPageRectangle.Height) ); if( OBJECTTYPE_TITLE==eObjectType ) { //@todo decide wether x is primary or secondary chart2::RelativePosition aRelativePosition; aRelativePosition.Anchor = drawing::Alignment_TOP; //the anchor point at the title object is top/middle Point aPos = aObjectRect.TopLeft(); aRelativePosition.Primary = (double(aPos.X())+double(aObjectRect.getWidth())/2.0)/double(aPageRect.getWidth()); aRelativePosition.Secondary = double(aPos.Y())/double(aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativePosition" ), uno::makeAny(aRelativePosition) ); } else if( OBJECTTYPE_DATA_CURVE_EQUATION==eObjectType ) { //@todo decide wether x is primary or secondary chart2::RelativePosition aRelativePosition; aRelativePosition.Anchor = drawing::Alignment_TOP_LEFT; //the anchor point at the title object is top/middle Point aPos = aObjectRect.TopLeft(); aRelativePosition.Primary = double(aPos.X())/double(aPageRect.getWidth()); aRelativePosition.Secondary = double(aPos.Y())/double(aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativePosition" ), uno::makeAny(aRelativePosition) ); } else if(OBJECTTYPE_LEGEND==eObjectType) { LegendPosition ePos = LegendPosition_LINE_END; xObjectProp->getPropertyValue( C2U( "AnchorPosition" )) >>= ePos; chart2::RelativePosition aRelativePosition; Point aAnchor = aObjectRect.TopLeft(); switch( ePos ) { case LegendPosition_LINE_START: { //@todo language dependent positions ... aRelativePosition.Anchor = drawing::Alignment_LEFT; aAnchor = aObjectRect.LeftCenter(); } break; case LegendPosition_LINE_END: { //@todo language dependent positions ... aRelativePosition.Anchor = drawing::Alignment_RIGHT; aAnchor = aObjectRect.RightCenter(); } break; case LegendPosition_PAGE_START: { //@todo language dependent positions ... aRelativePosition.Anchor = drawing::Alignment_TOP; aAnchor = aObjectRect.TopCenter(); } break; case LegendPosition_PAGE_END: //@todo language dependent positions ... { aRelativePosition.Anchor = drawing::Alignment_BOTTOM; aAnchor = aObjectRect.BottomCenter(); } break; case LegendPosition_CUSTOM: { //@todo language dependent positions ... aRelativePosition.Anchor = drawing::Alignment_TOP_LEFT; } break; case LegendPosition_MAKE_FIXED_SIZE: OSL_ASSERT( false ); break; } aRelativePosition.Primary = static_cast< double >( aAnchor.X()) / static_cast< double >( aPageRect.getWidth() ); aRelativePosition.Secondary = static_cast< double >( aAnchor.Y()) / static_cast< double >( aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativePosition" ), uno::makeAny(aRelativePosition) ); } else if(OBJECTTYPE_DIAGRAM==eObjectType || OBJECTTYPE_DIAGRAM_WALL==eObjectType || OBJECTTYPE_DIAGRAM_FLOOR==eObjectType) { //@todo decide wether x is primary or secondary //xChartView //set position: chart2::RelativePosition aRelativePosition; aRelativePosition.Anchor = drawing::Alignment_CENTER; Point aPos = aObjectRect.Center(); aRelativePosition.Primary = double(aPos.X())/double(aPageRect.getWidth()); aRelativePosition.Secondary = double(aPos.Y())/double(aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativePosition" ), uno::makeAny(aRelativePosition) ); //set size: RelativeSize aRelativeSize; //the anchor points for the diagram are in the middle of the diagram //and in the middle of the page aRelativeSize.Primary = double(aObjectRect.getWidth())/double(aPageRect.getWidth()); aRelativeSize.Secondary = double(aObjectRect.getHeight())/double(aPageRect.getHeight()); xObjectProp->setPropertyValue( C2U( "RelativeSize" ), uno::makeAny(aRelativeSize) ); } else return false; return true; } bool PositionAndSizeHelper::moveObject( const rtl::OUString& rObjectCID , const uno::Reference< frame::XModel >& xChartModel , const awt::Rectangle& rNewPositionAndSize , const awt::Rectangle& rPageRectangle , uno::Reference< uno::XInterface > xChartView ) { ControllerLockGuard aLockedControllers( xChartModel ); awt::Rectangle aNewPositionAndSize( rNewPositionAndSize ); uno::Reference< beans::XPropertySet > xObjectProp = ObjectIdentifier::getObjectPropertySet( rObjectCID, xChartModel ); ObjectType eObjectType( ObjectIdentifier::getObjectType( rObjectCID ) ); if(OBJECTTYPE_DIAGRAM==eObjectType || OBJECTTYPE_DIAGRAM_WALL==eObjectType || OBJECTTYPE_DIAGRAM_FLOOR==eObjectType) { xObjectProp = uno::Reference< beans::XPropertySet >( ObjectIdentifier::getDiagramForCID( rObjectCID, xChartModel ), uno::UNO_QUERY ); if(!xObjectProp.is()) return false; //add axis title sizes to the diagram size aNewPositionAndSize = ExplicitValueProvider::calculateDiagramPositionAndSizeInclusiveTitle( xChartModel, xChartView, rNewPositionAndSize ); } return moveObject( eObjectType, xObjectProp, aNewPositionAndSize, rPageRectangle ); } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>// -*- C++ -*- // The MIT License (MIT) // // Copyright (c) 2021 Alexander Samoilov // // 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 "ChebyshevDifferentiate.hpp" namespace CS { /// /// as \f$T_n(\cos\theta)=\cos n\theta\f$, then /// /// \f[ /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}=\frac2{c_n}T_n(x) /// \quad(n>=0) /// \f] /// /// where \f$c_0=2,\,c_n=1\,(n\le1)\f$ and \f$T'_0=T'_{-1}=0\f$, implies if /// /// \f[ /// \frac d{dx}\sum^N_{n=0}a_nT_n(x)=\sum^N_{n=0}b_nT_n(x) /// \f] /// /// then /// /// \f{align*}{ /// \sum^N_{n=0}a_nT'_n(x) /// &=\sum^N_{n=0}c_nb_n\left[T_n(x) /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}\right]\\ /// &=\sum^{N+1}_{n=0}[c_{n-1}b_{n-1}-b_{n+1}]T'_n(x)/n /// \f} /// /// equating \f$T'_n(x)\f$ for \f$n=1,\dots,N+1\f$ /// we derive recurrent equations for Chebyshev polynomials derivatives /// /// \f{alignat*}{{2} /// c_{n-1}b_{n-1}-b_{n+1} &= 2na_n &&\quad(1\le n\le N)\\ /// b_n &=0 &&\quad(n\ge N) /// \f} /// /// if approximate solution is at each collocation point \f$(x_j)\f$ /// /// \f[ /// u(x,t) = \sum_{k=1}^{N+1}a_{k}T_{k-1}(x) /// \f] /// /// then, in particular, spatial derivatives can be defined directly in terms /// of undifferentiated Chebyshev polynomials, i.e. /// /// \f[ /// \frac{\partial{u}}{\partial{x}} = \sum_{k=1}^{N}a_{k}^{(1)}T_{k-1}(x) /// \f] /// /// and /// /// \f[ /// \frac{\partial^2{u}}{\partial{x^2}} = \sum_{k=1}^{N-1}a_{k}^{(2)}T_{k-1}(x) /// \f] /// /// Specifically, the following recurrence relations permit all /// the \f$a_k^{(1)}, a_k^{(2)}\f$ coefficients to be obtained in \f$O(N)\f$ operations /// /// \f{alignat*}{{2} /// a_k^{(1)} &= a_{k+2}^{(1)} + 2k a_{k+1} &&\quad(2\le k\le N)\\ /// a_k^{(2)} &= a_{k+2}^{(2)} + 2k a_{k+1}^{(1)} &&\quad(2\le k\le N-1)\\ /// \f} /// /// and \f$\qquad a_1^{(1)} = 0.5 a_3^{(1)} + 2k a_2, \quad a_1^{(2)} = 0.5 a_3^{(2)} + 2k a_2^{(1)}\f$ /// /// and \f$\qquad a_{N+1}^{(1)} = a_{N+2}^{(1)} = 0, \quad a_{N}^{(2)} = a_{N+1}^{(2)} = 0\f$ void spectral_differentiate(size_t n, Eigen::Ref<RowVectorXd> in, Eigen::Ref<RowVectorXd> out, double span) { double temp1 = in[n-1], temp2 = in[n-2]; out[n-1] = 2.0 * n * in[n] * span; out[n-2] = 2.0 * (n-1) * temp1 * span; for (size_t j = n-3; j>0; j--) { temp1 = in[j]; out[j] = out[j+2] + 2.0 * (j+1) * temp2 * span; temp2 = temp1; } out[0] = 0.5 * out[2] + temp2 * span; out[n] = 0.0; } /// as \f$T_n(\cos\theta)=\cos n\theta\f$, then /// /// \f[ /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}=\frac2{c_n}T_n(x) /// \quad(n>=0) /// \f] /// /// From boundary conditions and Chebyshev polynomials traits \f$T_n(\pm1)=(\pm1)^n\f$ we derive /// \f{alignat}{{3} /// \sum^N_{p=0 \quad p\equiv0\pmod2} a_{mp} &= /// \sum^N_{p=1 \quad p\equiv1\pmod2} a_{mp} &= 0 && /// \qquad 0\le m\le M\\ /// \sum^N_{q=0 \quad q\equiv0\pmod2} a_{qn} &= /// \sum^N_{q=1 \quad q\equiv1\pmod2} a_{qn} &= 0 && /// \qquad 0\le n\le N /// \f} void homogeneous_boundary(size_t m, size_t n, Eigen::Ref<RowMatrixXd> in, Eigen::Ref<RowMatrixXd> out) { if (out != in) { out = in; } double evens, odds; for (size_t i=0; i<=m-2; ++i) { evens = odds = 0.0; for (size_t j=1; j<n-2; j+=2) { odds -= out(i, j); evens -= out(i, j+1); } out(i, n-1) = odds; out(i, n) = evens - out(i, 0); } for (size_t i=0; i<=n-2; ++i) { evens = odds = 0.0; for (size_t j=1; j<m-2; j+=2) { odds -= out(j, i); evens -= out(j+1, i); } out(n-1, i) = odds; out(n, i) = evens - out(0, i); } evens = odds = 0.0; for (size_t j=1; j<n-2; j+=2) { odds -= out(n-1, j); evens -= out(n-1, j+1); } out(n-1, n-1) = odds; out(n-1, n) = evens - out(n-1, 0); evens = odds = 0.0; for (size_t i=0; i<m; i+=2) { odds -= out(i, n-1); evens -= out(i, n); } out(n, n-1) = odds; out(n, n) = evens; } void second_derivative(size_t m, size_t n, Eigen::Ref<RowMatrixXd> in, Eigen::Ref<RowMatrixXd> out) { homogeneous_boundary(m, n, in, out); for (size_t i = 0; i <= m; ++i) { spectral_differentiate(n, out.row(i), out.row(i)); spectral_differentiate(n, out.row(i), out.row(i)); } } } // namespace CS <commit_msg>one more fix in `homogeneous_boundary`<commit_after>// -*- C++ -*- // The MIT License (MIT) // // Copyright (c) 2021 Alexander Samoilov // // 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 "ChebyshevDifferentiate.hpp" namespace CS { /// /// as \f$T_n(\cos\theta)=\cos n\theta\f$, then /// /// \f[ /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}=\frac2{c_n}T_n(x) /// \quad(n>=0) /// \f] /// /// where \f$c_0=2,\,c_n=1\,(n\le1)\f$ and \f$T'_0=T'_{-1}=0\f$, implies if /// /// \f[ /// \frac d{dx}\sum^N_{n=0}a_nT_n(x)=\sum^N_{n=0}b_nT_n(x) /// \f] /// /// then /// /// \f{align*}{ /// \sum^N_{n=0}a_nT'_n(x) /// &=\sum^N_{n=0}c_nb_n\left[T_n(x) /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}\right]\\ /// &=\sum^{N+1}_{n=0}[c_{n-1}b_{n-1}-b_{n+1}]T'_n(x)/n /// \f} /// /// equating \f$T'_n(x)\f$ for \f$n=1,\dots,N+1\f$ /// we derive recurrent equations for Chebyshev polynomials derivatives /// /// \f{alignat*}{{2} /// c_{n-1}b_{n-1}-b_{n+1} &= 2na_n &&\quad(1\le n\le N)\\ /// b_n &=0 &&\quad(n\ge N) /// \f} /// /// if approximate solution is at each collocation point \f$(x_j)\f$ /// /// \f[ /// u(x,t) = \sum_{k=1}^{N+1}a_{k}T_{k-1}(x) /// \f] /// /// then, in particular, spatial derivatives can be defined directly in terms /// of undifferentiated Chebyshev polynomials, i.e. /// /// \f[ /// \frac{\partial{u}}{\partial{x}} = \sum_{k=1}^{N}a_{k}^{(1)}T_{k-1}(x) /// \f] /// /// and /// /// \f[ /// \frac{\partial^2{u}}{\partial{x^2}} = \sum_{k=1}^{N-1}a_{k}^{(2)}T_{k-1}(x) /// \f] /// /// Specifically, the following recurrence relations permit all /// the \f$a_k^{(1)}, a_k^{(2)}\f$ coefficients to be obtained in \f$O(N)\f$ operations /// /// \f{alignat*}{{2} /// a_k^{(1)} &= a_{k+2}^{(1)} + 2k a_{k+1} &&\quad(2\le k\le N)\\ /// a_k^{(2)} &= a_{k+2}^{(2)} + 2k a_{k+1}^{(1)} &&\quad(2\le k\le N-1)\\ /// \f} /// /// and \f$\qquad a_1^{(1)} = 0.5 a_3^{(1)} + 2k a_2, \quad a_1^{(2)} = 0.5 a_3^{(2)} + 2k a_2^{(1)}\f$ /// /// and \f$\qquad a_{N+1}^{(1)} = a_{N+2}^{(1)} = 0, \quad a_{N}^{(2)} = a_{N+1}^{(2)} = 0\f$ void spectral_differentiate(size_t n, Eigen::Ref<RowVectorXd> in, Eigen::Ref<RowVectorXd> out, double span) { double temp1 = in[n-1], temp2 = in[n-2]; out[n-1] = 2.0 * n * in[n] * span; out[n-2] = 2.0 * (n-1) * temp1 * span; for (size_t j = n-3; j>0; j--) { temp1 = in[j]; out[j] = out[j+2] + 2.0 * (j+1) * temp2 * span; temp2 = temp1; } out[0] = 0.5 * out[2] + temp2 * span; out[n] = 0.0; } /// as \f$T_n(\cos\theta)=\cos n\theta\f$, then /// /// \f[ /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}=\frac2{c_n}T_n(x) /// \quad(n>=0) /// \f] /// /// From boundary conditions and Chebyshev polynomials traits \f$T_n(\pm1)=(\pm1)^n\f$ we derive /// \f{alignat}{{3} /// \sum^N_{p=0 \quad p\equiv0\pmod2} a_{mp} &= /// \sum^N_{p=1 \quad p\equiv1\pmod2} a_{mp} &= 0 && /// \qquad 0\le m\le M\\ /// \sum^N_{q=0 \quad q\equiv0\pmod2} a_{qn} &= /// \sum^N_{q=1 \quad q\equiv1\pmod2} a_{qn} &= 0 && /// \qquad 0\le n\le N /// \f} void homogeneous_boundary(size_t m, size_t n, Eigen::Ref<RowMatrixXd> in, Eigen::Ref<RowMatrixXd> out) { if (out != in) { out = in; } double evens, odds; for (size_t i=0; i<=m-2; ++i) { evens = odds = 0.0; for (size_t j=1; j<=n-2; j+=2) { odds -= out(i, j); evens -= out(i, j+1); } out(i, n-1) = odds; out(i, n) = evens - out(i, 0); } for (size_t i=0; i<=n-2; ++i) { evens = odds = 0.0; for (size_t j=1; j<m-2; j+=2) { odds -= out(j, i); evens -= out(j+1, i); } out(m-1, i) = odds; out(m, i) = evens - out(0, i); } evens = odds = 0.0; for (size_t j=1; j<n-2; j+=2) { odds -= out(m-1, j); evens -= out(m-1, j+1); } out(m-1, n-1) = odds; out(m-1, n) = evens - out(n-1, 0); evens = odds = 0.0; for (size_t i=0; i<m; i+=2) { odds -= out(i, n-1); evens -= out(i, n); } out(m, n-1) = odds; out(m, n) = evens; } void second_derivative(size_t m, size_t n, Eigen::Ref<RowMatrixXd> in, Eigen::Ref<RowMatrixXd> out) { homogeneous_boundary(m, n, in, out); for (size_t i = 0; i <= m; ++i) { spectral_differentiate(n, out.row(i), out.row(i)); spectral_differentiate(n, out.row(i), out.row(i)); } } } // namespace CS <|endoftext|>