text
stringlengths
54
60.6k
<commit_before>c9c45645-4b02-11e5-8fba-28cfe9171a43<commit_msg>#BUG723 uncommitted code found on my computer Monday morning<commit_after>c9d3d966-4b02-11e5-aa18-28cfe9171a43<|endoftext|>
<commit_before>9957cf6e-2e4f-11e5-95eb-28cfe91dbc4b<commit_msg>995e5e66-2e4f-11e5-80f5-28cfe91dbc4b<commit_after>995e5e66-2e4f-11e5-80f5-28cfe91dbc4b<|endoftext|>
<commit_before>633ef4c6-5216-11e5-9811-6c40088e03e4<commit_msg>634671f4-5216-11e5-8e22-6c40088e03e4<commit_after>634671f4-5216-11e5-8e22-6c40088e03e4<|endoftext|>
<commit_before>985bcc19-327f-11e5-af0e-9cf387a8033e<commit_msg>9861c56e-327f-11e5-96b2-9cf387a8033e<commit_after>9861c56e-327f-11e5-96b2-9cf387a8033e<|endoftext|>
<commit_before>75e59f8c-2749-11e6-bf71-e0f84713e7b8<commit_msg>I'm done<commit_after>75f309bd-2749-11e6-995d-e0f84713e7b8<|endoftext|>
<commit_before>#include <iostream> #include <string> #include "Generator.h" using namespace std; int main(){ string input; Generator gen; cout << "Schrijf een woord: "; cin >> input; gen.setString(input); cout << "'" << input << "' " << "in pepekestaal is: '" << gen.getPPConversion() << "'" <<endl; return 0; }<commit_msg>added full sentence support<commit_after>#include <iostream> #include <string> #include "Generator.h" using namespace std; int main(){ string input; Generator gen; cout << "Schrijf een woord: "; getline(cin, input); gen.setString(input); cout << "'" << input << "' " << "in pepekestaal is: '" << gen.getPPConversion() << "'" <<endl; return 0; }<|endoftext|>
<commit_before>320e1147-2d3e-11e5-814c-c82a142b6f9b<commit_msg>32ccdae1-2d3e-11e5-93b8-c82a142b6f9b<commit_after>32ccdae1-2d3e-11e5-93b8-c82a142b6f9b<|endoftext|>
<commit_before>7bb16014-5216-11e5-998f-6c40088e03e4<commit_msg>7bb7f136-5216-11e5-8b66-6c40088e03e4<commit_after>7bb7f136-5216-11e5-8b66-6c40088e03e4<|endoftext|>
<commit_before>781de734-2d53-11e5-baeb-247703a38240<commit_msg>781e6308-2d53-11e5-baeb-247703a38240<commit_after>781e6308-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>75d3e442-2d53-11e5-baeb-247703a38240<commit_msg>75d467be-2d53-11e5-baeb-247703a38240<commit_after>75d467be-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>d7485568-313a-11e5-aefa-3c15c2e10482<commit_msg>d74de582-313a-11e5-8a37-3c15c2e10482<commit_after>d74de582-313a-11e5-8a37-3c15c2e10482<|endoftext|>
<commit_before>78d18b9a-2d53-11e5-baeb-247703a38240<commit_msg>78d20d68-2d53-11e5-baeb-247703a38240<commit_after>78d20d68-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>7904cde6-2e4f-11e5-a5f0-28cfe91dbc4b<commit_msg>790b8670-2e4f-11e5-9d43-28cfe91dbc4b<commit_after>790b8670-2e4f-11e5-9d43-28cfe91dbc4b<|endoftext|>
<commit_before>a6f6fce6-ad5b-11e7-a6d0-ac87a332f658<commit_msg>roselyn broke it<commit_after>a7b41cae-ad5b-11e7-8c7d-ac87a332f658<|endoftext|>
<commit_before>5d286585-2d16-11e5-af21-0401358ea401<commit_msg>5d286586-2d16-11e5-af21-0401358ea401<commit_after>5d286586-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>add6db21-2e4f-11e5-905d-28cfe91dbc4b<commit_msg>adddbfc7-2e4f-11e5-ad81-28cfe91dbc4b<commit_after>adddbfc7-2e4f-11e5-ad81-28cfe91dbc4b<|endoftext|>
<commit_before>/* * main.cpp * * Created on: 16 nov. 2015 * Author: tinyl */ #include "libraries.h" #include "lib_opencv.h" #include "main_features_detect.hpp" using namespace std; using namespace cv; int main(){ cv::Mat img_original, dst; //dst = cv::imread("/home/tinyl/Images/Rituals/DSC08075.JPG"); //dst = cv::imread("/home/tinyl/Images/groupe3.jpg"); //dst = cv::imread("/home/tinyl/Images/main3.jpg"); //dst = cv::imread("/home/tinyl/Images/cochon.jpg"); //dst = cv::imread("/home/tinyl/Images/test.jpg"); //dst = cv::imread("/home/tinyl/Images/main2.jpg"); dst = cv::imread("/home/tinyl/Images/main1.png"); //dst = cv::imread("/home/tinyl/Images/main.jpg"); //Condition de non lecture if (dst.empty()) { std::cout << "Cannot load image!" << std::endl; return -1; } Size size(1024,768); resize(dst, img_original, size); cv::namedWindow("Original", CV_WINDOW_AUTOSIZE); cv::imshow("Original",img_original); cv::waitKey(0); Mat img_YCbCr; img_YCbCr = Mat::zeros (img_original.rows, img_original.cols, CV_8UC3); cvtColor(img_original,img_YCbCr,CV_RGB2YCrCb); cv::namedWindow("Modified", CV_WINDOW_AUTOSIZE); cv::imshow("Modified",img_YCbCr); cv::waitKey(0); cout << "Valeur YCrCb:" << img_YCbCr.at<Vec3b>(Point(35,90)); cout << endl; cout << "Valeur RGB:" << img_original.at<Vec3b>(Point(35,90)); cout << endl; cout << float(img_YCbCr.at<Vec3b>(Point(35,90))[1])/float(img_YCbCr.at<Vec3b>(Point(35,90))[2]); cout << endl; Mat imdetect; imdetect = Mat::zeros(img_YCbCr.rows, img_YCbCr.cols, CV_8UC3); main_features_detect(img_YCbCr, imdetect); cv::namedWindow("Result", CV_WINDOW_AUTOSIZE); cv::imshow("Result",imdetect); cv::waitKey(0); Mat img_back_RGB; img_back_RGB = Mat::zeros(imdetect.rows, imdetect.cols, CV_8UC3); cvtColor(imdetect,img_back_RGB,CV_YCrCb2RGB); /*cv::namedWindow("back_RGB", CV_WINDOW_AUTOSIZE); cv::imshow("back_RGB",img_back_RGB); cv::waitKey(0); */ Mat img_gray; img_gray = Mat::zeros(imdetect.rows, imdetect.cols, CV_8UC1); cvtColor(img_back_RGB,img_gray,CV_RGB2GRAY); /*cv::namedWindow("gray", CV_WINDOW_AUTOSIZE); cv::imshow("gray",img_gray); cv::waitKey(0); */ Mat img_bw; // = img_gray > 128; img_bw = Mat (img_gray.size(),img_gray.type()); threshold(img_gray, img_bw, 100, 255, THRESH_BINARY); imwrite("image_bw.jpg", img_bw); cv::namedWindow("Binary Image", CV_WINDOW_AUTOSIZE); cv::imshow("Binary Image",img_bw); cv::waitKey(0); //Creation de l'element structurant Mat elementStruct; elementStruct = Mat::zeros(3,3,CV_8UC3); for (int i = 0; i < 3 ; i ++) { for (int j = 0 ; j < 3 ; j++) { elementStruct.at < Vec3b > (Point(i, j))[0] = 255; elementStruct.at < Vec3b > (Point(i, j))[1] = 255; elementStruct.at < Vec3b > (Point(i, j))[2] = 255; } } Mat elt_gris; elt_gris = Mat::zeros(elementStruct.rows, elementStruct.cols, CV_8UC1); cvtColor(elementStruct,elt_gris,CV_RGB2GRAY); Mat elt_bw; // = img_gray > 128; elt_bw = Mat(elt_gris.size(),elt_gris.type()); threshold(elt_gris, elt_bw, 100, 255, THRESH_BINARY); imwrite("element1.jpg", elt_bw); Mat imgMorpho; imgMorpho = Mat(elt_bw.size(),elt_bw.type()); cv::dilate(img_bw,imgMorpho,Mat(),Point(1,1),2,1,1); cv::erode(imgMorpho,imgMorpho,Mat(),Point(1,1),1,1,1); cv::dilate(imgMorpho,imgMorpho,Mat(),Point(1,1),1,1,1); cv::erode(imgMorpho,imgMorpho,Mat(),Point(1,1),2,1,1); imwrite("img_erode.jpg", imgMorpho); /*int scale = 1; int delta = 0; int ddepth = CV_16S; Mat imgx; Mat imgy; cv::Sobel(nouvelleImage,imgx,ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); cv::Sobel(nouvelleImage,imgy,ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( imgx, imgy ); imwrite("imgx.jpg",imgx); imwrite("imgSobel.jpg", imgy);*/ cv::Laplacian(imgMorpho,imgMorpho,CV_8U,3,1,0,BORDER_DEFAULT); convertScaleAbs( imgMorpho, imgMorpho ); cv::dilate(imgMorpho,imgMorpho,Mat(),Point(1,1),2,1,1); cv::erode(imgMorpho,imgMorpho,Mat(),Point(1,1),2,1,1); cv::dilate(imgMorpho,imgMorpho,Mat(),Point(1,1),1,1,1); imwrite("imglaplacien.jpg", imgMorpho); cv::namedWindow("Laplacien", CV_WINDOW_AUTOSIZE); cv::imshow("Laplacien",imgMorpho); cv::waitKey(0); RNG rng(12345); vector<vector<Point> > contours; vector<Vec4i> hierarchy; int area = 2500; findContours( imgMorpho, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) ); vector<vector<Point> > contours_poly( contours.size() ); vector<Rect> boundRect( contours.size() ); vector<Rect> boundRectFiltre( contours.size() ); vector<Point2f>center( contours.size() ); vector<float>radius( contours.size() ); for( size_t i = 0; i < contours.size(); i++ ) { approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true ); boundRect[i] = boundingRect( Mat(contours_poly[i]) ); cout << "Top-left" << boundRect[i].tl() << endl; cout << "Bottom-right" << boundRect[i].br() << endl; if(boundRect[i].width * boundRect[i].height > area){ boundRectFiltre[i] = boundRect[i]; } //minEnclosingCircle( contours_poly[i], center[i], radius[i] ); } Mat drawing = Mat::zeros( imgMorpho.size(), CV_8UC3 ); for( size_t i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours_poly, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() ); rectangle( drawing, boundRectFiltre[i].tl(), boundRectFiltre[i].br(), color, 2, 8, 0 ); //circle( drawing, center[i], (int)radius[i], color, 2, 8, 0 ); } namedWindow( "Contours", WINDOW_AUTOSIZE ); imshow( "Contours", drawing ); waitKey(0); /* /// Separate the image in 3 places ( B, G and R ) vector<Mat> bgr_planes; split( img_YCbCr, bgr_planes ); /// Establish the number of bins int histSize = 256; /// Set the ranges ( for B,G,R) ) float range[] = { 0, 256 } ; const float* histRange = { range }; bool uniform = true; bool accumulate = false; cv::Mat b_hist, g_hist, r_hist; /// Compute the histograms: calcHist( &bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate ); calcHist( &bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate ); calcHist( &bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate ); // Draw the histograms for B, G and R int hist_w = 512; int hist_h = 400; int bin_w = cvRound( (double) hist_w/histSize ); Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) ); /// Normalize the result to [ 0, histImage.rows ] normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() ); normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() ); normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() ); /// Draw for each channel for( int i = 1; i < histSize; i++ ) { line( histImage, Point( bin_w*(i-1), hist_h - cvRound(b_hist.at<float>(i-1)) ) , Point( bin_w*(i), hist_h - cvRound(b_hist.at<float>(i)) ), Scalar( 255, 0, 0), 2, 8, 0 ); line( histImage, Point( bin_w*(i-1), hist_h - cvRound(g_hist.at<float>(i-1)) ) , Point( bin_w*(i), hist_h - cvRound(g_hist.at<float>(i)) ), Scalar( 0, 255, 0), 2, 8, 0 ); line( histImage, Point( bin_w*(i-1), hist_h - cvRound(r_hist.at<float>(i-1)) ) , Point( bin_w*(i), hist_h - cvRound(r_hist.at<float>(i)) ), Scalar( 0, 0, 255), 2, 8, 0 ); } /// Display namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE ); imshow("calcHist Demo", histImage ); waitKey(0); return 0; */ } <commit_msg>[Emilie] INTER: removing small areas and extracting sub-images<commit_after>/* * main.cpp * * Created on: 16 nov. 2015 * Author: tinyl */ #include "libraries.h" #include "lib_opencv.h" #include "main_features_detect.hpp" using namespace std; using namespace cv; int main(){ cv::Mat img_original, dst; //dst = cv::imread("/home/tinyl/Images/Rituals/DSC08075.JPG"); //dst = cv::imread("/home/tinyl/Images/groupe3.jpg"); //dst = cv::imread("/home/tinyl/Images/main3.jpg"); //dst = cv::imread("/home/tinyl/Images/cochon.jpg"); //dst = cv::imread("/home/tinyl/Images/test.jpg"); dst = cv::imread("/home/tinyl/Images/main2.jpg"); //dst = cv::imread("/home/tinyl/Images/main1.png"); //dst = cv::imread("/home/tinyl/Images/main.jpg"); //Condition de non lecture if (dst.empty()) { std::cout << "Cannot load image!" << std::endl; return -1; } Size size(1024,768); resize(dst, img_original, size); cv::namedWindow("Original", CV_WINDOW_AUTOSIZE); cv::imshow("Original",img_original); cv::waitKey(0); Mat img_YCbCr; img_YCbCr = Mat::zeros (img_original.rows, img_original.cols, CV_8UC3); cvtColor(img_original,img_YCbCr,CV_RGB2YCrCb); cv::namedWindow("Modified", CV_WINDOW_AUTOSIZE); cv::imshow("Modified",img_YCbCr); cv::waitKey(0); cout << "Valeur YCrCb:" << img_YCbCr.at<Vec3b>(Point(35,90)); cout << endl; cout << "Valeur RGB:" << img_original.at<Vec3b>(Point(35,90)); cout << endl; cout << float(img_YCbCr.at<Vec3b>(Point(35,90))[1])/float(img_YCbCr.at<Vec3b>(Point(35,90))[2]); cout << endl; Mat imdetect; imdetect = Mat::zeros(img_YCbCr.rows, img_YCbCr.cols, CV_8UC3); main_features_detect(img_YCbCr, imdetect); cv::namedWindow("Result", CV_WINDOW_AUTOSIZE); cv::imshow("Result",imdetect); cv::waitKey(0); Mat img_back_RGB; img_back_RGB = Mat::zeros(imdetect.rows, imdetect.cols, CV_8UC3); cvtColor(imdetect,img_back_RGB,CV_YCrCb2RGB); /*cv::namedWindow("back_RGB", CV_WINDOW_AUTOSIZE); cv::imshow("back_RGB",img_back_RGB); cv::waitKey(0); */ Mat img_gray; img_gray = Mat::zeros(imdetect.rows, imdetect.cols, CV_8UC1); cvtColor(img_back_RGB,img_gray,CV_RGB2GRAY); /*cv::namedWindow("gray", CV_WINDOW_AUTOSIZE); cv::imshow("gray",img_gray); cv::waitKey(0); */ Mat img_bw; // = img_gray > 128; img_bw = Mat (img_gray.size(),img_gray.type()); threshold(img_gray, img_bw, 100, 255, THRESH_BINARY); imwrite("image_bw.jpg", img_bw); cv::namedWindow("Binary Image", CV_WINDOW_AUTOSIZE); cv::imshow("Binary Image",img_bw); cv::waitKey(0); //Creation de l'element structurant Mat elementStruct; elementStruct = Mat::zeros(3,3,CV_8UC3); for (int i = 0; i < 3 ; i ++) { for (int j = 0 ; j < 3 ; j++) { elementStruct.at < Vec3b > (Point(i, j))[0] = 255; elementStruct.at < Vec3b > (Point(i, j))[1] = 255; elementStruct.at < Vec3b > (Point(i, j))[2] = 255; } } Mat elt_gris; elt_gris = Mat::zeros(elementStruct.rows, elementStruct.cols, CV_8UC1); cvtColor(elementStruct,elt_gris,CV_RGB2GRAY); Mat elt_bw; // = img_gray > 128; elt_bw = Mat(elt_gris.size(),elt_gris.type()); threshold(elt_gris, elt_bw, 100, 255, THRESH_BINARY); imwrite("element1.jpg", elt_bw); Mat imgMorpho; imgMorpho = Mat(elt_bw.size(),elt_bw.type()); cv::dilate(img_bw,imgMorpho,Mat(),Point(1,1),2,1,1); cv::erode(imgMorpho,imgMorpho,Mat(),Point(1,1),1,1,1); cv::dilate(imgMorpho,imgMorpho,Mat(),Point(1,1),1,1,1); cv::erode(imgMorpho,imgMorpho,Mat(),Point(1,1),2,1,1); imwrite("img_erode.jpg", imgMorpho); /*int scale = 1; int delta = 0; int ddepth = CV_16S; Mat imgx; Mat imgy; cv::Sobel(nouvelleImage,imgx,ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); cv::Sobel(nouvelleImage,imgy,ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); convertScaleAbs( imgx, imgy ); imwrite("imgx.jpg",imgx); imwrite("imgSobel.jpg", imgy);*/ cv::Laplacian(imgMorpho,imgMorpho,CV_8U,3,1,0,BORDER_DEFAULT); convertScaleAbs( imgMorpho, imgMorpho ); cv::dilate(imgMorpho,imgMorpho,Mat(),Point(1,1),2,1,1); cv::erode(imgMorpho,imgMorpho,Mat(),Point(1,1),2,1,1); cv::dilate(imgMorpho,imgMorpho,Mat(),Point(1,1),1,1,1); imwrite("imglaplacien.jpg", imgMorpho); cv::namedWindow("Laplacien", CV_WINDOW_AUTOSIZE); cv::imshow("Laplacien",imgMorpho); cv::waitKey(0); RNG rng(12345); vector<vector<Point> > contours; vector<Vec4i> hierarchy; int area = 2500; findContours( imgMorpho, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) ); vector<vector<Point> > contours_poly( contours.size() ); vector<Rect> boundRect( contours.size() ); vector<Rect> boundRectFiltre( contours.size() ); vector<Point2f>center( contours.size() ); vector<float>radius( contours.size() ); for( size_t i = 0; i < contours.size(); i++ ) { approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true ); boundRect[i] = boundingRect( Mat(contours_poly[i]) ); cout << "Top-left" << boundRect[i].tl() << endl; cout << "Bottom-right" << boundRect[i].br() << endl; //if(boundRect[i].width * boundRect[i].height > area){ //boundRectFiltre[i] = boundRect[i]; //} //minEnclosingCircle( contours_poly[i], center[i], radius[i] ); } Mat drawing = Mat::zeros( imgMorpho.size(), CV_8UC3 ); /*for( size_t i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours_poly, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() ); rectangle( drawing, boundRectFiltre[i].tl(), boundRectFiltre[i].br(), color, 2, 8, 0 ); //circle( drawing, center[i], (int)radius[i], color, 2, 8, 0 ); } namedWindow( "Contours", WINDOW_AUTOSIZE ); imshow( "Contours", drawing ); waitKey(0);*/ /* int m1 = boundRect[0].tl().x; int n1 = boundRect[0].tl().y; int m2 = boundRect[0].br().x; int n2 = boundRect[0].br().y; cout << m1 << endl; cout << m2 << endl; cout << n1 << endl; cout << n2 << endl; */ int boolean = 1; std::vector<Mat*> vImage; for( size_t i = 0; i< contours.size(); i++ ) { boolean = 1; int x1 = boundRect[i].tl().x; int y1 = boundRect[i].tl().y; int x2 = boundRect[i].br().x; int y2 = boundRect[i].br().y; int aire = (x2 - x1)*(y2 - y1); //cout << aire << endl; if (aire > 500) { for (size_t j=0 ; j < contours.size() ; j++) { int tempx1 = boundRect[j].tl().x; int tempy1 = boundRect[j].tl().y; int tempx2 = boundRect[j].br().x; int tempy2 = boundRect[j].br().y; if (x1 > tempx1 && x2 < tempx2 && y1 > tempy1 && y2 < tempy2 ) { boolean = 0; } } if (boolean == 1) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours_poly, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() ); rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 ); int l = x2 - x1; int h = y2 - y1; Mat* image = new Mat(); *image = Mat::zeros(l,h, THRESH_BINARY); for (int x = 1 ; x < l-1 ; x++){ for (int y = 1 ; y < h-1 ; y++){ image->at < Vec3b > (Point(x, y)) = imgMorpho.at < Vec3b > (Point(x+x1, y+y1)); } } vImage.push_back(image); } } } imwrite("imgrogner.jpg", drawing); cv::namedWindow("Rognagne", CV_WINDOW_AUTOSIZE); cv::imshow("Rognagne",drawing); cv::waitKey(0); /* /// Separate the image in 3 places ( B, G and R ) vector<Mat> bgr_planes; split( img_YCbCr, bgr_planes ); /// Establish the number of bins int histSize = 256; /// Set the ranges ( for B,G,R) ) float range[] = { 0, 256 } ; const float* histRange = { range }; bool uniform = true; bool accumulate = false; cv::Mat b_hist, g_hist, r_hist; /// Compute the histograms: calcHist( &bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate ); calcHist( &bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate ); calcHist( &bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate ); // Draw the histograms for B, G and R int hist_w = 512; int hist_h = 400; int bin_w = cvRound( (double) hist_w/histSize ); Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) ); /// Normalize the result to [ 0, histImage.rows ] normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() ); normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() ); normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() ); /// Draw for each channel for( int i = 1; i < histSize; i++ ) { line( histImage, Point( bin_w*(i-1), hist_h - cvRound(b_hist.at<float>(i-1)) ) , Point( bin_w*(i), hist_h - cvRound(b_hist.at<float>(i)) ), Scalar( 255, 0, 0), 2, 8, 0 ); line( histImage, Point( bin_w*(i-1), hist_h - cvRound(g_hist.at<float>(i-1)) ) , Point( bin_w*(i), hist_h - cvRound(g_hist.at<float>(i)) ), Scalar( 0, 255, 0), 2, 8, 0 ); line( histImage, Point( bin_w*(i-1), hist_h - cvRound(r_hist.at<float>(i-1)) ) , Point( bin_w*(i), hist_h - cvRound(r_hist.at<float>(i)) ), Scalar( 0, 0, 255), 2, 8, 0 ); } /// Display namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE ); imshow("calcHist Demo", histImage ); waitKey(0); return 0; */ } <|endoftext|>
<commit_before>c23a7d3d-2d3d-11e5-b373-c82a142b6f9b<commit_msg>c28e6521-2d3d-11e5-8166-c82a142b6f9b<commit_after>c28e6521-2d3d-11e5-8166-c82a142b6f9b<|endoftext|>
<commit_before>7aac2a64-5216-11e5-aa9e-6c40088e03e4<commit_msg>7ab2c21e-5216-11e5-9068-6c40088e03e4<commit_after>7ab2c21e-5216-11e5-9068-6c40088e03e4<|endoftext|>
<commit_before>8c3d20ff-2d14-11e5-af21-0401358ea401<commit_msg>8c3d2100-2d14-11e5-af21-0401358ea401<commit_after>8c3d2100-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>b84e3370-35ca-11e5-b0ad-6c40088e03e4<commit_msg>b854ceb8-35ca-11e5-9c5f-6c40088e03e4<commit_after>b854ceb8-35ca-11e5-9c5f-6c40088e03e4<|endoftext|>
<commit_before>14a567a6-ad5b-11e7-a499-ac87a332f658<commit_msg>OKAY this time it should work<commit_after>15583a17-ad5b-11e7-a403-ac87a332f658<|endoftext|>
<commit_before>#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <stdarg.h> #include <getopt.h> #include <ctype.h> #include <limits.h> #include <archive.h> #include <archive_entry.h> #include "main.h" static int LogLevel = Message; static const char *arg0 = 0; unsigned int opt_verbosity = 0; enum { RESET = 0, BOLD = 1, BLACK = 30, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, GRAY, WHITE = GRAY }; void log(int level, const char *msg, ...) { if (level < LogLevel) return; FILE *out = (level <= Message) ? stdout : stderr; if (level == Message) { if (isatty(fileno(out))) { fprintf(out, "\033[%d;%dm***\033[0;0m ", BOLD, GREEN); } else fprintf(out, "*** "); } va_list ap; va_start(ap, msg); vfprintf(out, msg, ap); va_end(ap); } static struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, -'v' }, { "db", required_argument, 0, 'd' }, { "install", no_argument, 0, 'i' }, { "dry", no_argument, 0, -'d' }, { "remove", no_argument, 0, 'r' }, { "info", no_argument, 0, 'I' }, { "list", no_argument, 0, 'L' }, { "missing", no_argument, 0, 'M' }, { "found", no_argument, 0, 'F' }, { "pkgs", no_argument, 0, 'P' }, { "verbose", no_argument, 0, 'v' }, { "rename", required_argument, 0, 'n' }, { "ld-append", required_argument, 0, -'A' }, { "ld-prepend", required_argument, 0, -'P' }, { "ld-delete", required_argument, 0, -'D' }, { "ld-insert", required_argument, 0, -'I' }, { "ld-clear", no_argument, 0, -'C' }, { "relink", no_argument, 0, -'R' }, { "json", no_argument, 0, -'J' }, { 0, 0, 0, 0 } }; static void help(int x) { FILE *out = x ? stderr : stdout; fprintf(out, "usage: %s [options] packages...\n", arg0); fprintf(out, "options:\n" " -h, --help show this message\n" " --version show version info\n" " -v, --verbose print more information\n" ); fprintf(out, "db management options:\n" " -d, --db=FILE set the database file to commit to\n" " -i, --install install packages to a dependency db\n" " -r, --remove remove packages from the database\n" " --dry do not commit the changes to the db\n" ); fprintf(out, "db query options:\n" " -I, --info show general information about the db\n" " -L, --list list packages and object files\n" " -M, --missing show the 'missing' table\n" " -F, --found show the 'found' table\n" " -P, --pkgs show the installed packages\n" " -n, --rename=NAME rename the database\n" ); fprintf(out, "db library path options: (run --relink after these changes)\n" " --ld-prepend=DIR add or move a directory to the\n" " top of the trusted library path\n" " --ld-append=DIR add or move a directory to the\n" " bottom of the trusted library path\n" " --ld-delete=DIR remove a library path\n" " --ld-insert=N:DIR add or move a directro to position N\n" " of the trusted library path\n" " --ld-clear remove all library paths\n" " --relink relink all objects\n" ); exit(x); } static void version(int x) { printf("pkgdepdb " FULL_VERSION_STRING "\n"); exit(x); } // don't ask class ArgArg { public: bool on; bool *mode; std::vector<std::string> arg; ArgArg(bool *om) { mode = om; on = false; } operator bool() const { return on; } inline bool operator!() const { return !on; } inline void operator=(bool on) { this->on = on; } inline void operator=(const char *arg) { on = true; this->arg.push_back(arg); } inline void operator=(std::string &&arg) { on = true; this->arg.push_back(std::move(arg)); } }; bool db_store_json(DB *db, const std::string& filename); int main(int argc, char **argv) { arg0 = argv[0]; if (argc < 2) help(1); std::string dbfile, newname; bool do_install = false; bool do_delete = false; bool has_db = false; bool modified = false; bool show_info = false; bool show_list = false; bool show_missing = false; bool show_found = false; bool show_packages = false; bool do_rename = false; bool do_relink = false; bool dryrun = false; bool use_json = false; bool oldmode = true; // library path options ArgArg ld_append (&oldmode), ld_prepend(&oldmode), ld_delete (&oldmode), ld_clear (&oldmode); std::vector<std::tuple<std::string,size_t>> ld_insert; for (;;) { int opt_index = 0; int c = getopt_long(argc, argv, "hird:ILMFPvn:", long_opts, &opt_index); if (c == -1) break; switch (c) { case 'h': help(0); break; case -'v': version(0); break; case 'd': oldmode = false; has_db = true; dbfile = optarg; break; case 'n': oldmode = false; do_rename = true; newname = optarg; break; case -'d': dryrun = true; break; case 'v': ++opt_verbosity; break; case 'i': oldmode = false; do_install = true; break; case 'r': oldmode = false; do_delete = true; break; case 'I': oldmode = false; show_info = true; break; case 'L': oldmode = false; show_list = true; break; case 'M': oldmode = false; show_missing = true; break; case 'F': oldmode = false; show_found = true; break; case 'P': oldmode = false; show_packages = true; break; case -'R': oldmode = false; do_relink = true; break; case -'A': ld_append = optarg; break; case -'P': ld_prepend = optarg; break; case -'D': ld_delete = optarg; break; case -'C': ld_clear = true; break; case -'I': { oldmode = false; std::string str(optarg); if (!isdigit(str[0])) { log(Error, "--ld-insert format wrong: has to start with a number\n"); help(1); return 1; } size_t colon = str.find_first_of(':'); if (std::string::npos == colon) { log(Error, "--ld-insert format wrong, no colon found\n"); help(1); return 1; } ld_insert.push_back(std::make_tuple(std::move(str.substr(colon+1)), strtoul(str.c_str(), nullptr, 0))); break; } case -'J': use_json = true; break; case ':': case '?': help(1); break; } } if (do_install && do_delete) { log(Error, "--install and --remove are mutually exclusive\n"); help(1); } if (do_delete && optind >= argc) { log(Error, "--remove requires a list of package names\n"); help(1); } if (do_install && optind >= argc) { log(Error, "--install requires a list of package archive files\n"); help(1); } std::vector<Package*> packages; if (oldmode) { // non-database mode! while (optind < argc) { Package *package = Package::open(argv[optind++]); for (auto &obj : package->objects) { const char *objdir = obj->dirname.c_str(); const char *objname = obj->basename.c_str(); for (auto &need : obj->needed) { printf("%s : %s/%s NEEDS %s\n", package->name.c_str(), objdir, objname, need.c_str()); } } delete package; } return 0; } if (!do_delete && optind < argc) { if (do_install) log(Message, "loading packages...\n"); while (optind < argc) { if (do_install) log(Print, " %s\n", argv[optind]); Package *package = Package::open(argv[optind]); if (!package) log(Error, "error reading package %s\n", argv[optind]); else { if (do_install) packages.push_back(package); else { package->show_needed(); delete package; } } ++optind; } if (do_install) log(Message, "packages loaded...\n"); } std::unique_ptr<DB> db(new DB); if (has_db) { if (!db->read(dbfile)) { log(Error, "failed to read database\n"); return 1; } } if (do_rename) { modified = true; db->name = newname; } if (ld_append) { for (auto &dir : ld_append.arg) modified = db->ld_append(dir) || modified; } if (ld_prepend) { for (auto &dir : ld_prepend.arg) modified = db->ld_prepend(dir) || modified; } if (ld_delete) { for (auto &dir : ld_delete.arg) modified = db->ld_delete(dir) || modified; } for (auto &ins : ld_insert) { modified = db->ld_insert(std::get<0>(ins), std::get<1>(ins)) || modified; } if (ld_clear) modified = db->ld_clear() || modified; if (do_install && packages.size()) { log(Message, "installing packages\n"); for (auto pkg : packages) { modified = true; if (!db->install_package(std::move(pkg))) { printf("failed to commit package %s to database\n", pkg->name.c_str()); break; } } } if (do_delete) { while (optind < argc) { log(Message, "uninstalling: %s\n", argv[optind]); modified = true; if (!db->delete_package(argv[optind])) { log(Error, "error uninstalling package: %s\n", argv[optind]); return 1; } ++optind; } } if (do_relink) { modified = true; db->relink_all(); } if (show_info) db->show_info(); if (show_packages) db->show_packages(); if (show_list) db->show_objects(); if (show_missing) db->show_missing(); if (show_found) db->show_found(); if (!dryrun && modified && has_db) { if (use_json) db_store_json(db.get(), dbfile); else if (!db->store(dbfile)) log(Error, "failed to write to the database\n"); } return 0; } <commit_msg>--relink now shows a message when it starts...<commit_after>#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <stdarg.h> #include <getopt.h> #include <ctype.h> #include <limits.h> #include <archive.h> #include <archive_entry.h> #include "main.h" static int LogLevel = Message; static const char *arg0 = 0; unsigned int opt_verbosity = 0; enum { RESET = 0, BOLD = 1, BLACK = 30, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, GRAY, WHITE = GRAY }; void log(int level, const char *msg, ...) { if (level < LogLevel) return; FILE *out = (level <= Message) ? stdout : stderr; if (level == Message) { if (isatty(fileno(out))) { fprintf(out, "\033[%d;%dm***\033[0;0m ", BOLD, GREEN); } else fprintf(out, "*** "); } va_list ap; va_start(ap, msg); vfprintf(out, msg, ap); va_end(ap); } static struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, -'v' }, { "db", required_argument, 0, 'd' }, { "install", no_argument, 0, 'i' }, { "dry", no_argument, 0, -'d' }, { "remove", no_argument, 0, 'r' }, { "info", no_argument, 0, 'I' }, { "list", no_argument, 0, 'L' }, { "missing", no_argument, 0, 'M' }, { "found", no_argument, 0, 'F' }, { "pkgs", no_argument, 0, 'P' }, { "verbose", no_argument, 0, 'v' }, { "rename", required_argument, 0, 'n' }, { "ld-append", required_argument, 0, -'A' }, { "ld-prepend", required_argument, 0, -'P' }, { "ld-delete", required_argument, 0, -'D' }, { "ld-insert", required_argument, 0, -'I' }, { "ld-clear", no_argument, 0, -'C' }, { "relink", no_argument, 0, -'R' }, { "json", no_argument, 0, -'J' }, { 0, 0, 0, 0 } }; static void help(int x) { FILE *out = x ? stderr : stdout; fprintf(out, "usage: %s [options] packages...\n", arg0); fprintf(out, "options:\n" " -h, --help show this message\n" " --version show version info\n" " -v, --verbose print more information\n" ); fprintf(out, "db management options:\n" " -d, --db=FILE set the database file to commit to\n" " -i, --install install packages to a dependency db\n" " -r, --remove remove packages from the database\n" " --dry do not commit the changes to the db\n" ); fprintf(out, "db query options:\n" " -I, --info show general information about the db\n" " -L, --list list packages and object files\n" " -M, --missing show the 'missing' table\n" " -F, --found show the 'found' table\n" " -P, --pkgs show the installed packages\n" " -n, --rename=NAME rename the database\n" ); fprintf(out, "db library path options: (run --relink after these changes)\n" " --ld-prepend=DIR add or move a directory to the\n" " top of the trusted library path\n" " --ld-append=DIR add or move a directory to the\n" " bottom of the trusted library path\n" " --ld-delete=DIR remove a library path\n" " --ld-insert=N:DIR add or move a directro to position N\n" " of the trusted library path\n" " --ld-clear remove all library paths\n" " --relink relink all objects\n" ); exit(x); } static void version(int x) { printf("pkgdepdb " FULL_VERSION_STRING "\n"); exit(x); } // don't ask class ArgArg { public: bool on; bool *mode; std::vector<std::string> arg; ArgArg(bool *om) { mode = om; on = false; } operator bool() const { return on; } inline bool operator!() const { return !on; } inline void operator=(bool on) { this->on = on; } inline void operator=(const char *arg) { on = true; this->arg.push_back(arg); } inline void operator=(std::string &&arg) { on = true; this->arg.push_back(std::move(arg)); } }; bool db_store_json(DB *db, const std::string& filename); int main(int argc, char **argv) { arg0 = argv[0]; if (argc < 2) help(1); std::string dbfile, newname; bool do_install = false; bool do_delete = false; bool has_db = false; bool modified = false; bool show_info = false; bool show_list = false; bool show_missing = false; bool show_found = false; bool show_packages = false; bool do_rename = false; bool do_relink = false; bool dryrun = false; bool use_json = false; bool oldmode = true; // library path options ArgArg ld_append (&oldmode), ld_prepend(&oldmode), ld_delete (&oldmode), ld_clear (&oldmode); std::vector<std::tuple<std::string,size_t>> ld_insert; for (;;) { int opt_index = 0; int c = getopt_long(argc, argv, "hird:ILMFPvn:", long_opts, &opt_index); if (c == -1) break; switch (c) { case 'h': help(0); break; case -'v': version(0); break; case 'd': oldmode = false; has_db = true; dbfile = optarg; break; case 'n': oldmode = false; do_rename = true; newname = optarg; break; case -'d': dryrun = true; break; case 'v': ++opt_verbosity; break; case 'i': oldmode = false; do_install = true; break; case 'r': oldmode = false; do_delete = true; break; case 'I': oldmode = false; show_info = true; break; case 'L': oldmode = false; show_list = true; break; case 'M': oldmode = false; show_missing = true; break; case 'F': oldmode = false; show_found = true; break; case 'P': oldmode = false; show_packages = true; break; case -'R': oldmode = false; do_relink = true; break; case -'A': ld_append = optarg; break; case -'P': ld_prepend = optarg; break; case -'D': ld_delete = optarg; break; case -'C': ld_clear = true; break; case -'I': { oldmode = false; std::string str(optarg); if (!isdigit(str[0])) { log(Error, "--ld-insert format wrong: has to start with a number\n"); help(1); return 1; } size_t colon = str.find_first_of(':'); if (std::string::npos == colon) { log(Error, "--ld-insert format wrong, no colon found\n"); help(1); return 1; } ld_insert.push_back(std::make_tuple(std::move(str.substr(colon+1)), strtoul(str.c_str(), nullptr, 0))); break; } case -'J': use_json = true; break; case ':': case '?': help(1); break; } } if (do_install && do_delete) { log(Error, "--install and --remove are mutually exclusive\n"); help(1); } if (do_delete && optind >= argc) { log(Error, "--remove requires a list of package names\n"); help(1); } if (do_install && optind >= argc) { log(Error, "--install requires a list of package archive files\n"); help(1); } std::vector<Package*> packages; if (oldmode) { // non-database mode! while (optind < argc) { Package *package = Package::open(argv[optind++]); for (auto &obj : package->objects) { const char *objdir = obj->dirname.c_str(); const char *objname = obj->basename.c_str(); for (auto &need : obj->needed) { printf("%s : %s/%s NEEDS %s\n", package->name.c_str(), objdir, objname, need.c_str()); } } delete package; } return 0; } if (!do_delete && optind < argc) { if (do_install) log(Message, "loading packages...\n"); while (optind < argc) { if (do_install) log(Print, " %s\n", argv[optind]); Package *package = Package::open(argv[optind]); if (!package) log(Error, "error reading package %s\n", argv[optind]); else { if (do_install) packages.push_back(package); else { package->show_needed(); delete package; } } ++optind; } if (do_install) log(Message, "packages loaded...\n"); } std::unique_ptr<DB> db(new DB); if (has_db) { if (!db->read(dbfile)) { log(Error, "failed to read database\n"); return 1; } } if (do_rename) { modified = true; db->name = newname; } if (ld_append) { for (auto &dir : ld_append.arg) modified = db->ld_append(dir) || modified; } if (ld_prepend) { for (auto &dir : ld_prepend.arg) modified = db->ld_prepend(dir) || modified; } if (ld_delete) { for (auto &dir : ld_delete.arg) modified = db->ld_delete(dir) || modified; } for (auto &ins : ld_insert) { modified = db->ld_insert(std::get<0>(ins), std::get<1>(ins)) || modified; } if (ld_clear) modified = db->ld_clear() || modified; if (do_install && packages.size()) { log(Message, "installing packages\n"); for (auto pkg : packages) { modified = true; if (!db->install_package(std::move(pkg))) { printf("failed to commit package %s to database\n", pkg->name.c_str()); break; } } } if (do_delete) { while (optind < argc) { log(Message, "uninstalling: %s\n", argv[optind]); modified = true; if (!db->delete_package(argv[optind])) { log(Error, "error uninstalling package: %s\n", argv[optind]); return 1; } ++optind; } } if (do_relink) { modified = true; log(Message, "relinking everything\n"); db->relink_all(); } if (show_info) db->show_info(); if (show_packages) db->show_packages(); if (show_list) db->show_objects(); if (show_missing) db->show_missing(); if (show_found) db->show_found(); if (!dryrun && modified && has_db) { if (use_json) db_store_json(db.get(), dbfile); else if (!db->store(dbfile)) log(Error, "failed to write to the database\n"); } return 0; } <|endoftext|>
<commit_before>#include "aquila/global.h" #include "aquila/source/generator/SquareGenerator.h" #include "aquila/source/SignalSource.h" #include "aquila/transform/FftFactory.h" #include "aquila/tools/TextPlot.h" #include "aquila/source/WaveFile.h" #include <algorithm> #include <functional> #include <memory> #include <iostream> #include <cstdlib> using namespace std; int main(int argc, char *argv[]) { if (argc < 2) { std::cout << "Usage: main <FILENAME>" << std::endl; return 1; } Aquila::WaveFile wav(argv[1]); std::cout << "Loaded file: " << wav.getFilename() << " (" << wav.getBitsPerSample() << "b)" << std::endl; Aquila::SampleType maxValue = 0, minValue = 0, average = 0; const Aquila::FrequencyType sampleFreq = wav.getSampleFrequency(); const std::size_t SIZE = 4000; const std::size_t END = wav.getSamplesCount(); //220500 //cout << END; const Aquila::FrequencyType f_lp = 500; vector<Aquila::SampleType> chunk; for (std::size_t i =END-SIZE; i< END; ++i) { chunk.push_back(wav.sample(i)); } Aquila::SignalSource data(chunk, sampleFreq); // std::cout << "Maximum sample value: " << maxValue << std::endl; // const Aquila::FrequencyType sampleFreq = 2000; // const Aquila::FrequencyType f1 = 180, f2 = 300; Aquila::TextPlot plt("input wave"); //trap?? //plt.plot(data); /* // input signal parameters Aquila::SquareGenerator generator1(SIZE); generator1.setFrequency(f1).setAmplitude(255).generate(64); ///Aquila::SquareGenerator generator2(SIZE); //generator2.setFrequency(f2).setAmplitude(255).generate(64); auto sum = generator1; // + generator2; Aquila::TextPlot plt("Signal waveform before filtration"); plt.plot(sum);*/ // calculate the FFT //for(auto&x :generator.toArray()) cout<<x; auto fft = Aquila::FftFactory::getFft(SIZE); cout<<"work"; Aquila::SpectrumType spectrum = fft->fft(data.toArray()); plt.setTitle("Signal spectrum before filtration"); //cout << spectrum.size(); int kk = 0; for(auto&x : spectrum){ cout<<x<<endl; kk++; cout << kk; } // plt.plotSpectrum(spectrum); // generate a low-pass filter spectrum Aquila::SpectrumType filterSpectrum(SIZE); for (std::size_t i = 0; i < SIZE; ++i) { if (i < (SIZE * f_lp / sampleFreq)) { // passband filterSpectrum[i] = 1.0; } else { // stopband filterSpectrum[i] = 0.0; } } plt.setTitle("Filter spectrum"); // plt.plotSpectrum(filterSpectrum); // the following call does the multiplication of two spectra // (which is complementary to convolution in time domain) std::transform( std::begin(spectrum), std::end(spectrum), std::begin(filterSpectrum), std::begin(spectrum), [] (Aquila::ComplexType x, Aquila::ComplexType y) { return x * y; } ); plt.setTitle("Signal spectrum after filtration"); // plt.plotSpectrum(spectrum); // Inverse FFT moves us back to time domain double x1[SIZE]; fft->ifft(spectrum, x1); plt.setTitle("Signal waveform after filtration"); //plt.plot(x1, SIZE); return 0; } <commit_msg>peak freq found<commit_after>#include "aquila/global.h" #include "aquila/source/generator/SquareGenerator.h" #include "aquila/source/SignalSource.h" #include "aquila/transform/FftFactory.h" #include "aquila/tools/TextPlot.h" #include "aquila/source/WaveFile.h" #include <algorithm> #include <functional> #include <memory> #include <iostream> #include <cstdlib> using namespace std; void plotSpectrum(Aquila::SpectrumType spectrum, Aquila::FrequencyType sampleFreq) { std::size_t halfLength = spectrum.size() / 2; std::vector<double> absSpectrum(halfLength); double max = 0; int peak_freq = 0; for (std::size_t i = 0; i < halfLength; ++i) { absSpectrum[i] = std::abs(spectrum[i]); //cout << i*(sampleFreq/halfLength)<< " amp " <<absSpectrum[i] << endl; if(absSpectrum[i] > max){ max = absSpectrum[i]; peak_freq = i*(sampleFreq/halfLength)/2; } } cout << "\n\npeak freq for input with sample size: "<< halfLength*2 << " which needs to be pow of 2" <<endl; cout <<peak_freq << " Hz max amp:" << max << endl; //plot(absSpectrum); } int main(int argc, char *argv[]) { if (argc < 2) { std::cout << "Usage: main <FILENAME>" << std::endl; return 1; } Aquila::WaveFile wav(argv[1]); const Aquila::FrequencyType sampleFreq = wav.getSampleFrequency(); const std::size_t SIZE = 64; const std::size_t END = wav.getSamplesCount(); //220500 //cout << END; const Aquila::FrequencyType f_lp = 500; vector<Aquila::SampleType> chunk; for (std::size_t i =END-SIZE; i< END; ++i) { chunk.push_back(wav.sample(i)); } Aquila::SignalSource data(chunk, sampleFreq); // std::cout << "Maximum sample value: " << maxValue << std::endl; // const Aquila::FrequencyType sampleFreq = 2000; // const Aquila::FrequencyType f1 = 180, f2 = 300; Aquila::TextPlot plt("input wave"); auto fft = Aquila::FftFactory::getFft(SIZE); Aquila::SpectrumType spectrum = fft->fft(data.toArray()); plt.setTitle("Signal spectrum before filtration"); plotSpectrum(spectrum, sampleFreq); plt.plotSpectrum(spectrum); // generate a low-pass filter spectrum Aquila::SpectrumType filterSpectrum(SIZE); for (std::size_t i = 0; i < SIZE; ++i) { if (i < (SIZE * f_lp / sampleFreq)) { // passband filterSpectrum[i] = 1.0; } else { // stopband filterSpectrum[i] = 0.0; } } plt.setTitle("Filter spectrum"); // plt.plotSpectrum(filterSpectrum); // the following call does the multiplication of two spectra // (which is complementary to convolution in time domain) std::transform( std::begin(spectrum), std::end(spectrum), std::begin(filterSpectrum), std::begin(spectrum), [] (Aquila::ComplexType x, Aquila::ComplexType y) { return x * y; } ); plt.setTitle("Signal spectrum after filtration"); // plt.plotSpectrum(spectrum); // Inverse FFT moves us back to time domain double x1[SIZE]; fft->ifft(spectrum, x1); plt.setTitle("Signal waveform after filtration"); //plt.plot(x1, SIZE); return 0; } <|endoftext|>
<commit_before>6693cda4-2fa5-11e5-a315-00012e3d3f12<commit_msg>6695f086-2fa5-11e5-81b0-00012e3d3f12<commit_after>6695f086-2fa5-11e5-81b0-00012e3d3f12<|endoftext|>
<commit_before>24d10059-2748-11e6-b74f-e0f84713e7b8<commit_msg>update testing<commit_after>24da58f5-2748-11e6-b906-e0f84713e7b8<|endoftext|>
<commit_before>765cbfa6-2d53-11e5-baeb-247703a38240<commit_msg>765d3cec-2d53-11e5-baeb-247703a38240<commit_after>765d3cec-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>d0b62e82-2e4e-11e5-9d94-28cfe91dbc4b<commit_msg>d0bc9ae1-2e4e-11e5-96b1-28cfe91dbc4b<commit_after>d0bc9ae1-2e4e-11e5-96b1-28cfe91dbc4b<|endoftext|>
<commit_before>5597f334-5216-11e5-9c0f-6c40088e03e4<commit_msg>55a053a6-5216-11e5-a732-6c40088e03e4<commit_after>55a053a6-5216-11e5-a732-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { cout <<"Hello World"<< endl; cout << "test" << endl; } <commit_msg>Delete main.cpp<commit_after><|endoftext|>
<commit_before>c6ef47ba-2e4e-11e5-b16c-28cfe91dbc4b<commit_msg>c6f65759-2e4e-11e5-a35a-28cfe91dbc4b<commit_after>c6f65759-2e4e-11e5-a35a-28cfe91dbc4b<|endoftext|>
<commit_before>f1a3f8fd-2e4e-11e5-bd21-28cfe91dbc4b<commit_msg>f1aa6cc0-2e4e-11e5-82fc-28cfe91dbc4b<commit_after>f1aa6cc0-2e4e-11e5-82fc-28cfe91dbc4b<|endoftext|>
<commit_before>58a39419-2748-11e6-bb9d-e0f84713e7b8<commit_msg>Fix that bug where things didn't work but now they should<commit_after>58b6fecc-2748-11e6-88e9-e0f84713e7b8<|endoftext|>
<commit_before>5ae7ecc1-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ecc2-2d16-11e5-af21-0401358ea401<commit_after>5ae7ecc2-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>4faa5407-2748-11e6-af40-e0f84713e7b8<commit_msg>having coffee<commit_after>4fbb114f-2748-11e6-9f8c-e0f84713e7b8<|endoftext|>
<commit_before>829eb545-2749-11e6-ac2e-e0f84713e7b8<commit_msg>NO CHANGES<commit_after>82adf3f5-2749-11e6-a1e0-e0f84713e7b8<|endoftext|>
<commit_before>b78e61c6-35ca-11e5-b5ca-6c40088e03e4<commit_msg>b794c20a-35ca-11e5-9a46-6c40088e03e4<commit_after>b794c20a-35ca-11e5-9a46-6c40088e03e4<|endoftext|>
<commit_before>c2027082-327f-11e5-ba38-9cf387a8033e<commit_msg>c208db47-327f-11e5-bfae-9cf387a8033e<commit_after>c208db47-327f-11e5-bfae-9cf387a8033e<|endoftext|>
<commit_before>5bf6745e-2d16-11e5-af21-0401358ea401<commit_msg>5bf6745f-2d16-11e5-af21-0401358ea401<commit_after>5bf6745f-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>79a6acb2-2d53-11e5-baeb-247703a38240<commit_msg>79a73024-2d53-11e5-baeb-247703a38240<commit_after>79a73024-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>0f401611-2d3d-11e5-8ca9-c82a142b6f9b<commit_msg>0fb48d59-2d3d-11e5-a4e6-c82a142b6f9b<commit_after>0fb48d59-2d3d-11e5-a4e6-c82a142b6f9b<|endoftext|>
<commit_before>cc289302-4b02-11e5-b699-28cfe9171a43<commit_msg>Typical lynda<commit_after>cc37aa73-4b02-11e5-9614-28cfe9171a43<|endoftext|>
<commit_before>1f9ef30a-ad58-11e7-b89a-ac87a332f658<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>1ff749e1-ad58-11e7-a94f-ac87a332f658<|endoftext|>
<commit_before>a25f8e38-2e4f-11e5-a0b2-28cfe91dbc4b<commit_msg>a2661a47-2e4f-11e5-aeb4-28cfe91dbc4b<commit_after>a2661a47-2e4f-11e5-aeb4-28cfe91dbc4b<|endoftext|>
<commit_before>8a7314d4-35ca-11e5-8985-6c40088e03e4<commit_msg>8a7a0cba-35ca-11e5-96e9-6c40088e03e4<commit_after>8a7a0cba-35ca-11e5-96e9-6c40088e03e4<|endoftext|>
<commit_before>5cd707a4-5216-11e5-bab4-6c40088e03e4<commit_msg>5cde27b4-5216-11e5-85a7-6c40088e03e4<commit_after>5cde27b4-5216-11e5-85a7-6c40088e03e4<|endoftext|>
<commit_before>#include <stdint.h> #include <string.h> #include <FS.h> #include <time.h> #include <TFT_eSPI.h> #include "display.h" #include "dbg.h" // These read 16- and 32-bit types from the SD card file. // BMP data is stored little-endian, Arduino is little-endian too. // May need to reverse subscript order if porting elsewhere. static uint16_t read16(File &f) { uint16_t result; size_t n = f.read((uint8_t *)&result, sizeof(result)); return result; } static uint32_t read32(File &f) { uint32_t result; size_t n = f.read((uint8_t *)&result, sizeof(result)); return result; } // from Adafruit's spitftbitmap ST7735 example int display_bmp(const char *filename, uint8_t x, uint8_t y) { int bmpWidth, bmpHeight; // W+H in pixels uint8_t bmpDepth; // Bit depth (currently must be 24) uint32_t bmpImageoffset; // Start of image data in file uint32_t rowSize; // Not always = bmpWidth; may have padding uint8_t buf[60]; uint8_t buffidx = sizeof(buf); // Current position in buffer boolean flip = true; // BMP is stored bottom-to-top int w, h, row, col; uint8_t r, g, b; uint32_t pos = 0; if((x >= tft.width()) || (y >= tft.height())) return -1; uint32_t startTime = millis(); char fbuf[32]; strcpy(fbuf, "/"); strcat(fbuf, filename); strcat(fbuf, ".bmp"); File f = SPIFFS.open(fbuf, "r"); if (!f) { ERR(print(F("file.open!"))); ERR(print(' ')); ERR(println(filename)); return -1; } // Parse BMP header if (read16(f) != 0x4D42) { ERR(println(F("Unknown BMP signature"))); f.close(); return -1; } uint32_t size = read32(f); DBG(print(F("File size: "))); DBG(println(size)); (void)read32(f); // Read & ignore creator bytes bmpImageoffset = read32(f); // Start of image data DBG(print(F("Image Offset: "))); DBG(println(bmpImageoffset, DEC)); // Read DIB header size = read32(f); DBG(print(F("Header size: "))); DBG(println(size)); bmpWidth = read32(f); bmpHeight = read32(f); if (read16(f) != 1) { ERR(println(F("# planes -- must be '1'"))); f.close(); return -1; } bmpDepth = read16(f); // bits per pixel DBG(print(F("Bit Depth: "))); DBG(println(bmpDepth)); if ((bmpDepth != 24) || (read32(f) != 0)) { // 0 = uncompressed ERR(println(F("BMP format not recognized."))); f.close(); return -1; } DBG(print(F("Image size: "))); DBG(print(bmpWidth)); DBG(print('x')); DBG(println(bmpHeight)); // BMP rows are padded (if needed) to 4-byte boundary rowSize = (bmpWidth * 3 + 3) & ~3; // If bmpHeight is negative, image is in top-down order. // This is not canon but has been observed in the wild. if (bmpHeight < 0) { bmpHeight = -bmpHeight; flip = false; } // Crop area to be loaded w = bmpWidth; h = bmpHeight; if ((x+w-1) >= tft.width()) w = tft.width() - x; if ((y+h-1) >= tft.height()) h = tft.height() - y; // Set TFT address window to clipped image bounds tft.setAddrWindow(x, y, x+w-1, y+h-1); for (row=0; row<h; row++) { // For each scanline... // Seek to start of scan line. It might seem labor- // intensive to be doing this on every line, but this // method covers a lot of gritty details like cropping // and scanline padding. Also, the seek only takes // place if the file position actually needs to change // (avoids a lot of cluster math in SD library). if (flip) // Bitmap is stored bottom-to-top order (normal BMP) pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize; else // Bitmap is stored top-to-bottom pos = bmpImageoffset + row * rowSize; if (f.position() != pos) { // Need seek? f.seek(pos); buffidx = sizeof(buf); // Force buffer reload } for (col=0; col<w; col++) { // For each pixel... // Time to read more pixel data? if (buffidx >= sizeof(buf)) { // Indeed f.read(buf, sizeof(buf)); buffidx = 0; // Set index to beginning } // Convert pixel from BMP to TFT format, push to display b = buf[buffidx++]; g = buf[buffidx++]; r = buf[buffidx++]; tft.pushColor(tft.color565(r, g, b)); } // end pixel } f.close(); DBG(print(F("Loaded in "))); DBG(print(millis() - startTime)); DBG(println(F(" ms"))); return 0; } int centre_text(const char *s, int x, int size) { return x - (strlen(s) * size * 6) / 2; } int right(int n, int x, int size) { return x - n * size * 6; } int val_len(int b) { if (b >= 1000) return 4; if (b >= 100) return 3; if (b >= 10) return 2; if (b >= 0) return 1; if (b > -10) return 2; return 3; } void display_time(time_t &epoch, bool metric) { char buf[32]; strftime(buf, sizeof(buf), metric? "%H:%S": "%I:%S%p", localtime(&epoch)); tft.setCursor(centre_text(buf, tft.width()/2, 1), 109); tft.print(buf); strftime(buf, sizeof(buf), "%a %d", localtime(&epoch)); tft.setCursor(centre_text(buf, tft.width()/2, 1), 118); tft.print(buf); } void display_wind(int wind_degrees, int wind_speed) { // http://www.iquilezles.org/www/articles/sincos/sincos.htm int rad = tft.width()/3, cx = tft.width()/2, cy = 68; const float a = 0.999847695, b = 0.017452406; // wind dir is azimuthal angle with N at 0 float sin = 1.0, cos = 0.0; for (uint16_t i = 0; i < wind_degrees; i++) { const float ns = a*sin + b*cos; const float nc = a*cos - b*sin; cos = nc; sin = ns; } // wind dir rotates clockwise so compensate int ex = cx-rad*cos, ey = cy-rad*sin; tft.fillCircle(ex, ey, 3, TFT_BLACK); tft.drawLine(ex, ey, ex+wind_speed*(cx-ex)/50, ey+wind_speed*(cy-ey)/50, TFT_BLACK); } void display_wind_speed(int wind_speed, const char *wind_dir, bool metric) { tft.setTextSize(2); tft.setCursor(1, 1); tft.print(wind_speed); tft.setTextSize(1); tft.print(metric? F("kph"): F("mph")); tft.setCursor(1, 17); tft.print(wind_dir); } void display_temperature(int temp, int temp_min, bool metric) { tft.setTextSize(2); tft.setCursor(1, tft.height() - 16); tft.print(temp); tft.setTextSize(1); tft.print(metric? 'C': 'F'); if (temp != temp_min) { tft.setCursor(1, tft.height() - 24); tft.print(temp_min); } } void display_humidity(int humidity) { tft.setTextSize(2); tft.setCursor(right(val_len(humidity), tft.width(), 2) - 6, tft.height() - 16); tft.print(humidity); tft.setTextSize(1); tft.setCursor(tft.width() - 6, tft.height() - 16); tft.print('%'); } <commit_msg>bugfix<commit_after>#include <stdint.h> #include <string.h> #include <FS.h> #include <time.h> #include <TFT_eSPI.h> #include "display.h" #include "dbg.h" // These read 16- and 32-bit types from the SD card file. // BMP data is stored little-endian, Arduino is little-endian too. // May need to reverse subscript order if porting elsewhere. static uint16_t read16(File &f) { uint16_t result; size_t n = f.read((uint8_t *)&result, sizeof(result)); return result; } static uint32_t read32(File &f) { uint32_t result; size_t n = f.read((uint8_t *)&result, sizeof(result)); return result; } // from Adafruit's spitftbitmap ST7735 example int display_bmp(const char *filename, uint8_t x, uint8_t y) { int bmpWidth, bmpHeight; // W+H in pixels uint8_t bmpDepth; // Bit depth (currently must be 24) uint32_t bmpImageoffset; // Start of image data in file uint32_t rowSize; // Not always = bmpWidth; may have padding uint8_t buf[60]; uint8_t buffidx = sizeof(buf); // Current position in buffer boolean flip = true; // BMP is stored bottom-to-top int w, h, row, col; uint8_t r, g, b; uint32_t pos = 0; if((x >= tft.width()) || (y >= tft.height())) return -1; uint32_t startTime = millis(); char fbuf[32]; strcpy(fbuf, "/"); strcat(fbuf, filename); strcat(fbuf, ".bmp"); File f = SPIFFS.open(fbuf, "r"); if (!f) { ERR(print(F("file.open!"))); ERR(print(' ')); ERR(println(filename)); return -1; } // Parse BMP header if (read16(f) != 0x4D42) { ERR(println(F("Unknown BMP signature"))); f.close(); return -1; } uint32_t size = read32(f); DBG(print(F("File size: "))); DBG(println(size)); (void)read32(f); // Read & ignore creator bytes bmpImageoffset = read32(f); // Start of image data DBG(print(F("Image Offset: "))); DBG(println(bmpImageoffset, DEC)); // Read DIB header size = read32(f); DBG(print(F("Header size: "))); DBG(println(size)); bmpWidth = read32(f); bmpHeight = read32(f); if (read16(f) != 1) { ERR(println(F("# planes -- must be '1'"))); f.close(); return -1; } bmpDepth = read16(f); // bits per pixel DBG(print(F("Bit Depth: "))); DBG(println(bmpDepth)); if ((bmpDepth != 24) || (read32(f) != 0)) { // 0 = uncompressed ERR(println(F("BMP format not recognized."))); f.close(); return -1; } DBG(print(F("Image size: "))); DBG(print(bmpWidth)); DBG(print('x')); DBG(println(bmpHeight)); // BMP rows are padded (if needed) to 4-byte boundary rowSize = (bmpWidth * 3 + 3) & ~3; // If bmpHeight is negative, image is in top-down order. // This is not canon but has been observed in the wild. if (bmpHeight < 0) { bmpHeight = -bmpHeight; flip = false; } // Crop area to be loaded w = bmpWidth; h = bmpHeight; if ((x+w-1) >= tft.width()) w = tft.width() - x; if ((y+h-1) >= tft.height()) h = tft.height() - y; // Set TFT address window to clipped image bounds tft.setAddrWindow(x, y, x+w-1, y+h-1); for (row=0; row<h; row++) { // For each scanline... // Seek to start of scan line. It might seem labor- // intensive to be doing this on every line, but this // method covers a lot of gritty details like cropping // and scanline padding. Also, the seek only takes // place if the file position actually needs to change // (avoids a lot of cluster math in SD library). if (flip) // Bitmap is stored bottom-to-top order (normal BMP) pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize; else // Bitmap is stored top-to-bottom pos = bmpImageoffset + row * rowSize; if (f.position() != pos) { // Need seek? f.seek(pos); buffidx = sizeof(buf); // Force buffer reload } for (col=0; col<w; col++) { // For each pixel... // Time to read more pixel data? if (buffidx >= sizeof(buf)) { // Indeed f.read(buf, sizeof(buf)); buffidx = 0; // Set index to beginning } // Convert pixel from BMP to TFT format, push to display b = buf[buffidx++]; g = buf[buffidx++]; r = buf[buffidx++]; tft.pushColor(tft.color565(r, g, b)); } // end pixel } f.close(); DBG(print(F("Loaded in "))); DBG(print(millis() - startTime)); DBG(println(F(" ms"))); return 0; } int centre_text(const char *s, int x, int size) { return x - (strlen(s) * size * 6) / 2; } int right(int n, int x, int size) { return x - n * size * 6; } int val_len(int b) { if (b >= 1000) return 4; if (b >= 100) return 3; if (b >= 10) return 2; if (b >= 0) return 1; if (b > -10) return 2; return 3; } void display_time(time_t &epoch, bool metric) { char buf[32]; strftime(buf, sizeof(buf), metric? "%H:%M": "%I:%M%p", localtime(&epoch)); tft.setCursor(centre_text(buf, tft.width()/2, 1), 109); tft.print(buf); strftime(buf, sizeof(buf), "%a %d", localtime(&epoch)); tft.setCursor(centre_text(buf, tft.width()/2, 1), 118); tft.print(buf); } void display_wind(int wind_degrees, int wind_speed) { // http://www.iquilezles.org/www/articles/sincos/sincos.htm int rad = tft.width()/3, cx = tft.width()/2, cy = 68; const float a = 0.999847695, b = 0.017452406; // wind dir is azimuthal angle with N at 0 float sin = 1.0, cos = 0.0; for (uint16_t i = 0; i < wind_degrees; i++) { const float ns = a*sin + b*cos; const float nc = a*cos - b*sin; cos = nc; sin = ns; } // wind dir rotates clockwise so compensate int ex = cx-rad*cos, ey = cy-rad*sin; tft.fillCircle(ex, ey, 3, TFT_BLACK); tft.drawLine(ex, ey, ex+wind_speed*(cx-ex)/50, ey+wind_speed*(cy-ey)/50, TFT_BLACK); } void display_wind_speed(int wind_speed, const char *wind_dir, bool metric) { tft.setTextSize(2); tft.setCursor(1, 1); tft.print(wind_speed); tft.setTextSize(1); tft.print(metric? F("kph"): F("mph")); tft.setCursor(1, 17); tft.print(wind_dir); } void display_temperature(int temp, int temp_min, bool metric) { tft.setTextSize(2); tft.setCursor(1, tft.height() - 16); tft.print(temp); tft.setTextSize(1); tft.print(metric? 'C': 'F'); if (temp != temp_min) { tft.setCursor(1, tft.height() - 24); tft.print(temp_min); } } void display_humidity(int humidity) { tft.setTextSize(2); tft.setCursor(right(val_len(humidity), tft.width(), 2) - 6, tft.height() - 16); tft.print(humidity); tft.setTextSize(1); tft.setCursor(tft.width() - 6, tft.height() - 16); tft.print('%'); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <algorithm> #include <sstream> #include <fstream> #include <vector> #include <unistd.h> #include "gen.hpp" #include "info.hpp" #include "file.hpp" #include "repo.hpp" //Shark package manager //Shamelessy stolen from some stack overflow thread char* getField(char** begin, char** end, const std::string& option) { char** itr = std::find(begin, end, option); if(itr != end && ++itr != end) { return *itr; } return 0; } bool getFlag(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } std::string root; int Install(std::string package); int Untar(std::string tarball); std::string Download(std::string package, std::string ver = ""); int main(int argc, char* argv[]) { //Set the default values root="/"; if(getFlag(argv, argv+argc, "--root")) { root = (std::string)getField(argv, argv+argc, "--root"); if(root[root.size()-1] != '/') { root.append("/"); } std::cout << "Using " << root << " as /\n"; } if(getFlag(argv, argv+argc, "-U")) { return Untar(getField(argv, argv+argc, "-U")); } if(getFlag(argv, argv+argc, "-UI")) { std::string pkg = getField(argv, argv+argc, "-UI"); if(Untar(pkg) != 0) { return 1; } int slash = pkg.find_last_of("/"); if(slash != std::string::npos) { pkg = pkg.substr(slash+1); } int dot = pkg.find(".tar"); if(dot != std::string::npos) { pkg = pkg.substr(0, dot); } return Install(pkg); } if(getFlag(argv, argv+argc, "-I")) { return Install(getField(argv, argv+argc, "-I")); } if(getFlag(argv, argv+argc, "-D")) { if(Download(getField(argv, argv+argc, "-D")) == ""); return 1; } if(getFlag(argv, argv+argc, "-DU")) { std::string pkg = getField(argv, argv+argc, "-DU"); std::string dl = Download(pkg); if(dl == "") { return 1; } return Untar(dl); } if(getFlag(argv, argv+argc, "-DUI")) { std::string pkg = getField(argv, argv+argc, "-DUI"); std::string dl = Download(pkg); if(dl == "") { return 1; } if(Untar(dl) != 0) { return 1; } std::string rm = "rm " + dl; system(rm.c_str()); int dot = dl.find(".tar"); if(dot != std::string::npos) { dl = dl.substr(0, dot); } return Install(dl); } if(getFlag(argv, argv+argc, "--gen-dirs")) { GenDirs(root, getField(argv, argv+argc, "--gen-dirs"), ""); } if(getFlag(argv, argv+argc, "--gen-links")) { GenLinks(root, getField(argv, argv+argc, "--gen-links"), getField(argv, argv+argc, "-p")); } if(getFlag(argv, argv+argc, "--gen-files")) { GenFiles(root, getField(argv, argv+argc, "--gen-files"), ""); } if(getFlag(argv, argv+argc, "--nuke")) { if(root == "/") { std::cout << "ARE YOU CRAZY\n" << "THIS COMMAND DELETES EVERYTHING ON THE ROOT\n" << "DON'T DO THIS\n"; return 1; } std::stringstream nukecmd; nukecmd << "rm -rf " << root << "*"; //std::cout << nukecmd.str() << std::endl; system(nukecmd.str().c_str()); } if(getFlag(argv, argv+argc, "--do-post")) { std::cout << "Doing post scripts\n"; std::ifstream posts; posts.open("/etc/shark/posts"); if(!posts.is_open()) { std::cout << "Error: no post scripts to perform\n"; return 1; } while(posts.good()) { std::string line; std::getline(posts, line); std::stringstream cmd; cmd << "sh /usr/pkg/" << line << "/post"; std::cout << cmd.str() << std::endl; system(cmd.str().c_str()); } posts.close(); } if(getFlag(argv, argv+argc, "-S")) { return Sync(root); } if(getFlag(argv, argv+argc, "-DIR")) { std::vector<std::string> pkgs = GetPkgList(getField(argv, argv+argc, "-DIR"), root); std::cout << "The following packages will be installed\n"; for(int k = 0; k < pkgs.size(); k++) std::cout << pkgs[k] << " "; std::cout << std::endl; std::cin.get(); for(int i = 0; i < pkgs.size(); i++) { if(FileExists(root + "usr/pkg/" + pkgs[i])) continue; std::string dl = Download(pkgs[i]); if(dl == "") { return 1; } if(Untar(dl) != 0) { return 1; } std::string rm = "rm " + dl; system(rm.c_str()); int dot = dl.find(".tar"); if(dot != std::string::npos) { dl = dl.substr(0, dot); } if(Install(dl) != 0) return 1; } } return 0; } int Install(std::string package) { std::cout << "Verifying the package (not really)\n"; std::cout << "Loading the package info\n"; std::stringstream infofile; infofile << root << "usr/pkg/" << package << "/info"; int res; std::map<std::string, std::string> info = LoadInfo(infofile.str(), res); if(res != 0) return res; std::string pkgname = info["PKG_NAME"]; std::string ver = info["PKG_VER"]; std::ifstream checkreinstall; std::stringstream reinstallcheck; reinstallcheck << root << "usr/pkg/" << pkgname; checkreinstall.open(reinstallcheck.str().c_str()); if(checkreinstall.is_open()) { std::map<std::string, std::string> reint = LoadInfo(reinstallcheck.str().c_str(), res); if(ver == reint["PKG_VER"]) { std::cout << "Package " << pkgname << " is already installed. Reinstall?(Y/n)"; char c; std::cin >> c; if(c == 'N' || c == 'n') { std::cout << "Installation aborted\n"; return 1; } } else std::cout << "Upgrading " << pkgname << " to version " << ver << std::endl; checkreinstall.close(); } std::cout << "Loading the file list\n"; std::vector<std::string> filelist; std::ifstream files; std::stringstream filesfile; filesfile << root << "usr/pkg/" << package << "/files"; files.open(filesfile.str().c_str()); if(!files.is_open()) { std::cout << "Error: no file list found. Malformed packge\n"; return 1; } std::string line; while(files.good()) { std::getline(files, line); if(line == "EOF") break; if(line == "") continue; filelist.push_back(line); } files.close(); std::cout << "Looking for conflicts\n"; for(int i = 0; i < filelist.size(); i++) { std::stringstream filename; filename << root << "usr/pkgdb/" << filelist[i]; std::ifstream f; f.open(filename.str().c_str()); if(f.is_open()) { //we are probably conflicting, but make sure std::string pkg; getline(f, pkg); if(pkg != pkgname) { std::cout << "Error: package " << pkgname << " conflicts with " << pkg << " on file " << filename.str() << ".\nInstallation aborted\n"; return 1; } } } std::cout << "Installing package " << package << std::endl; //TODO:load the info file, add it to the package DB //make the directories from dirs std::ifstream dirs; std::stringstream dirsfile; dirsfile << root << "usr/pkg/" << package << "/dirs"; dirs.open(dirsfile.str().c_str()); if(dirs.is_open()) //assume that nothing needs to be made if there is no file { std::string dir; while(dirs.good()) { std::getline(dirs, dir); if(dir == "EOF") break; std::stringstream d; d << "mkdir --parents " << root << dir << " " << root << "usr/pkgdb/" << dir; system(d.str().c_str()); } } //copy any files that need copying for(int i=0; i < filelist.size(); i++) { std::stringstream f; f << "cp -fd " << root << "usr/pkg/" << package << "/" << filelist[i] << " " << root << filelist[i]; //std::cout << f.str() << std::endl; system(f.str().c_str()); //update the package db std::stringstream dbcmd; dbcmd << "echo \"" << pkgname << "\" > " << root << "usr/pkgdb/" << filelist[i]; //std::cout << dbcmd.str() << "\n"; system(dbcmd.str().c_str()); } //install the info file std::stringstream infocmd; infocmd << "cp -fd " << root << "usr/pkg/" << package << "/info " << root << "usr/pkg/" << pkgname; //std::cout << infocmd.str() << std::endl; system(infocmd.str().c_str()); //check for a post script std::stringstream post; post << root << "usr/pkg/" << package << "/post"; if(FileExists(post.str().c_str())) { //check to see if we have a fake root if(root != "/") { std::cout << "This package has a post install script, but you are currently using a fake root. Please chroot into your fake root and run shark --do-post\n"; //add the post script to the posts file std::stringstream posta; posta << "echo " << package << " >> " << root << "/etc/shark/posts"; system(posta.str().c_str()); } else { std::stringstream postcmd; postcmd << "bash " << "/usr/pkg/" << package << "/post"; system(postcmd.str().c_str()); } } files.close(); return 0; } int Untar(std::string tarball) { std::cout << "Extracting tarball\n"; std::stringstream tar; tar << "tar xf " << tarball << " -C "<< root << "usr/pkg"; if(system(tar.str().c_str())) { return 1; } return 0; } std::string Download(std::string package, std::string ver) { std::string version; if(ver == "") { std::cout << "Resolving for latest version\n"; //resolve for latest version std::stringstream infoget; infoget << "curl -s -f -o " << package << " http://neos300.com/astro/pkg/info/" << package; if(system(infoget.str().c_str()) != 0) { std::cout << "Package " << package << " not found\n"; return ""; } int r; std::map<std::string, std::string> newinfo = LoadInfo(package, r); version = newinfo["PKG_VER"]; std::stringstream rm; rm << "rm " << package; system(rm.str().c_str()); } else version = ver; //resolve for the correct repo std::string repo = FindPkg(package, root); int dot; dot = repo.find("."); while(dot != std::string::npos) { repo[dot] = '/'; dot = repo.find("."); } //std::cout << repo << "\n"; //get the package std::cout << "Downloading package\n"; std::stringstream pkgcmd; pkgcmd << "curl -# -f -o " << package << "-" << version << ".tar.xz http://neos300.com/astro/pkg/" << repo << "/" << package << "-" << version << ".tar.xz"; if(system(pkgcmd.str().c_str()) != 0) { std::cout << "Unable to find package tarball for package " << package << "\n"; return ""; } std::cout << "Download successful\n"; std::stringstream ret; ret << package << "-" << version << ".tar.xz"; return ret.str(); } <commit_msg>Added checking to see if a repo can be batch downloaded.<commit_after>#include <iostream> #include <string> #include <algorithm> #include <sstream> #include <fstream> #include <vector> #include <unistd.h> #include "gen.hpp" #include "info.hpp" #include "file.hpp" #include "repo.hpp" //Shark package manager //Shamelessy stolen from some stack overflow thread char* getField(char** begin, char** end, const std::string& option) { char** itr = std::find(begin, end, option); if(itr != end && ++itr != end) { return *itr; } return 0; } bool getFlag(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } std::string root; int Install(std::string package); int Untar(std::string tarball); std::string Download(std::string package, std::string ver = ""); int main(int argc, char* argv[]) { //Set the default values root="/"; if(getFlag(argv, argv+argc, "--root")) { root = (std::string)getField(argv, argv+argc, "--root"); if(root[root.size()-1] != '/') { root.append("/"); } std::cout << "Using " << root << " as /\n"; } if(getFlag(argv, argv+argc, "-U")) { return Untar(getField(argv, argv+argc, "-U")); } if(getFlag(argv, argv+argc, "-UI")) { std::string pkg = getField(argv, argv+argc, "-UI"); if(Untar(pkg) != 0) { return 1; } int slash = pkg.find_last_of("/"); if(slash != std::string::npos) { pkg = pkg.substr(slash+1); } int dot = pkg.find(".tar"); if(dot != std::string::npos) { pkg = pkg.substr(0, dot); } return Install(pkg); } if(getFlag(argv, argv+argc, "-I")) { return Install(getField(argv, argv+argc, "-I")); } if(getFlag(argv, argv+argc, "-D")) { if(Download(getField(argv, argv+argc, "-D")) == ""); return 1; } if(getFlag(argv, argv+argc, "-DU")) { std::string pkg = getField(argv, argv+argc, "-DU"); std::string dl = Download(pkg); if(dl == "") { return 1; } return Untar(dl); } if(getFlag(argv, argv+argc, "-DUI")) { std::string pkg = getField(argv, argv+argc, "-DUI"); std::string dl = Download(pkg); if(dl == "") { return 1; } if(Untar(dl) != 0) { return 1; } std::string rm = "rm " + dl; system(rm.c_str()); int dot = dl.find(".tar"); if(dot != std::string::npos) { dl = dl.substr(0, dot); } return Install(dl); } if(getFlag(argv, argv+argc, "--gen-dirs")) { GenDirs(root, getField(argv, argv+argc, "--gen-dirs"), ""); } if(getFlag(argv, argv+argc, "--gen-links")) { GenLinks(root, getField(argv, argv+argc, "--gen-links"), getField(argv, argv+argc, "-p")); } if(getFlag(argv, argv+argc, "--gen-files")) { GenFiles(root, getField(argv, argv+argc, "--gen-files"), ""); } if(getFlag(argv, argv+argc, "--nuke")) { if(root == "/") { std::cout << "ARE YOU CRAZY\n" << "THIS COMMAND DELETES EVERYTHING ON THE ROOT\n" << "DON'T DO THIS\n"; return 1; } std::stringstream nukecmd; nukecmd << "rm -rf " << root << "*"; //std::cout << nukecmd.str() << std::endl; system(nukecmd.str().c_str()); } if(getFlag(argv, argv+argc, "--do-post")) { std::cout << "Doing post scripts\n"; std::ifstream posts; posts.open("/etc/shark/posts"); if(!posts.is_open()) { std::cout << "Error: no post scripts to perform\n"; return 1; } while(posts.good()) { std::string line; std::getline(posts, line); std::stringstream cmd; cmd << "sh /usr/pkg/" << line << "/post"; std::cout << cmd.str() << std::endl; system(cmd.str().c_str()); } posts.close(); } if(getFlag(argv, argv+argc, "-S")) { return Sync(root); } if(getFlag(argv, argv+argc, "-DIR")) { std::vector<std::string> pkgs = GetPkgList(getField(argv, argv+argc, "-DIR"), root); std::cout << "The following packages will be installed\n"; if(pkgs[0] == "FALSE") { std::cout << "Error: this repo cannot be group installed\n"; return 1; } for(int k = 1; k < pkgs.size(); k++) std::cout << pkgs[k] << " "; std::cout << std::endl; std::cin.get(); for(int i = 0; i < pkgs.size(); i++) { if(FileExists(root + "usr/pkg/" + pkgs[i])) continue; std::string dl = Download(pkgs[i]); if(dl == "") { return 1; } if(Untar(dl) != 0) { return 1; } std::string rm = "rm " + dl; system(rm.c_str()); int dot = dl.find(".tar"); if(dot != std::string::npos) { dl = dl.substr(0, dot); } if(Install(dl) != 0) return 1; } } return 0; } int Install(std::string package) { std::cout << "Verifying the package (not really)\n"; std::cout << "Loading the package info\n"; std::stringstream infofile; infofile << root << "usr/pkg/" << package << "/info"; int res; std::map<std::string, std::string> info = LoadInfo(infofile.str(), res); if(res != 0) return res; std::string pkgname = info["PKG_NAME"]; std::string ver = info["PKG_VER"]; std::ifstream checkreinstall; std::stringstream reinstallcheck; reinstallcheck << root << "usr/pkg/" << pkgname; checkreinstall.open(reinstallcheck.str().c_str()); if(checkreinstall.is_open()) { std::map<std::string, std::string> reint = LoadInfo(reinstallcheck.str().c_str(), res); if(ver == reint["PKG_VER"]) { std::cout << "Package " << pkgname << " is already installed. Reinstall?(Y/n)"; char c; std::cin >> c; if(c == 'N' || c == 'n') { std::cout << "Installation aborted\n"; return 1; } } else std::cout << "Upgrading " << pkgname << " to version " << ver << std::endl; checkreinstall.close(); } std::cout << "Loading the file list\n"; std::vector<std::string> filelist; std::ifstream files; std::stringstream filesfile; filesfile << root << "usr/pkg/" << package << "/files"; files.open(filesfile.str().c_str()); if(!files.is_open()) { std::cout << "Error: no file list found. Malformed packge\n"; return 1; } std::string line; while(files.good()) { std::getline(files, line); if(line == "EOF") break; if(line == "") continue; filelist.push_back(line); } files.close(); std::cout << "Looking for conflicts\n"; for(int i = 0; i < filelist.size(); i++) { std::stringstream filename; filename << root << "usr/pkgdb/" << filelist[i]; std::ifstream f; f.open(filename.str().c_str()); if(f.is_open()) { //we are probably conflicting, but make sure std::string pkg; getline(f, pkg); if(pkg != pkgname) { std::cout << "Error: package " << pkgname << " conflicts with " << pkg << " on file " << filename.str() << ".\nInstallation aborted\n"; return 1; } } } std::cout << "Installing package " << package << std::endl; //TODO:load the info file, add it to the package DB //make the directories from dirs std::ifstream dirs; std::stringstream dirsfile; dirsfile << root << "usr/pkg/" << package << "/dirs"; dirs.open(dirsfile.str().c_str()); if(dirs.is_open()) //assume that nothing needs to be made if there is no file { std::string dir; while(dirs.good()) { std::getline(dirs, dir); if(dir == "EOF") break; std::stringstream d; d << "mkdir --parents " << root << dir << " " << root << "usr/pkgdb/" << dir; system(d.str().c_str()); } } //copy any files that need copying for(int i=0; i < filelist.size(); i++) { std::stringstream f; f << "cp -fd " << root << "usr/pkg/" << package << "/" << filelist[i] << " " << root << filelist[i]; //std::cout << f.str() << std::endl; system(f.str().c_str()); //update the package db std::stringstream dbcmd; dbcmd << "echo \"" << pkgname << "\" > " << root << "usr/pkgdb/" << filelist[i]; //std::cout << dbcmd.str() << "\n"; system(dbcmd.str().c_str()); } //install the info file std::stringstream infocmd; infocmd << "cp -fd " << root << "usr/pkg/" << package << "/info " << root << "usr/pkg/" << pkgname; //std::cout << infocmd.str() << std::endl; system(infocmd.str().c_str()); //check for a post script std::stringstream post; post << root << "usr/pkg/" << package << "/post"; if(FileExists(post.str().c_str())) { //check to see if we have a fake root if(root != "/") { std::cout << "This package has a post install script, but you are currently using a fake root. Please chroot into your fake root and run shark --do-post\n"; //add the post script to the posts file std::stringstream posta; posta << "echo " << package << " >> " << root << "/etc/shark/posts"; system(posta.str().c_str()); } else { std::stringstream postcmd; postcmd << "bash " << "/usr/pkg/" << package << "/post"; system(postcmd.str().c_str()); } } files.close(); return 0; } int Untar(std::string tarball) { std::cout << "Extracting tarball\n"; std::stringstream tar; tar << "tar xf " << tarball << " -C "<< root << "usr/pkg"; if(system(tar.str().c_str())) { return 1; } return 0; } std::string Download(std::string package, std::string ver) { std::string version; if(ver == "") { std::cout << "Resolving for latest version\n"; //resolve for latest version std::stringstream infoget; infoget << "curl -s -f -o " << package << " http://neos300.com/astro/pkg/info/" << package; if(system(infoget.str().c_str()) != 0) { std::cout << "Package " << package << " not found\n"; return ""; } int r; std::map<std::string, std::string> newinfo = LoadInfo(package, r); version = newinfo["PKG_VER"]; std::stringstream rm; rm << "rm " << package; system(rm.str().c_str()); } else version = ver; //resolve for the correct repo std::string repo = FindPkg(package, root); int dot; dot = repo.find("."); while(dot != std::string::npos) { repo[dot] = '/'; dot = repo.find("."); } //std::cout << repo << "\n"; //get the package std::cout << "Downloading package\n"; std::stringstream pkgcmd; pkgcmd << "curl -# -f -o " << package << "-" << version << ".tar.xz http://neos300.com/astro/pkg/" << repo << "/" << package << "-" << version << ".tar.xz"; if(system(pkgcmd.str().c_str()) != 0) { std::cout << "Unable to find package tarball for package " << package << "\n"; return ""; } std::cout << "Download successful\n"; std::stringstream ret; ret << package << "-" << version << ".tar.xz"; return ret.str(); } <|endoftext|>
<commit_before>#include <iostream> #include <memory> #include <fstream> #include <cctype> #include "Game/Game.h" #include "Game/Board.h" #include "Game/Game_Result.h" #include "Players/Genetic_AI.h" #include "Players/Human_Player.h" #include "Players/Random_AI.h" #include "Players/Outside_Player.h" #include "Genes/Gene_Pool.h" #include "Stalemate_Search.h" #include "Exceptions/Illegal_Move_Exception.h" #include "Utility.h" #include "Testing.h" void print_help(); void replay_game(const std::string& file_name, int game_number); int find_last_id(const std::string& filename); int main(int argc, char *argv[]) { try { run_tests(); if(argc > 1) { if(std::string(argv[1]) == "-genepool") { std::string gene_pool_config_file_name; if(argc > 2) { gene_pool_config_file_name = argv[2]; } gene_pool(gene_pool_config_file_name); } else if(std::string(argv[1]) == "-replay") { if(argc > 2) { std::string file_name = argv[2]; int game_number = -1; if(argc > 3) { game_number = std::stoi(argv[3]); } replay_game(file_name, game_number); } else { std::cout << "Provide a file containing a game to replay." << std::endl; return 1; } } else if(std::string(argv[1]) == "-stalemate") { stalemate_search_start(); } else { // Use pointers since each player could be Human, Genetic, Random, etc. std::unique_ptr<Player> white; std::unique_ptr<Player> black; std::unique_ptr<Player> latest; double game_time = 0; size_t moves_per_reset = 0; double increment_time = 0; for(int i = 1; i < argc; ++i) { std::string opt = argv[i]; if(opt == "-human") { latest = std::make_unique<Human_Player>(); } else if(opt == "-random") { latest = std::make_unique<Random_AI>(); } else if(opt == "-genetic") { std::string filename; int id = -1; if(i + 1 < argc) { filename = argv[i+1]; if(filename.front() == '-') { filename.clear(); } } if(i + 2 < argc) { try { id = std::stoi(argv[i+2]); } catch(const std::exception&) { } } if(filename.empty()) { latest = std::make_unique<Genetic_AI>(); for(int j = 0; j < 100; ++j) { static_cast<Genetic_AI*>(latest.get())->mutate(); } static_cast<Genetic_AI*>(latest.get())->print_genome("single_game_player.txt"); } else { if(id < 0) { latest = std::make_unique<Genetic_AI>(filename, find_last_id(filename)); i += 1; } else { latest = std::make_unique<Genetic_AI>(filename, id); i += 2; } } } else if(opt == "-time") { game_time = std::stod(argv[++i]); } else if(opt == "-reset_moves") { moves_per_reset = std::stoul(argv[++i]); } else if(opt == "-increment_time") { increment_time = std::stod(argv[++i]); } else { throw std::runtime_error("Invalid option: " + opt); } if(latest) { if( ! white) { white = std::move(latest); } else if( ! black) { black = std::move(latest); } else { throw std::runtime_error("More than two players specified."); } } } std::string game_file_name = "game.pgn"; if(black) { play_game(*white, *black, game_time, moves_per_reset, increment_time, game_file_name); } else { auto outside = connect_to_outside(*white); game_time = outside->get_game_time(); moves_per_reset = outside->get_reset_moves(); increment_time = outside->get_increment(); if(outside->get_ai_color() == WHITE) { play_game(*white, *outside, game_time, moves_per_reset, increment_time, game_file_name); } else { play_game(*outside, *white, game_time, moves_per_reset, increment_time, game_file_name); } } } } else { print_help(); } } catch(const std::exception& e) { std::cerr << "\n\nERROR: " << e.what() << std::endl; return 1; } return 0; } void print_help() { std::cout << "\n\nGenetic Chess" << std::endl << "=============" << std::endl << std::endl << "Options:" << std::endl << "\t-genepool [file name]" << std::endl << "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name." << std::endl << std::endl << "\t-replay [filename]" << std::endl << "\t\tStep through a PGN game file, drawing the board after each\n\t\tmove with an option to begin playing at any time." << std::endl << std::endl << "\t-stalemate" << std::endl << "\t\tBegin a search for the shortest possible stalemate--i.e., where\n\t\tthe player to move has no legal moves. Estimated time to\n\t\tcompletion: months." << std::endl << std::endl << "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP command from outside to start\nplaying." << std::endl << std::endl << "\t-human" << std::endl << "\t\tSpecify a human player for a game." << std::endl << std::endl << "\t-genetic [filename [number]]" << std::endl << "\t\tSpecify a genetic AI player for a game. Optional file name and\n\t\tID number to load an AI from a file." << std::endl << std::endl << "\t-random" << std::endl << "\t\tSpecify a player that makes random moves for a game." << std::endl << std::endl << "Other game options:" << std::endl << std::endl << "\t-time [number]" << std::endl << "\t\tSpecify the time (in seconds) each player has to play the game\n\t\tor to make a set number of moves (see -reset_moves option)." << std::endl << std::endl << "\t-reset_moves [number]" << std::endl << "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock adds the initial time every time this\n\t\tnumber of moves is made." << std::endl << std::endl << "\t-increment_time [number]" << std::endl << "\t\tSpecify seconds to add to time after each move." << std::endl << std::endl; } int find_last_id(const std::string& players_file_name) { auto pools = load_gene_pool_file(players_file_name); int smallest_id = -1; if( ! pools.empty()) { smallest_id = pools.front().front().get_id(); for(const auto& pool : pools) { for(const auto& player : pool) { if(player.get_id() < smallest_id) { smallest_id = player.get_id(); } } } } if(smallest_id != -1) { return smallest_id; } std::ifstream player_input(players_file_name); std::string line; int last_player = -1; while(std::getline(player_input, line)) { if(String::starts_with(line, "ID:")) { last_player = std::stoi(String::split(line).back()); } } // Filter out players with zero wins auto games_file = players_file_name + "_games.txt"; std::ifstream games_input(games_file); std::map<int, int> win_count; int best_id = -1; while(std::getline(games_input, line)) { int white_id = -1; int black_id = -1; if(String::starts_with(line, "[White")) { white_id = std::stoi(String::split(String::split(line, "\"")[1])[2]); } else if(String::starts_with(line, "[Black")) { black_id = std::stoi(String::split(String::split(line, "\"")[1])[2]); } else if(String::starts_with(line, "[Result")) { auto result_string = String::split(line, "\"")[1]; auto winning_id = -1; if(result_string == "1-0") { winning_id = white_id; } else if(result_string == "0-1") { winning_id = black_id; } int wins_so_far = ++win_count[winning_id]; if(wins_so_far >= 3 && winning_id > best_id) { best_id = winning_id; } } } if(best_id == -1) { return last_player; } else { return best_id; } } void replay_game(const std::string& file_name, int game_number) { std::ifstream ifs(file_name); std::vector<std::string> game_headers; std::string line; if(game_number >= 0) { // fast forward to indicated game while(std::getline(ifs, line)) { line = String::trim_outer_whitespace(line); if(String::starts_with(line, '[')) { game_headers.push_back(line); } else { game_headers.clear(); } if(String::starts_with(line, "[Round")) { auto number = std::stoi(String::split(line, "\"")[1]); if(number == game_number) { break; } } } if( ! ifs) { std::cout << "No game with ID number " << game_number << " found." << std::endl; } for(const auto& header : game_headers) { std::cout << header << std::endl; } } Board board; Game_Result result; bool game_started = false; while( ! result.game_has_ended() && std::getline(ifs, line)) { line = String::strip_block_comment(line, '{', '}'); line = String::strip_comments(line, ';'); if(line.empty()) { if(game_started) { break; } else { continue; } } if(line[0] == '[') // header lines { std::cout << line << std::endl; continue; } for(const auto& s : String::split(line)) { try { result = board.submit_move(board.get_move(s)); board.ascii_draw(WHITE); game_started = true; std::cout << "Last move: "; std::cout << (board.get_game_record().size() + 1)/2 << ". "; std::cout << (board.whose_turn() == WHITE ? "... " : ""); std::cout << board.get_game_record().back()->coordinate_move() << std::endl; if(result.game_has_ended()) { std::cout << result.get_ending_reason() << std::endl; break; } std::cout << "Enter \"y\" to play game from here: " << std::endl; char response = std::cin.get(); if(std::tolower(response) == 'y') { play_game_with_board(Human_Player(), Human_Player(), 0, 0, 0, file_name + "_continued.pgn", board); break; } } catch(const Illegal_Move_Exception&) { std::cout << "Ignoring: " << s << std::endl; continue; } } } } <commit_msg>Create function for checking PGN game records<commit_after>#include <iostream> #include <memory> #include <fstream> #include <cctype> #include "Game/Game.h" #include "Game/Board.h" #include "Game/Game_Result.h" #include "Players/Genetic_AI.h" #include "Players/Human_Player.h" #include "Players/Random_AI.h" #include "Players/Outside_Player.h" #include "Genes/Gene_Pool.h" #include "Stalemate_Search.h" #include "Exceptions/Illegal_Move_Exception.h" #include "Utility.h" #include "Testing.h" void print_help(); void replay_game(const std::string& file_name, int game_number); bool confirm_game_record(const std::string& file_name); int find_last_id(const std::string& filename); int main(int argc, char *argv[]) { try { run_tests(); if(argc > 1) { if(std::string(argv[1]) == "-genepool") { std::string gene_pool_config_file_name; if(argc > 2) { gene_pool_config_file_name = argv[2]; } gene_pool(gene_pool_config_file_name); } else if(std::string(argv[1]) == "-replay") { if(argc > 2) { std::string file_name = argv[2]; int game_number = -1; if(argc > 3) { game_number = std::stoi(argv[3]); } replay_game(file_name, game_number); } else { std::cout << "Provide a file containing a game to replay." << std::endl; return 1; } } else if(std::string(argv[1]) == "-stalemate") { stalemate_search_start(); } else if(std::string(argv[1]) == "-confirm") { if(argc >= 3) { if( ! confirm_game_record(argv[2])) { std::cerr << "Game contains illegal or mismarked moves." << std::endl; return 2; } } else { std::cerr << "Provide a file containing a game to confirm has all legal moves." << std::endl; return 1; } } else { // Use pointers since each player could be Human, Genetic, Random, etc. std::unique_ptr<Player> white; std::unique_ptr<Player> black; std::unique_ptr<Player> latest; double game_time = 0; size_t moves_per_reset = 0; double increment_time = 0; for(int i = 1; i < argc; ++i) { std::string opt = argv[i]; if(opt == "-human") { latest = std::make_unique<Human_Player>(); } else if(opt == "-random") { latest = std::make_unique<Random_AI>(); } else if(opt == "-genetic") { std::string filename; int id = -1; if(i + 1 < argc) { filename = argv[i+1]; if(filename.front() == '-') { filename.clear(); } } if(i + 2 < argc) { try { id = std::stoi(argv[i+2]); } catch(const std::exception&) { } } if(filename.empty()) { latest = std::make_unique<Genetic_AI>(); for(int j = 0; j < 100; ++j) { static_cast<Genetic_AI*>(latest.get())->mutate(); } static_cast<Genetic_AI*>(latest.get())->print_genome("single_game_player.txt"); } else { if(id < 0) { latest = std::make_unique<Genetic_AI>(filename, find_last_id(filename)); i += 1; } else { latest = std::make_unique<Genetic_AI>(filename, id); i += 2; } } } else if(opt == "-time") { game_time = std::stod(argv[++i]); } else if(opt == "-reset_moves") { moves_per_reset = std::stoul(argv[++i]); } else if(opt == "-increment_time") { increment_time = std::stod(argv[++i]); } else { throw std::runtime_error("Invalid option: " + opt); } if(latest) { if( ! white) { white = std::move(latest); } else if( ! black) { black = std::move(latest); } else { throw std::runtime_error("More than two players specified."); } } } std::string game_file_name = "game.pgn"; if(black) { play_game(*white, *black, game_time, moves_per_reset, increment_time, game_file_name); } else { auto outside = connect_to_outside(*white); game_time = outside->get_game_time(); moves_per_reset = outside->get_reset_moves(); increment_time = outside->get_increment(); if(outside->get_ai_color() == WHITE) { play_game(*white, *outside, game_time, moves_per_reset, increment_time, game_file_name); } else { play_game(*outside, *white, game_time, moves_per_reset, increment_time, game_file_name); } } } } else { print_help(); } } catch(const std::exception& e) { std::cerr << "\n\nERROR: " << e.what() << std::endl; return 1; } return 0; } void print_help() { std::cout << "\n\nGenetic Chess" << std::endl << "=============" << std::endl << std::endl << "Options:" << std::endl << "\t-genepool [file name]" << std::endl << "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name." << std::endl << std::endl << "\t-replay [filename]" << std::endl << "\t\tStep through a PGN game file, drawing the board after each\n\t\tmove with an option to begin playing at any time." << std::endl << std::endl << "\t-confirm [filename]" << std::endl << "\t\tCheck a file containing PGN game records for any illegal moves\n\t\tor mismarked checks or checkmates." << std::endl << std::endl << "\t-stalemate" << std::endl << "\t\tBegin a search for the shortest possible stalemate--i.e., where\n\t\tthe player to move has no legal moves. Estimated time to\n\t\tcompletion: months." << std::endl << std::endl << "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP command from outside to start\nplaying." << std::endl << std::endl << "\t-human" << std::endl << "\t\tSpecify a human player for a game." << std::endl << std::endl << "\t-genetic [filename [number]]" << std::endl << "\t\tSpecify a genetic AI player for a game. Optional file name and\n\t\tID number to load an AI from a file." << std::endl << std::endl << "\t-random" << std::endl << "\t\tSpecify a player that makes random moves for a game." << std::endl << std::endl << "Other game options:" << std::endl << std::endl << "\t-time [number]" << std::endl << "\t\tSpecify the time (in seconds) each player has to play the game\n\t\tor to make a set number of moves (see -reset_moves option)." << std::endl << std::endl << "\t-reset_moves [number]" << std::endl << "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock adds the initial time every time this\n\t\tnumber of moves is made." << std::endl << std::endl << "\t-increment_time [number]" << std::endl << "\t\tSpecify seconds to add to time after each move." << std::endl << std::endl; } int find_last_id(const std::string& players_file_name) { auto pools = load_gene_pool_file(players_file_name); int smallest_id = -1; if( ! pools.empty()) { smallest_id = pools.front().front().get_id(); for(const auto& pool : pools) { for(const auto& player : pool) { if(player.get_id() < smallest_id) { smallest_id = player.get_id(); } } } } if(smallest_id != -1) { return smallest_id; } std::ifstream player_input(players_file_name); std::string line; int last_player = -1; while(std::getline(player_input, line)) { if(String::starts_with(line, "ID:")) { last_player = std::stoi(String::split(line).back()); } } // Filter out players with zero wins auto games_file = players_file_name + "_games.txt"; std::ifstream games_input(games_file); std::map<int, int> win_count; int best_id = -1; while(std::getline(games_input, line)) { int white_id = -1; int black_id = -1; if(String::starts_with(line, "[White")) { white_id = std::stoi(String::split(String::split(line, "\"")[1])[2]); } else if(String::starts_with(line, "[Black")) { black_id = std::stoi(String::split(String::split(line, "\"")[1])[2]); } else if(String::starts_with(line, "[Result")) { auto result_string = String::split(line, "\"")[1]; auto winning_id = -1; if(result_string == "1-0") { winning_id = white_id; } else if(result_string == "0-1") { winning_id = black_id; } int wins_so_far = ++win_count[winning_id]; if(wins_so_far >= 3 && winning_id > best_id) { best_id = winning_id; } } } if(best_id == -1) { return last_player; } else { return best_id; } } void replay_game(const std::string& file_name, int game_number) { std::ifstream ifs(file_name); std::vector<std::string> game_headers; std::string line; if(game_number >= 0) { // fast forward to indicated game while(std::getline(ifs, line)) { line = String::trim_outer_whitespace(line); if(String::starts_with(line, '[')) { game_headers.push_back(line); } else { game_headers.clear(); } if(String::starts_with(line, "[Round")) { auto number = std::stoi(String::split(line, "\"")[1]); if(number == game_number) { break; } } } if( ! ifs) { std::cout << "No game with ID number " << game_number << " found." << std::endl; } for(const auto& header : game_headers) { std::cout << header << std::endl; } } Board board; Game_Result result; bool game_started = false; while( ! result.game_has_ended() && std::getline(ifs, line)) { line = String::strip_block_comment(line, '{', '}'); line = String::strip_comments(line, ';'); if(line.empty()) { if(game_started) { break; } else { continue; } } if(line[0] == '[') // header lines { std::cout << line << std::endl; continue; } for(const auto& s : String::split(line)) { try { result = board.submit_move(board.get_move(s)); board.ascii_draw(WHITE); game_started = true; std::cout << "Last move: "; std::cout << (board.get_game_record().size() + 1)/2 << ". "; std::cout << (board.whose_turn() == WHITE ? "... " : ""); std::cout << board.get_game_record().back()->coordinate_move() << std::endl; if(result.game_has_ended()) { std::cout << result.get_ending_reason() << std::endl; break; } std::cout << "Enter \"y\" to play game from here: " << std::endl; char response = std::cin.get(); if(std::tolower(response) == 'y') { play_game_with_board(Human_Player(), Human_Player(), 0, 0, 0, file_name + "_continued.pgn", board); break; } } catch(const Illegal_Move_Exception&) { std::cout << "Ignoring: " << s << std::endl; continue; } } } } bool confirm_game_record(const std::string& file_name) { auto input = std::ifstream(file_name); std::string line; auto expected_winner = NONE; auto expect_checkmate = true; auto in_game = false; Board board; while(std::getline(input, line)) { line = String::strip_block_comment(line, '{', '}'); line = String::strip_comments(line, ';'); line = String::remove_extra_whitespace(line); if(line.empty()) { continue; } if(in_game && String::starts_with(line, '[')) { expected_winner = NONE; expect_checkmate = true; in_game = false; board = Board(); } if(String::starts_with(line, "[Result")) { if(String::contains(line, "1-0")) { expected_winner = WHITE; } else if(String::contains(line, "0-1")) { expected_winner = BLACK; } else if(String::contains(line, "1/2-1/2")) { expected_winner = NONE; } else { std::cerr << "Malformed Result: " << line << std::endl; return false; } } else if(String::starts_with(line, "[Termination")) { expect_checkmate = false; } else if(String::starts_with(line, "[FEN")) { board = Board(String::split(line, "\"").at(1)); } else if(String::starts_with(line, '[')) { continue; } else { // In game in_game = true; for(const auto& move : String::split(line)) { if(move.back() == '.') { continue; } if((move == "1/2-1/2" && expected_winner != NONE) || (move == "1-0" && expected_winner != WHITE) || (move == "0-1" && expected_winner != BLACK)) { std::cerr << "Final result mark (" << move << ") does not match game result." << std::endl; return false; } if(move == "1/2-1/2" || move == "1-0" || move == "0-1") { continue; } try { auto move_checks = move.back() == '+'; auto move_checkmates = move.back() == '#'; auto& move_to_submit = board.get_move(move); if(String::contains(move, 'x')) // check that move captures { const Board& temp = board; // to prevent use of non-const private overload if( ! temp.piece_on_square(move_to_submit.end_file(), move_to_submit.end_rank())) { std::cerr << "Move: " << move << " indicates capture but does not capture." << std::endl; return false; } } auto result = board.submit_move(move_to_submit); if(move_checks) { if(!board.king_is_in_check(board.whose_turn())) { std::cerr << "Move (" << move << ") indicates check but does not check." << std::endl; return false; } } if(move_checkmates) { if(result.get_winner() != opposite(board.whose_turn())) { std::cerr << "Move (" << move << ") indicates checkmate, but move does not checkmate." << std::endl; return false; } } } catch(const Illegal_Move_Exception&) { std::cerr << "Move (" << move << ") is illegal." << std::endl; return false; } } } } return true; }<|endoftext|>
<commit_before>#include "lexer.hpp" #include "helper_lexer.hpp" #include "gtest.h" TEST(lexer, comment1) { std::stringstream is; is << R"( {~ comment {~ broken nest ~} def placeholder )"; klang::TokenVector tokens; bool success; std::tie(success, tokens) = klang::tokenize(is); EXPECT_TRUE(success); using T = klang::Token; using klang::TokenType; klang::TokenVector const expect = { T{TokenType::SYMBOL, "def", 5}, T{TokenType::IDENTIFIER, "placeholder", 5}, }; ASSERT_EQ(expect.size(), tokens.size()); for(size_t i(0); i < expect.size(); ++i) EXPECT_EQ(expect[i], tokens[i]); } <commit_msg>12345abcde をtokenize するtest<commit_after>#include "lexer.hpp" #include "helper_lexer.hpp" #include "gtest.h" TEST(lexer, comment1) { std::stringstream is; is << R"( {~ comment {~ broken nest ~} def placeholder )"; klang::TokenVector tokens; bool success; std::tie(success, tokens) = klang::tokenize(is); EXPECT_TRUE(success); using T = klang::Token; using klang::TokenType; klang::TokenVector const expect = { T{TokenType::SYMBOL, "def", 5}, T{TokenType::IDENTIFIER, "placeholder", 5}, }; ASSERT_EQ(expect.size(), tokens.size()); for(size_t i(0); i < expect.size(); ++i) EXPECT_EQ(expect[i], tokens[i]); } TEST(lexer, split12345abcde) { /* 現在はこのテストは失敗する。 はやく通過するようになっておくれ ref: https://github.com/kmc-jp/Klang/pull/57#issuecomment-57607078 */ std::stringstream is; is << "12345abcde"; klang::TokenVector tokens; bool success; std::tie(success, tokens) = klang::tokenize(is); EXPECT_FALSE(success); ASSERT_EQ(klang::TokenVector(), tokens); } <|endoftext|>
<commit_before>616816d4-2749-11e6-9646-e0f84713e7b8<commit_msg>new flies<commit_after>6175e540-2749-11e6-920b-e0f84713e7b8<|endoftext|>
<commit_before>#include <windows.h> #include <iostream> #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") //Global variables RECT rect; HWND hWnd; HWND hWndEdit; //Declaring used methods. void getWindowSize(); //Handling uncaught exceptions. LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg == WM_SIZE) { getWindowSize(); //The magic numbers 16 and 39 are the adjustments for the window bars. SetWindowPos(hWndEdit, NULL, 0, 0, ((rect.right - rect.left) - 16), ((rect.bottom - rect.top) - 39), NULL); } switch (msg) { case WM_CLOSE: DestroyWindow(hWnd); case WM_DESTROY: PostQuitMessage(EXIT_SUCCESS); default: return DefWindowProc(hWnd, msg, wParam, lParam); } return FALSE; } //The main entry point for the program. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR nCmdLine, int nCmdShow) { LPTSTR windowClass = TEXT("ProjectHowlApp"); LPTSTR windowTitle = TEXT("ProjectHowl"); WNDCLASSEX wcex; wcex.cbClsExtra = 0; wcex.cbSize = sizeof(WNDCLASSEX); wcex.cbWndExtra = 0; wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wcex.hInstance = hInstance; wcex.lpfnWndProc = WndProc; wcex.lpszClassName = windowClass; wcex.lpszMenuName = NULL; wcex.style = CS_HREDRAW | CS_VREDRAW; //Registering the window. Will exit gracefully if failed. if (!RegisterClassEx(&wcex)) { MessageBox(NULL, TEXT("RegisterClassEx Failed!"), TEXT("Error"), MB_ICONERROR); return EXIT_FAILURE; } //Creating main window and exiting gracefully if exceptions occur. if (!(hWnd = CreateWindow(windowClass, windowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL))) { MessageBox(NULL, TEXT("CreateWindow Failed!"), TEXT("Error"), MB_ICONERROR); return EXIT_FAILURE; } getWindowSize(); //Creating inner editing window. hWndEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT("Start Writing Motherfucker..."), WS_CHILD | WS_VISIBLE | ES_WANTRETURN | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, NULL, NULL, NULL); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); //Structure to hold message. MSG msg; //Loop to handle events. while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return EXIT_SUCCESS; } void getWindowSize() { //Get size of the window called hWnd and store in RECT rect. if (GetWindowRect(hWnd, &rect) == false) { std::cout << "Error getting the windows size.\n"; } }<commit_msg>Changed redundant if statement in WndProc.<commit_after>#include <windows.h> #include <iostream> #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") //Global variables RECT rect; HWND hWnd; HWND hWndEdit; //Declaring used methods. void getWindowSize(); //Handling uncaught exceptions. LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CLOSE: DestroyWindow(hWnd); case WM_DESTROY: PostQuitMessage(EXIT_SUCCESS); case WM_SIZE: getWindowSize(); //The magic numbers 16 and 39 are the adjustments for the window bars. SetWindowPos(hWndEdit, NULL, 0, 0, ((rect.right - rect.left) - 16), ((rect.bottom - rect.top) - 39), NULL); default: return DefWindowProc(hWnd, msg, wParam, lParam); } return FALSE; } //The main entry point for the program. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR nCmdLine, int nCmdShow) { LPTSTR windowClass = TEXT("ProjectHowlApp"); LPTSTR windowTitle = TEXT("ProjectHowl"); WNDCLASSEX wcex; wcex.cbClsExtra = 0; wcex.cbSize = sizeof(WNDCLASSEX); wcex.cbWndExtra = 0; wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wcex.hInstance = hInstance; wcex.lpfnWndProc = WndProc; wcex.lpszClassName = windowClass; wcex.lpszMenuName = NULL; wcex.style = CS_HREDRAW | CS_VREDRAW; //Registering the window. Will exit gracefully if failed. if (!RegisterClassEx(&wcex)) { MessageBox(NULL, TEXT("RegisterClassEx Failed!"), TEXT("Error"), MB_ICONERROR); return EXIT_FAILURE; } //Creating main window and exiting gracefully if exceptions occur. if (!(hWnd = CreateWindow(windowClass, windowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL))) { MessageBox(NULL, TEXT("CreateWindow Failed!"), TEXT("Error"), MB_ICONERROR); return EXIT_FAILURE; } getWindowSize(); //Creating inner editing window. hWndEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT("Start Writing Motherfucker..."), WS_CHILD | WS_VISIBLE | ES_WANTRETURN | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, NULL, NULL, NULL); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); //Structure to hold message. MSG msg; //Loop to handle events. while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return EXIT_SUCCESS; } void getWindowSize() { //Get size of the window called hWnd and store in RECT rect. if (GetWindowRect(hWnd, &rect) == false) { std::cout << "Error getting the windows size.\n"; } }<|endoftext|>
<commit_before>85627993-2d15-11e5-af21-0401358ea401<commit_msg>85627994-2d15-11e5-af21-0401358ea401<commit_after>85627994-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>7a4e31fa-5216-11e5-935a-6c40088e03e4<commit_msg>7a5542b0-5216-11e5-b603-6c40088e03e4<commit_after>7a5542b0-5216-11e5-b603-6c40088e03e4<|endoftext|>
<commit_before>a7bbf00f-327f-11e5-ac5d-9cf387a8033e<commit_msg>a7c1ffc5-327f-11e5-b365-9cf387a8033e<commit_after>a7c1ffc5-327f-11e5-b365-9cf387a8033e<|endoftext|>
<commit_before>5d28661a-2d16-11e5-af21-0401358ea401<commit_msg>5d28661b-2d16-11e5-af21-0401358ea401<commit_after>5d28661b-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>ff5b5862-585a-11e5-986d-6c40088e03e4<commit_msg>ff62c908-585a-11e5-b115-6c40088e03e4<commit_after>ff62c908-585a-11e5-b115-6c40088e03e4<|endoftext|>
<commit_before>91380430-4b02-11e5-8807-28cfe9171a43<commit_msg>Really doesn't crash if X, now<commit_after>9145f52b-4b02-11e5-bca0-28cfe9171a43<|endoftext|>
<commit_before>1731c902-2f67-11e5-9139-6c40088e03e4<commit_msg>17382e1c-2f67-11e5-b53c-6c40088e03e4<commit_after>17382e1c-2f67-11e5-b53c-6c40088e03e4<|endoftext|>
<commit_before>51d6ea28-ad5b-11e7-a092-ac87a332f658<commit_msg>lets try again<commit_after>524f4b26-ad5b-11e7-b447-ac87a332f658<|endoftext|>
<commit_before>c00d580a-35ca-11e5-9df9-6c40088e03e4<commit_msg>c014dfd2-35ca-11e5-9063-6c40088e03e4<commit_after>c014dfd2-35ca-11e5-9063-6c40088e03e4<|endoftext|>
<commit_before>bfb82075-2e4f-11e5-bd96-28cfe91dbc4b<commit_msg>bfbec50c-2e4f-11e5-812f-28cfe91dbc4b<commit_after>bfbec50c-2e4f-11e5-812f-28cfe91dbc4b<|endoftext|>
<commit_before>1244f0d7-2e4f-11e5-bd27-28cfe91dbc4b<commit_msg>124dbfd7-2e4f-11e5-918d-28cfe91dbc4b<commit_after>124dbfd7-2e4f-11e5-918d-28cfe91dbc4b<|endoftext|>
<commit_before>4ce82791-2748-11e6-b121-e0f84713e7b8<commit_msg>I am finally done<commit_after>4d02c0a1-2748-11e6-842d-e0f84713e7b8<|endoftext|>
<commit_before>adf765c0-4b02-11e5-a559-28cfe9171a43<commit_msg>this is my first commit?<commit_after>ae0aefd1-4b02-11e5-ae26-28cfe9171a43<|endoftext|>
<commit_before>2f9d1f2e-2e3a-11e5-9324-c03896053bdd<commit_msg>2faab63e-2e3a-11e5-a2f5-c03896053bdd<commit_after>2faab63e-2e3a-11e5-a2f5-c03896053bdd<|endoftext|>
<commit_before>d36da81e-313a-11e5-ad78-3c15c2e10482<commit_msg>d373ac97-313a-11e5-a11c-3c15c2e10482<commit_after>d373ac97-313a-11e5-a11c-3c15c2e10482<|endoftext|>
<commit_before>81cf0da9-2d15-11e5-af21-0401358ea401<commit_msg>81cf0daa-2d15-11e5-af21-0401358ea401<commit_after>81cf0daa-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <memory> #include <iostream> #include <botan/sha2_64.h> #include <botan/botan.h> #include <QtGlobal> #include "serializer.h" const int blobType_simpleStaticFile = 0x01; const int blobType_splitStaticFile = 0x02; const int blobType_simpleStaticDir = 0x11; const int validationMethod_HashSHA512 = 0x01; const std::string cipher_AES256_hexStr = "01"; const size_t simpleFileSizeLimit = 16 * 1024*1024; template< typename T > std::string toHex( const T& data ) { Botan::Pipe hexPipe( new Botan::Hex_Encoder( Botan::Hex_Encoder::Lowercase ) ); hexPipe.start_msg(); hexPipe.write( data ); hexPipe.end_msg(); return hexPipe.read_all_as_string(); } struct Blob { Botan::SecureVector< Botan::byte > sourceData; Botan::SecureVector< Botan::byte > resultData; std::string bid; std::string key; void dump( std::string name ) { std::cout << "======== " << name << " ==================================================================================" << std::endl; std::cout << std::endl; std::cout << "DATA: " << toHex( sourceData ) << std::endl; std::cout << "BID: " << bid << std::endl; std::cout << "KEY: " << key << std::endl; std::cout << "BLOB: " << toHex( resultData ) << std::endl; std::cout << std::endl; } }; template< typename T > Blob createBlobHash( char blobType, const T& content ) { Botan::SHA_512 hasher; Blob ret; // Build the unencrypted data buffer ret.sourceData.push_back( blobType ); for( const auto& ch: content ) ret.sourceData.push_back(ch); // Create the hash of the unencrypted buffer to be used as the encryption hey hasher.clear(); hasher.update( ret.sourceData ); Botan::SymmetricKey key( hasher.final(), 32 ); Botan::byte zeroIV[16] = {0}; Botan::InitializationVector iv( zeroIV, sizeof(zeroIV) ); // Encrypt the data Botan::Pipe pipe( Botan::get_cipher("AES-256/CFB/NoPadding", key, iv, Botan::ENCRYPTION ) ); pipe.start_msg(); pipe.write( ret.sourceData ); pipe.end_msg(); Botan::SecureVector< Botan::byte > encryptedData = pipe.read_all(); // Generate blob id hasher.clear(); hasher.update( encryptedData ); // Get the result ret.bid = toHex( hasher.final() ); ret.key = cipher_AES256_hexStr + toHex( key.bits_of() ); ret.resultData.push_back( validationMethod_HashSHA512 ); for( const auto& ch: encryptedData ) ret.resultData.push_back(ch); return ret; } /////////////////////////////////////////////////////////////////////////////// template< typename T > Blob createFileBlobHash( const T& content ) { std::vector< Blob > partials; for ( size_t pos = 0; pos < content.size(); pos += simpleFileSizeLimit ) { size_t partSize = std::min( simpleFileSizeLimit, content.size() - pos ); std::vector<char> partContent( content.begin()+pos, content.begin()+pos+partSize ); Blob blob = createBlobHash( blobType_simpleStaticFile, content ); partials.push_back( blob ); } // Make sure we've got at least one blob if ( partials.empty() ) { partials.push_back( createBlobHash( blobType_simpleStaticFile, std::string() ) ); } // Don't have to split the blob if it fits in one part if ( partials.size() == 1 ) { return partials.front(); } // Create extra blob containing information about the parts Serializer s; s << content.size() << partials.size(); for ( const auto& blob: partials ) s << blob.bid << blob.key; return createBlobHash( blobType_splitStaticFile, s.getData() ); } void dumpFileBlobHash( const std::string& content ) { std::string name = "Simple File: '" + content.substr(0,20); if ( content.size()>20 ) name.append("..."); name.append("'"); createFileBlobHash(content).dump( name ); } void createFileBlobs() { dumpFileBlobHash( "" ); dumpFileBlobHash( "a" ); dumpFileBlobHash( "Hello World!" ); std::string str; for( char ch = 'a'; ch <= 'z'; ch++ ) str.push_back(ch); for( char ch = 'A'; ch <= 'Z'; ch++ ) str.push_back(ch); dumpFileBlobHash( str ); std::string aaa; for ( size_t i=0; i<simpleFileSizeLimit; i++ ) aaa.push_back('a'); dumpFileBlobHash( aaa ); } /////////////////////////////////////////////////////////////////////////////// struct DirEntry { std::string name; std::string bid; std::string key; inline DirEntry( std::string&& _name, std::string&& _bid, std::string&& _key ) : name(_name) , bid(_bid) , key(_key) {} inline bool operator<( const DirEntry& other ) const { return name < other.name; } }; void createSimpleDirBlobHash( const std::string& name, std::vector< DirEntry > entries ) { std::sort( entries.begin(), entries.end() ); Serializer s; s << entries.size(); for( const auto& entry: entries ) s << entry.name << entry.bid << entry.key; createBlobHash( blobType_simpleStaticDir, s.getData() ).dump( name ); } void createDirBlobs() { createSimpleDirBlobHash( "Empty Dir", {} ); createSimpleDirBlobHash( "One entry - empty file", { { "empty", "b4f5a7bb878c0cec9cb4bd6ae8bb175a7ea59c1a048c5ab7c119990d0041cb9cfb67c2aa9e6fada8112719777b4b80ffada80205f8ebe6981c0ade97ff3df8e5", "017b54b66836c1fbdd13d2441d9e1434dc62ca677fb68f5fe66a464baadecdbd00" } }); createSimpleDirBlobHash( "Two entrie - empty file and 'a' file", { { "a", "c9d30a9938ecea16bed58efe5ad5b998927a56da7c8c36c1ee13292dec79aa50c5613fc90d80c37a77a5a422691d1967693a1236892e228ad95ed6fe4b505d85", "01504ce2f6de7e33389deb73b21f765570ad2b9f2aa8aaec8328f47b48bc3e841f" }, { "empty", "b4f5a7bb878c0cec9cb4bd6ae8bb175a7ea59c1a048c5ab7c119990d0041cb9cfb67c2aa9e6fada8112719777b4b80ffada80205f8ebe6981c0ade97ff3df8e5", "017b54b66836c1fbdd13d2441d9e1434dc62ca677fb68f5fe66a464baadecdbd00" } }); } int main(int argc, char *argv[]) { Botan::LibraryInitializer init; createFileBlobs(); createDirBlobs(); Q_UNUSED(argc); Q_UNUSED(argv); return 0; } <commit_msg>Deal with some speed problems<commit_after>#include <memory> #include <iostream> #include <botan/sha2_64.h> #include <botan/botan.h> #include <QtGlobal> #include "serializer.h" const int blobType_simpleStaticFile = 0x01; const int blobType_splitStaticFile = 0x02; const int blobType_simpleStaticDir = 0x11; const int validationMethod_HashSHA512 = 0x01; const std::string cipher_AES256_hexStr = "01"; const size_t simpleFileSizeLimit = 16 * 1024*1024; template< typename T > std::string toHex( const T& data ) { Botan::Pipe hexPipe( new Botan::Hex_Encoder( Botan::Hex_Encoder::Lowercase ) ); hexPipe.start_msg(); hexPipe.write( data ); hexPipe.end_msg(); return hexPipe.read_all_as_string(); } struct Blob { std::vector< char > sourceData; std::vector< char > resultData; std::string bid; std::string key; void dump( std::string name ) { std::cout << "======== " << name << " ==================================================================================" << std::endl; std::cout << std::endl; std::cout << "DATA: " << toHex( sourceData ) << std::endl; std::cout << "BID: " << bid << std::endl; std::cout << "KEY: " << key << std::endl; std::cout << "BLOB: " << toHex( resultData ) << std::endl; std::cout << std::endl; } }; template< typename T > Botan::MemoryVector< Botan::byte > toBotan( const T& data ) { // NOTE: assumes the data is a container of byte-size values return Botan::MemoryVector< Botan::byte >( (const Botan::byte*)&data[0], data.size() ); } template< typename T > Blob createBlobHash( char blobType, const T& content ) { Botan::SHA_512 hasher; Blob ret; // Build the unencrypted data buffer ret.sourceData.resize( content.size() + 1 ); ret.sourceData[0] = blobType; std::copy( content.begin(), content.end(), ret.sourceData.begin()+1 ); // Create the hash of the unencrypted buffer to be used as the encryption hey hasher.clear(); hasher.update( toBotan( ret.sourceData ) ); Botan::SymmetricKey key( hasher.final(), 32 ); Botan::byte zeroIV[16] = {0}; Botan::InitializationVector iv( zeroIV, sizeof(zeroIV) ); // Encrypt the data Botan::Pipe pipe( Botan::get_cipher("AES-256/CFB/NoPadding", key, iv, Botan::ENCRYPTION ) ); pipe.start_msg(); pipe.write( toBotan( ret.sourceData ) ); pipe.end_msg(); Botan::SecureVector< Botan::byte > encryptedData = pipe.read_all(); // Generate blob id hasher.clear(); hasher.update( encryptedData ); // Get the result ret.bid = toHex( hasher.final() ); ret.key = cipher_AES256_hexStr + toHex( key.bits_of() ); ret.resultData.push_back( validationMethod_HashSHA512 ); for( const auto& ch: encryptedData ) ret.resultData.push_back(ch); return ret; } /////////////////////////////////////////////////////////////////////////////// template< typename T > Blob createFileBlobHash( const T& content ) { std::vector< Blob > partials; for ( size_t pos = 0; pos < content.size(); pos += simpleFileSizeLimit ) { size_t partSize = std::min( simpleFileSizeLimit, content.size() - pos ); std::vector<char> partContent( content.begin()+pos, content.begin()+pos+partSize ); Blob blob = createBlobHash( blobType_simpleStaticFile, content ); partials.push_back( blob ); } // Make sure we've got at least one blob if ( partials.empty() ) { partials.push_back( createBlobHash( blobType_simpleStaticFile, std::string() ) ); } // Don't have to split the blob if it fits in one part if ( partials.size() == 1 ) { return partials.front(); } // Create extra blob containing information about the parts Serializer s; s << content.size() << partials.size(); for ( const auto& blob: partials ) s << blob.bid << blob.key; return createBlobHash( blobType_splitStaticFile, s.getData() ); } void dumpFileBlobHash( const std::string& content ) { std::string name = "Simple File: '" + content.substr(0,20); if ( content.size()>20 ) name.append("..."); name.append("'"); createFileBlobHash(content).dump( name ); } void createFileBlobs() { dumpFileBlobHash( "" ); dumpFileBlobHash( "a" ); dumpFileBlobHash( "Hello World!" ); std::string str; for( char ch = 'a'; ch <= 'z'; ch++ ) str.push_back(ch); for( char ch = 'A'; ch <= 'Z'; ch++ ) str.push_back(ch); dumpFileBlobHash( str ); std::string aaa; for ( size_t i=0; i<simpleFileSizeLimit; i++ ) aaa.push_back('a'); dumpFileBlobHash( aaa ); } /////////////////////////////////////////////////////////////////////////////// struct DirEntry { std::string name; std::string bid; std::string key; inline DirEntry( std::string&& _name, std::string&& _bid, std::string&& _key ) : name(_name) , bid(_bid) , key(_key) {} inline bool operator<( const DirEntry& other ) const { return name < other.name; } }; void createSimpleDirBlobHash( const std::string& name, std::vector< DirEntry > entries ) { std::sort( entries.begin(), entries.end() ); Serializer s; s << entries.size(); for( const auto& entry: entries ) s << entry.name << entry.bid << entry.key; createBlobHash( blobType_simpleStaticDir, s.getData() ).dump( name ); } void createDirBlobs() { createSimpleDirBlobHash( "Empty Dir", {} ); createSimpleDirBlobHash( "One entry - empty file", { { "empty", "b4f5a7bb878c0cec9cb4bd6ae8bb175a7ea59c1a048c5ab7c119990d0041cb9cfb67c2aa9e6fada8112719777b4b80ffada80205f8ebe6981c0ade97ff3df8e5", "017b54b66836c1fbdd13d2441d9e1434dc62ca677fb68f5fe66a464baadecdbd00" } }); createSimpleDirBlobHash( "Two entrie - empty file and 'a' file", { { "a", "c9d30a9938ecea16bed58efe5ad5b998927a56da7c8c36c1ee13292dec79aa50c5613fc90d80c37a77a5a422691d1967693a1236892e228ad95ed6fe4b505d85", "01504ce2f6de7e33389deb73b21f765570ad2b9f2aa8aaec8328f47b48bc3e841f" }, { "empty", "b4f5a7bb878c0cec9cb4bd6ae8bb175a7ea59c1a048c5ab7c119990d0041cb9cfb67c2aa9e6fada8112719777b4b80ffada80205f8ebe6981c0ade97ff3df8e5", "017b54b66836c1fbdd13d2441d9e1434dc62ca677fb68f5fe66a464baadecdbd00" } }); } int main(int argc, char *argv[]) { Botan::LibraryInitializer init; createFileBlobs(); createDirBlobs(); Q_UNUSED(argc); Q_UNUSED(argv); return 0; } <|endoftext|>
<commit_before>3c370aec-2e3a-11e5-927e-c03896053bdd<commit_msg>3c4a6f62-2e3a-11e5-9a46-c03896053bdd<commit_after>3c4a6f62-2e3a-11e5-9a46-c03896053bdd<|endoftext|>
<commit_before>6e5bb5a8-2749-11e6-9e68-e0f84713e7b8<commit_msg>almost working<commit_after>6e6ab6ae-2749-11e6-b91d-e0f84713e7b8<|endoftext|>
<commit_before>5ae7ed03-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ed04-2d16-11e5-af21-0401358ea401<commit_after>5ae7ed04-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5e1a546e-2e3a-11e5-8e62-c03896053bdd<commit_msg>5e2f3fca-2e3a-11e5-ae2f-c03896053bdd<commit_after>5e2f3fca-2e3a-11e5-ae2f-c03896053bdd<|endoftext|>
<commit_before>35272859-2d3f-11e5-9aa7-c82a142b6f9b<commit_msg>3591f251-2d3f-11e5-8d99-c82a142b6f9b<commit_after>3591f251-2d3f-11e5-8d99-c82a142b6f9b<|endoftext|>
<commit_before>5cc61f64-2e3a-11e5-9d93-c03896053bdd<commit_msg>5cd3b674-2e3a-11e5-b1bc-c03896053bdd<commit_after>5cd3b674-2e3a-11e5-b1bc-c03896053bdd<|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "material.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/modeling/bsdf/bsdf.h" #ifdef WITH_OSL #include "renderer/modeling/bsdf/oslbsdf.h" #endif #include "renderer/modeling/edf/edf.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/input/texturesource.h" #include "renderer/modeling/material/bumpmappingmodifier.h" #include "renderer/modeling/material/normalmappingmodifier.h" #include "renderer/modeling/scene/textureinstance.h" #ifdef WITH_OSL #include "renderer/modeling/shadergroup/shadergroup.h" #endif #include "renderer/modeling/surfaceshader/surfaceshader.h" #include "renderer/modeling/texture/texture.h" #include "renderer/utility/messagecontext.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/image/colorspace.h" #include "foundation/utility/makevector.h" // Standard headers. #include <cassert> #include <cstring> #include <string> using namespace foundation; using namespace std; namespace renderer { // // Material class implementation. // namespace { const UniqueID g_class_uid = new_guid(); } UniqueID Material::get_class_uid() { return g_class_uid; } struct Material::Impl { string m_model; }; Material::Material( const char* name, const char* model, const ParamArray& params) : ConnectableEntity(g_class_uid, params) , impl(new Impl()) , m_shade_alpha_cutouts(false) , m_surface_shader(0) , m_bsdf(0) , m_edf(0) , m_alpha_map(0) , m_normal_modifier(0) #ifdef WITH_OSL , m_shader_group(0) #endif { set_name(name); impl->m_model = model; m_inputs.declare("surface_shader", InputFormatEntity); if (strcmp(get_model(), "generic_material") == 0) { m_inputs.declare("bsdf", InputFormatEntity, ""); m_inputs.declare("edf", InputFormatEntity, ""); m_inputs.declare("alpha_map", InputFormatScalar, ""); m_inputs.declare("displacement_map", InputFormatSpectralReflectance, ""); } #ifdef WITH_OSL else if (strcmp(get_model(), "osl_material") == 0) { m_inputs.declare("osl_surface", InputFormatEntity, ""); m_inputs.declare("alpha_map", InputFormatScalar, ""); } #endif else { assert(!"Invalid material model."); } } Material::~Material() { delete impl; } void Material::release() { delete this; } const char* Material::get_model() const { return impl->m_model.c_str(); } namespace { const char* get_non_empty(const ParamArray& params, const char* name) { if (!params.strings().exist(name)) return 0; const char* value = params.strings().get(name); return strlen(value) > 0 ? value : 0; } } bool Material::has_alpha_map() const { return get_non_empty(m_params, "alpha_map") != 0; } const char* Material::get_surface_shader_name() const { return get_non_empty(m_params, "surface_shader"); } const char* Material::get_bsdf_name() const { return get_non_empty(m_params, "bsdf"); } const char* Material::get_edf_name() const { return get_non_empty(m_params, "edf"); } bool Material::on_frame_begin( const Project& project, const Assembly& assembly, AbortSwitch* abort_switch) { const EntityDefMessageContext context("material", this); m_shade_alpha_cutouts = m_params.get_optional<bool>("shade_alpha_cutouts", false); m_surface_shader = get_uncached_surface_shader(); m_alpha_map = get_uncached_alpha_map(); if (strcmp(get_model(), "generic_material") == 0) { m_bsdf = get_uncached_bsdf(); m_edf = get_uncached_edf(); if (!create_normal_modifier(context)) return false; if (m_edf && m_alpha_map) { RENDERER_LOG_WARNING( "%s: material is emitting light but may be partially or entirely transparent;" "this may lead to unexpected or unphysical results.", context.get()); } } #ifdef WITH_OSL else if (strcmp(get_model(), "osl_material") == 0) { m_shader_group = get_uncached_osl_surface(); if (m_shader_group) { m_osl_bsdf = OSLBSDFFactory().create(); m_bsdf = m_osl_bsdf.get(); m_osl_bsdf->on_frame_begin(project, assembly, abort_switch); } } #endif else assert(!"Invalid material model."); return true; } void Material::on_frame_end( const Project& project, const Assembly& assembly) { m_surface_shader = 0; m_bsdf = 0; m_edf = 0; m_alpha_map = 0; delete m_normal_modifier; m_normal_modifier = 0; #ifdef WITH_OSL if (m_osl_bsdf.get()) { m_osl_bsdf->on_frame_end(project, assembly); m_osl_bsdf.reset(); } m_shader_group = 0; #endif } const SurfaceShader* Material::get_uncached_surface_shader() const { return static_cast<const SurfaceShader*>(m_inputs.get_entity("surface_shader")); } const BSDF* Material::get_uncached_bsdf() const { return static_cast<const BSDF*>(m_inputs.get_entity("bsdf")); } const EDF* Material::get_uncached_edf() const { return static_cast<const EDF*>(m_inputs.get_entity("edf")); } const Source* Material::get_uncached_alpha_map() const { return m_inputs.source("alpha_map"); } #ifdef WITH_OSL bool Material::has_osl_surface() const { if (strcmp(get_model(), "osl_material") != 0) return false; return get_non_empty(m_params, "osl_surface") != 0; } const ShaderGroup* Material::get_uncached_osl_surface() const { return static_cast<const ShaderGroup*>(m_inputs.get_entity("osl_surface")); } #endif bool Material::create_normal_modifier(const MessageContext& context) { assert(m_normal_modifier == 0); // Retrieve the source bound to the displacement map input. const Source* displacement_source = m_inputs.source("displacement_map"); // Nothing to do if there is no displacement source. if (displacement_source == 0) return true; // Only texture instances can be bound to the displacement map input. if (dynamic_cast<const TextureSource*>(displacement_source) == 0) { RENDERER_LOG_ERROR( "%s: a texture instance must be bound to the \"displacement_map\" input.", context.get()); return false; } // Retrieve the displacement texture. const TextureSource* displacement_map = static_cast<const TextureSource*>(displacement_source); const Texture& texture = displacement_map->get_texture_instance().get_texture(); // Print a warning if the displacement texture is not expressed in the linear RGB color space. if (texture.get_color_space() != ColorSpaceLinearRGB) { RENDERER_LOG_WARNING( "%s: color space for displacement map \"%s\" " "should be \"%s\" but is \"%s\" instead; expect artifacts and/or slowdowns.", context.get(), texture.get_name(), color_space_name(ColorSpaceLinearRGB), color_space_name(texture.get_color_space())); } // Retrieve the displacement method. const string displacement_method = m_params.get_required<string>( "displacement_method", "bump", make_vector("bump", "normal"), context); // Create the normal modifier. if (displacement_method == "bump") { const double amplitude = m_params.get_optional<double>("bump_amplitude", 1.0); m_normal_modifier = new BumpMappingModifier(displacement_map, 2.0, amplitude); } else { const NormalMappingModifier::UpVector up_vector = m_params.get_optional<string>("normal_map_up", "z", make_vector("y", "z"), context) == "y" ? NormalMappingModifier::UpVectorY : NormalMappingModifier::UpVectorZ; m_normal_modifier = new NormalMappingModifier(displacement_map, up_vector); } return true; } } // namespace renderer <commit_msg>cosmetics.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "material.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/modeling/bsdf/bsdf.h" #ifdef WITH_OSL #include "renderer/modeling/bsdf/oslbsdf.h" #endif #include "renderer/modeling/edf/edf.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/input/texturesource.h" #include "renderer/modeling/material/bumpmappingmodifier.h" #include "renderer/modeling/material/normalmappingmodifier.h" #include "renderer/modeling/scene/textureinstance.h" #ifdef WITH_OSL #include "renderer/modeling/shadergroup/shadergroup.h" #endif #include "renderer/modeling/surfaceshader/surfaceshader.h" #include "renderer/modeling/texture/texture.h" #include "renderer/utility/messagecontext.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/image/colorspace.h" #include "foundation/utility/makevector.h" // Standard headers. #include <cassert> #include <cstring> #include <string> using namespace foundation; using namespace std; namespace renderer { // // Material class implementation. // namespace { const UniqueID g_class_uid = new_guid(); } UniqueID Material::get_class_uid() { return g_class_uid; } struct Material::Impl { string m_model; }; Material::Material( const char* name, const char* model, const ParamArray& params) : ConnectableEntity(g_class_uid, params) , impl(new Impl()) , m_shade_alpha_cutouts(false) , m_surface_shader(0) , m_bsdf(0) , m_edf(0) , m_alpha_map(0) , m_normal_modifier(0) #ifdef WITH_OSL , m_shader_group(0) #endif { set_name(name); impl->m_model = model; m_inputs.declare("surface_shader", InputFormatEntity); if (strcmp(get_model(), "generic_material") == 0) { m_inputs.declare("bsdf", InputFormatEntity, ""); m_inputs.declare("edf", InputFormatEntity, ""); m_inputs.declare("alpha_map", InputFormatScalar, ""); m_inputs.declare("displacement_map", InputFormatSpectralReflectance, ""); } #ifdef WITH_OSL else if (strcmp(get_model(), "osl_material") == 0) { m_inputs.declare("osl_surface", InputFormatEntity, ""); m_inputs.declare("alpha_map", InputFormatScalar, ""); } #endif else { assert(!"Invalid material model."); } } Material::~Material() { delete impl; } void Material::release() { delete this; } const char* Material::get_model() const { return impl->m_model.c_str(); } namespace { const char* get_non_empty(const ParamArray& params, const char* name) { if (!params.strings().exist(name)) return 0; const char* value = params.strings().get(name); return strlen(value) > 0 ? value : 0; } } bool Material::has_alpha_map() const { return get_non_empty(m_params, "alpha_map") != 0; } const char* Material::get_surface_shader_name() const { return get_non_empty(m_params, "surface_shader"); } const char* Material::get_bsdf_name() const { return get_non_empty(m_params, "bsdf"); } const char* Material::get_edf_name() const { return get_non_empty(m_params, "edf"); } bool Material::on_frame_begin( const Project& project, const Assembly& assembly, AbortSwitch* abort_switch) { const EntityDefMessageContext context("material", this); m_shade_alpha_cutouts = m_params.get_optional<bool>("shade_alpha_cutouts", false); m_surface_shader = get_uncached_surface_shader(); m_alpha_map = get_uncached_alpha_map(); if (strcmp(get_model(), "generic_material") == 0) { m_bsdf = get_uncached_bsdf(); m_edf = get_uncached_edf(); if (!create_normal_modifier(context)) return false; if (m_edf && m_alpha_map) { RENDERER_LOG_WARNING( "%s: material is emitting light but may be partially or entirely transparent;" "this may lead to unexpected or unphysical results.", context.get()); } } #ifdef WITH_OSL else if (strcmp(get_model(), "osl_material") == 0) { m_shader_group = get_uncached_osl_surface(); if (m_shader_group) { m_osl_bsdf = OSLBSDFFactory().create(); m_bsdf = m_osl_bsdf.get(); m_osl_bsdf->on_frame_begin(project, assembly, abort_switch); } } #endif else assert(!"Invalid material model."); return true; } void Material::on_frame_end( const Project& project, const Assembly& assembly) { m_surface_shader = 0; m_bsdf = 0; m_edf = 0; m_alpha_map = 0; delete m_normal_modifier; m_normal_modifier = 0; #ifdef WITH_OSL if (m_osl_bsdf.get()) { m_osl_bsdf->on_frame_end(project, assembly); m_osl_bsdf.reset(); } m_shader_group = 0; #endif } const SurfaceShader* Material::get_uncached_surface_shader() const { return static_cast<const SurfaceShader*>(m_inputs.get_entity("surface_shader")); } const BSDF* Material::get_uncached_bsdf() const { return static_cast<const BSDF*>(m_inputs.get_entity("bsdf")); } const EDF* Material::get_uncached_edf() const { return static_cast<const EDF*>(m_inputs.get_entity("edf")); } const Source* Material::get_uncached_alpha_map() const { return m_inputs.source("alpha_map"); } #ifdef WITH_OSL bool Material::has_osl_surface() const { if (strcmp(get_model(), "osl_material") != 0) return false; return get_non_empty(m_params, "osl_surface") != 0; } const ShaderGroup* Material::get_uncached_osl_surface() const { return static_cast<const ShaderGroup*>(m_inputs.get_entity("osl_surface")); } #endif bool Material::create_normal_modifier(const MessageContext& context) { assert(m_normal_modifier == 0); // Retrieve the source bound to the displacement map input. const Source* displacement_source = m_inputs.source("displacement_map"); // Nothing to do if there is no displacement source. if (displacement_source == 0) return true; // Only texture instances can be bound to the displacement map input. if (dynamic_cast<const TextureSource*>(displacement_source) == 0) { RENDERER_LOG_ERROR( "%s: a texture instance must be bound to the \"displacement_map\" input.", context.get()); return false; } // Retrieve the displacement texture. const TextureSource* displacement_map = static_cast<const TextureSource*>(displacement_source); const Texture& texture = displacement_map->get_texture_instance().get_texture(); // Print a warning if the displacement texture is not expressed in the linear RGB color space. if (texture.get_color_space() != ColorSpaceLinearRGB) { RENDERER_LOG_WARNING( "%s: color space for displacement map \"%s\" " "should be \"%s\" but is \"%s\" instead; expect artifacts and/or slowdowns.", context.get(), texture.get_name(), color_space_name(ColorSpaceLinearRGB), color_space_name(texture.get_color_space())); } // Retrieve the displacement method. const string displacement_method = m_params.get_required<string>( "displacement_method", "bump", make_vector("bump", "normal"), context); // Create the normal modifier. if (displacement_method == "bump") { const double amplitude = m_params.get_optional<double>("bump_amplitude", 1.0); m_normal_modifier = new BumpMappingModifier(displacement_map, 2.0, amplitude); } else { const NormalMappingModifier::UpVector up_vector = m_params.get_optional<string>("normal_map_up", "z", make_vector("y", "z"), context) == "y" ? NormalMappingModifier::UpVectorY : NormalMappingModifier::UpVectorZ; m_normal_modifier = new NormalMappingModifier(displacement_map, up_vector); } return true; } } // namespace renderer <|endoftext|>
<commit_before>d3cd137a-585a-11e5-83b9-6c40088e03e4<commit_msg>d3d5c96e-585a-11e5-b410-6c40088e03e4<commit_after>d3d5c96e-585a-11e5-b410-6c40088e03e4<|endoftext|>
<commit_before>32910974-2f67-11e5-98ee-6c40088e03e4<commit_msg>3297a874-2f67-11e5-9acd-6c40088e03e4<commit_after>3297a874-2f67-11e5-9acd-6c40088e03e4<|endoftext|>
<commit_before>8cd9232e-ad5c-11e7-9e42-ac87a332f658<commit_msg>No longer crashes if X<commit_after>8d47533a-ad5c-11e7-a75f-ac87a332f658<|endoftext|>
<commit_before>78e42cfa-2d53-11e5-baeb-247703a38240<commit_msg>78e4af9a-2d53-11e5-baeb-247703a38240<commit_after>78e4af9a-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>dfee325c-4b02-11e5-838d-28cfe9171a43<commit_msg>roselyn broke it<commit_after>dffbe00a-4b02-11e5-8d41-28cfe9171a43<|endoftext|>
<commit_before>5f8949f2-2d16-11e5-af21-0401358ea401<commit_msg>5f8949f3-2d16-11e5-af21-0401358ea401<commit_after>5f8949f3-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8c3d20a7-2d14-11e5-af21-0401358ea401<commit_msg>8c3d20a8-2d14-11e5-af21-0401358ea401<commit_after>8c3d20a8-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>//===-- MCJIT.cpp - MC-based Just-in-Time Compiler --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCJIT.h" #include "MCJITMemoryManager.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Target/TargetData.h" using namespace llvm; namespace { static struct RegisterJIT { RegisterJIT() { MCJIT::Register(); } } JITRegistrator; } extern "C" void LLVMLinkInMCJIT() { } ExecutionEngine *MCJIT::createJIT(Module *M, std::string *ErrorStr, JITMemoryManager *JMM, CodeGenOpt::Level OptLevel, bool GVsWithCode, CodeModel::Model CMM, StringRef MArch, StringRef MCPU, const SmallVectorImpl<std::string>& MAttrs) { // Try to register the program as a source of symbols to resolve against. // // FIXME: Don't do this here. sys::DynamicLibrary::LoadLibraryPermanently(0, NULL); // Pick a target either via -march or by guessing the native arch. // // FIXME: This should be lifted out of here, it isn't something which should // be part of the JIT policy, rather the burden for this selection should be // pushed to clients. TargetMachine *TM = MCJIT::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr); if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0; TM->setCodeModel(CMM); // If the target supports JIT code generation, create the JIT. if (TargetJITInfo *TJ = TM->getJITInfo()) return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM), OptLevel, GVsWithCode); if (ErrorStr) *ErrorStr = "target does not support JIT code generation"; return 0; } MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji, RTDyldMemoryManager *MM, CodeGenOpt::Level OptLevel, bool AllocateGVsWithCode) : ExecutionEngine(m), TM(tm), MemMgr(MM), M(m), OS(Buffer), Dyld(MM) { PM.add(new TargetData(*TM->getTargetData())); // Turn the machine code intermediate representation into bytes in memory // that may be executed. if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) { report_fatal_error("Target does not support MC emission!"); } // Initialize passes. // FIXME: When we support multiple modules, we'll want to move the code // gen and finalization out of the constructor here and do it more // on-demand as part of getPointerToFunction(). PM.run(*M); // Flush the output buffer so the SmallVector gets its data. OS.flush(); // Load the object into the dynamic linker. // FIXME: It would be nice to avoid making yet another copy. MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(), Buffer.size())); if (Dyld.loadObject(MB)) report_fatal_error(Dyld.getErrorString()); // Resolve any relocations. Dyld.resolveRelocations(); } MCJIT::~MCJIT() { delete MemMgr; } void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) { report_fatal_error("not yet implemented"); return 0; } void *MCJIT::getPointerToFunction(Function *F) { if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) { bool AbortOnFailure = !F->hasExternalWeakLinkage(); void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure); addGlobalMapping(F, Addr); return Addr; } Twine Name = TM->getMCAsmInfo()->getGlobalPrefix() + F->getName(); return (void*)Dyld.getSymbolAddress(Name.str()); } void *MCJIT::recompileAndRelinkFunction(Function *F) { report_fatal_error("not yet implemented"); } void MCJIT::freeMachineCodeForFunction(Function *F) { report_fatal_error("not yet implemented"); } GenericValue MCJIT::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert(F && "Function *F was null at entry to run()"); void *FPtr = getPointerToFunction(F); assert(FPtr && "Pointer to fn's code was null after getPointerToFunction"); const FunctionType *FTy = F->getFunctionType(); const Type *RetTy = FTy->getReturnType(); assert((FTy->getNumParams() == ArgValues.size() || (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) && "Wrong number of arguments passed into function!"); assert(FTy->getNumParams() == ArgValues.size() && "This doesn't support passing arguments through varargs (yet)!"); // Handle some common cases first. These cases correspond to common `main' // prototypes. if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) { switch (ArgValues.size()) { case 3: if (FTy->getParamType(0)->isIntegerTy(32) && FTy->getParamType(1)->isPointerTy() && FTy->getParamType(2)->isPointerTy()) { int (*PF)(int, char **, const char **) = (int(*)(int, char **, const char **))(intptr_t)FPtr; // Call the function. GenericValue rv; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), (char **)GVTOP(ArgValues[1]), (const char **)GVTOP(ArgValues[2]))); return rv; } break; case 2: if (FTy->getParamType(0)->isIntegerTy(32) && FTy->getParamType(1)->isPointerTy()) { int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr; // Call the function. GenericValue rv; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), (char **)GVTOP(ArgValues[1]))); return rv; } break; case 1: if (FTy->getNumParams() == 1 && FTy->getParamType(0)->isIntegerTy(32)) { GenericValue rv; int (*PF)(int) = (int(*)(int))(intptr_t)FPtr; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue())); return rv; } break; } } // Handle cases where no arguments are passed first. if (ArgValues.empty()) { GenericValue rv; switch (RetTy->getTypeID()) { default: llvm_unreachable("Unknown return type for function call!"); case Type::IntegerTyID: { unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth(); if (BitWidth == 1) rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)()); else if (BitWidth <= 8) rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)()); else if (BitWidth <= 16) rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)()); else if (BitWidth <= 32) rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)()); else if (BitWidth <= 64) rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)()); else llvm_unreachable("Integer types > 64 bits not supported"); return rv; } case Type::VoidTyID: rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)()); return rv; case Type::FloatTyID: rv.FloatVal = ((float(*)())(intptr_t)FPtr)(); return rv; case Type::DoubleTyID: rv.DoubleVal = ((double(*)())(intptr_t)FPtr)(); return rv; case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID: llvm_unreachable("long double not supported yet"); return rv; case Type::PointerTyID: return PTOGV(((void*(*)())(intptr_t)FPtr)()); } } assert("Full-featured argument passing not supported yet!"); return GenericValue(); } <commit_msg>80-col fix.<commit_after>//===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCJIT.h" #include "MCJITMemoryManager.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Target/TargetData.h" using namespace llvm; namespace { static struct RegisterJIT { RegisterJIT() { MCJIT::Register(); } } JITRegistrator; } extern "C" void LLVMLinkInMCJIT() { } ExecutionEngine *MCJIT::createJIT(Module *M, std::string *ErrorStr, JITMemoryManager *JMM, CodeGenOpt::Level OptLevel, bool GVsWithCode, CodeModel::Model CMM, StringRef MArch, StringRef MCPU, const SmallVectorImpl<std::string>& MAttrs) { // Try to register the program as a source of symbols to resolve against. // // FIXME: Don't do this here. sys::DynamicLibrary::LoadLibraryPermanently(0, NULL); // Pick a target either via -march or by guessing the native arch. // // FIXME: This should be lifted out of here, it isn't something which should // be part of the JIT policy, rather the burden for this selection should be // pushed to clients. TargetMachine *TM = MCJIT::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr); if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0; TM->setCodeModel(CMM); // If the target supports JIT code generation, create the JIT. if (TargetJITInfo *TJ = TM->getJITInfo()) return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM), OptLevel, GVsWithCode); if (ErrorStr) *ErrorStr = "target does not support JIT code generation"; return 0; } MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji, RTDyldMemoryManager *MM, CodeGenOpt::Level OptLevel, bool AllocateGVsWithCode) : ExecutionEngine(m), TM(tm), MemMgr(MM), M(m), OS(Buffer), Dyld(MM) { PM.add(new TargetData(*TM->getTargetData())); // Turn the machine code intermediate representation into bytes in memory // that may be executed. if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) { report_fatal_error("Target does not support MC emission!"); } // Initialize passes. // FIXME: When we support multiple modules, we'll want to move the code // gen and finalization out of the constructor here and do it more // on-demand as part of getPointerToFunction(). PM.run(*M); // Flush the output buffer so the SmallVector gets its data. OS.flush(); // Load the object into the dynamic linker. // FIXME: It would be nice to avoid making yet another copy. MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(), Buffer.size())); if (Dyld.loadObject(MB)) report_fatal_error(Dyld.getErrorString()); // Resolve any relocations. Dyld.resolveRelocations(); } MCJIT::~MCJIT() { delete MemMgr; } void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) { report_fatal_error("not yet implemented"); return 0; } void *MCJIT::getPointerToFunction(Function *F) { if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) { bool AbortOnFailure = !F->hasExternalWeakLinkage(); void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure); addGlobalMapping(F, Addr); return Addr; } Twine Name = TM->getMCAsmInfo()->getGlobalPrefix() + F->getName(); return (void*)Dyld.getSymbolAddress(Name.str()); } void *MCJIT::recompileAndRelinkFunction(Function *F) { report_fatal_error("not yet implemented"); } void MCJIT::freeMachineCodeForFunction(Function *F) { report_fatal_error("not yet implemented"); } GenericValue MCJIT::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert(F && "Function *F was null at entry to run()"); void *FPtr = getPointerToFunction(F); assert(FPtr && "Pointer to fn's code was null after getPointerToFunction"); const FunctionType *FTy = F->getFunctionType(); const Type *RetTy = FTy->getReturnType(); assert((FTy->getNumParams() == ArgValues.size() || (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) && "Wrong number of arguments passed into function!"); assert(FTy->getNumParams() == ArgValues.size() && "This doesn't support passing arguments through varargs (yet)!"); // Handle some common cases first. These cases correspond to common `main' // prototypes. if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) { switch (ArgValues.size()) { case 3: if (FTy->getParamType(0)->isIntegerTy(32) && FTy->getParamType(1)->isPointerTy() && FTy->getParamType(2)->isPointerTy()) { int (*PF)(int, char **, const char **) = (int(*)(int, char **, const char **))(intptr_t)FPtr; // Call the function. GenericValue rv; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), (char **)GVTOP(ArgValues[1]), (const char **)GVTOP(ArgValues[2]))); return rv; } break; case 2: if (FTy->getParamType(0)->isIntegerTy(32) && FTy->getParamType(1)->isPointerTy()) { int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr; // Call the function. GenericValue rv; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), (char **)GVTOP(ArgValues[1]))); return rv; } break; case 1: if (FTy->getNumParams() == 1 && FTy->getParamType(0)->isIntegerTy(32)) { GenericValue rv; int (*PF)(int) = (int(*)(int))(intptr_t)FPtr; rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue())); return rv; } break; } } // Handle cases where no arguments are passed first. if (ArgValues.empty()) { GenericValue rv; switch (RetTy->getTypeID()) { default: llvm_unreachable("Unknown return type for function call!"); case Type::IntegerTyID: { unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth(); if (BitWidth == 1) rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)()); else if (BitWidth <= 8) rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)()); else if (BitWidth <= 16) rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)()); else if (BitWidth <= 32) rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)()); else if (BitWidth <= 64) rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)()); else llvm_unreachable("Integer types > 64 bits not supported"); return rv; } case Type::VoidTyID: rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)()); return rv; case Type::FloatTyID: rv.FloatVal = ((float(*)())(intptr_t)FPtr)(); return rv; case Type::DoubleTyID: rv.DoubleVal = ((double(*)())(intptr_t)FPtr)(); return rv; case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID: llvm_unreachable("long double not supported yet"); return rv; case Type::PointerTyID: return PTOGV(((void*(*)())(intptr_t)FPtr)()); } } assert("Full-featured argument passing not supported yet!"); return GenericValue(); } <|endoftext|>
<commit_before>dde7e259-2e4e-11e5-ae97-28cfe91dbc4b<commit_msg>ddef509c-2e4e-11e5-b046-28cfe91dbc4b<commit_after>ddef509c-2e4e-11e5-b046-28cfe91dbc4b<|endoftext|>
<commit_before>b739039e-327f-11e5-aa8d-9cf387a8033e<commit_msg>b73f3111-327f-11e5-8fb0-9cf387a8033e<commit_after>b73f3111-327f-11e5-8fb0-9cf387a8033e<|endoftext|>
<commit_before>5f894953-2d16-11e5-af21-0401358ea401<commit_msg>5f894954-2d16-11e5-af21-0401358ea401<commit_after>5f894954-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f2567866-327f-11e5-b1ad-9cf387a8033e<commit_msg>f25cbc23-327f-11e5-bfcd-9cf387a8033e<commit_after>f25cbc23-327f-11e5-bfcd-9cf387a8033e<|endoftext|>
<commit_before>253e98e8-2d3e-11e5-91d2-c82a142b6f9b<commit_msg>259b6563-2d3e-11e5-a0dd-c82a142b6f9b<commit_after>259b6563-2d3e-11e5-a0dd-c82a142b6f9b<|endoftext|>
<commit_before>76a70ba1-4b02-11e5-a67b-28cfe9171a43<commit_msg>Nope, didn't work, now it does<commit_after>76b48c6e-4b02-11e5-9a54-28cfe9171a43<|endoftext|>
<commit_before>865e6694-4b02-11e5-a877-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>866c662e-4b02-11e5-a146-28cfe9171a43<|endoftext|>
<commit_before>74e0d32b-4b02-11e5-97a7-28cfe9171a43<commit_msg>fixed bug<commit_after>74ed93b0-4b02-11e5-a948-28cfe9171a43<|endoftext|>
<commit_before>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: peterharrison * * Created on 07 February 2016, 23:47 */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "maze.h" #include "mazeprinter.h" #include "mazesearcher.h" #include <glob.h> uint8_t wallData[1024]; enum { E_FILE_NOT_FOUND = 1, E_FILE_READ_ERROR = 2, }; int ReadRealWallsFromFile(char *filename) { FILE *fp; if ((fp = fopen(filename, "rb")) == NULL) { return E_FILE_NOT_FOUND; } if (fread(wallData, 1, 256, fp) < 256) { fclose(fp); return E_FILE_READ_ERROR; }; fclose(fp); return 0; } static char *strpad(const char *string, char pad, size_t fieldSize); char *strpad(const char *string, char pad, size_t fieldSize) { size_t ssize = strlen(string); size_t padSize = fieldSize - ssize; assert(padSize > 0); char padding[128]; memset(padding, pad, 126); padding[127] = 0; char *padded = (char *) malloc(fieldSize + 1); strncpy(padded, string, fieldSize); strncat(padded, padding, padSize); // memset(padded, pad, fieldSize); padded[fieldSize] = 0; // strcpy(padded , string); return padded; } /* * */ int main(int argc, char **argv) { MazeSearcher barney; glob_t glob_result; glob("./mazefiles/*", GLOB_TILDE, NULL, &glob_result); if (argc > 1) { Maze maze(16); int onePassCount = 0; int chancerCount = 0; printf(" FULL MODOPEN MODALL\n"); maze.setFloodType(Maze::RUNLENGTH_FLOOD); for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) { std::cout << ""; if (0 != ReadRealWallsFromFile(glob_result.gl_pathv[i])){ continue; }; maze.load(wallData); maze.copyMazeFromFileData(wallData, 256); maze.flood(0x77); barney.setRealMaze(&maze); barney.map()->resetToEmptyMaze(); barney.setLocation(0x00); int steps = barney.searchTo(0x77); steps += barney.searchTo(0x00); steps += barney.searchTo(0x77); steps += barney.searchTo(0x00); barney.map()->testForSolution(); int costDifference = barney.map()->costDifference(); int openCost = barney.map()->openMazeCost(); int residual = (100 * costDifference) / openCost; if (residual > 5) { MazePrinter::printVisitedDirs(barney.map()); } char *name = strpad(glob_result.gl_pathv[i], ' ', 50); std::cout << name; delete name; std::cout.width(6); std::cout << std::right; std::cout << steps << " steps"; std::cout << " delta " << costDifference << " (" << residual << "%)"; if (costDifference == 0) { onePassCount++; std::cout << " <---- "; } else if (residual < 5 && residual >= 0) { chancerCount++; std::cout << " ***** "; } std::cout << std::endl; } printf("\n%d mazes:\n", glob_result.gl_pathc); printf(" one Pass mazes: %3d\n", onePassCount); printf(" Possible chancer mazes: %3d\n", chancerCount); } else { printf(" you should provide the name of at least one libMaze file on the command line\n"); } return (EXIT_SUCCESS); } <commit_msg>correct transitive include in main.cpp and remove unused includes<commit_after>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: peterharrison * * Created on 07 February 2016, 23:47 */ #include <cstring> #include <iostream> #include "maze.h" #include "mazeprinter.h" #include "mazesearcher.h" #include <glob.h> uint8_t wallData[1024]; enum { E_FILE_NOT_FOUND = 1, E_FILE_READ_ERROR = 2, }; int ReadRealWallsFromFile(char *filename) { FILE *fp; if ((fp = fopen(filename, "rb")) == NULL) { return E_FILE_NOT_FOUND; } if (fread(wallData, 1, 256, fp) < 256) { fclose(fp); return E_FILE_READ_ERROR; }; fclose(fp); return 0; } static char *strpad(const char *string, char pad, size_t fieldSize); char *strpad(const char *string, char pad, size_t fieldSize) { size_t ssize = strlen(string); size_t padSize = fieldSize - ssize; assert(padSize > 0); char padding[128]; memset(padding, pad, 126); padding[127] = 0; char *padded = (char *) malloc(fieldSize + 1); strncpy(padded, string, fieldSize); strncat(padded, padding, padSize); // memset(padded, pad, fieldSize); padded[fieldSize] = 0; // strcpy(padded , string); return padded; } /* * */ int main(int argc, char **argv) { MazeSearcher barney; glob_t glob_result; glob("./mazefiles/*", GLOB_TILDE, NULL, &glob_result); if (argc > 1) { Maze maze(16); int onePassCount = 0; int chancerCount = 0; printf(" FULL MODOPEN MODALL\n"); maze.setFloodType(Maze::RUNLENGTH_FLOOD); for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) { std::cout << ""; if (0 != ReadRealWallsFromFile(glob_result.gl_pathv[i])){ continue; }; maze.load(wallData); maze.copyMazeFromFileData(wallData, 256); maze.flood(0x77); barney.setRealMaze(&maze); barney.map()->resetToEmptyMaze(); barney.setLocation(0x00); int steps = barney.searchTo(0x77); steps += barney.searchTo(0x00); steps += barney.searchTo(0x77); steps += barney.searchTo(0x00); barney.map()->testForSolution(); int costDifference = barney.map()->costDifference(); int openCost = barney.map()->openMazeCost(); int residual = (100 * costDifference) / openCost; if (residual > 5) { MazePrinter::printVisitedDirs(barney.map()); } char *name = strpad(glob_result.gl_pathv[i], ' ', 50); std::cout << name; delete name; std::cout.width(6); std::cout << std::right; std::cout << steps << " steps"; std::cout << " delta " << costDifference << " (" << residual << "%)"; if (costDifference == 0) { onePassCount++; std::cout << " <---- "; } else if (residual < 5 && residual >= 0) { chancerCount++; std::cout << " ***** "; } std::cout << std::endl; } printf("\n%d mazes:\n", glob_result.gl_pathc); printf(" one Pass mazes: %3d\n", onePassCount); printf(" Possible chancer mazes: %3d\n", chancerCount); } else { printf(" you should provide the name of at least one libMaze file on the command line\n"); } return (EXIT_SUCCESS); } <|endoftext|>
<commit_before>/* * File: main.cpp * Author: jasonlefley * * Created on June 17, 2015, 1:20 PM */ #include <cstdlib> #include "Zpp.h" int main(int argc, char** argv) { int i; #ifdef ZPP_INCLUDE_OPENALL zppZipArchive::openAll("*.zip"); zppZipArchive::dumpGlobalMap(); #endif /* ZPP_INCLUDE_OPENALL */ try { #ifndef ZPP_INCLUDE_OPENALL zppZipArchive zf1(std::string("zpp.zip")); #endif /* ZPP_INCLUDE_OPENALL */ izppstream fp; fp.open("readme.htm"); if (fp.fail()) { std::cerr << "can't open readme.htm" << std::endl; } std::cout << "<<contents of readme.htm>>" << std::endl; while (!fp.eof() && !fp.fail()) { char c; // do raw read of file so that newlines get read. // alternately, we could do fp->rdbuf() and use the // zppstreambuf object instead. fp.read(&c, 1); std::cout << c; } std::cout << "<<end of readme.htm>>" << std::endl; // EOF will be set here, so we need to clear it. fp.clear(std::ios::goodbit); // we can seek to the BEGINNING of a file, but nowhere // else, currently. fp.seekg(0, std::ios::beg); i = 0; while (i++ < 1000 && !fp.eof() && !fp.fail()) { char c; fp.read(&c, 1); std::cout << c; } std::cout << "<<end of dump of first 1000 bytes of readme.htm>>" << std::endl; fp.close(); fp.open("notinzip.txt"); if (fp.fail()) { std::cerr << "can't open notinzip.txt" << std::endl; std::exit(1); } std::cout << "<<contents of notinzip.txt>>" << std::endl; while (!fp.fail() && !fp.eof()) { char c; // do raw read of file so that newlines get read. // alternately, we could do fp->rdbuf() and use the // zppstreambuf object instead. fp.read(&c, 1); std::cout << c; } std::cout << "<<end of notinzip.txt>>" << std::endl; // EOF will be set here, so we need to clear it. fp.clear(std::ios::goodbit); // we can seek to the BEGINNING of a file, but nowhere // else, currently. fp.seekg(0, std::ios::beg); i = 0; while (i++ < 1000 && !fp.eof() && !fp.fail()) { char c; fp.read(&c, 1); std::cout << c; } std::cout << "<<end of dump of first 1000 bytes of notinzip.txt>>" << std::endl; } catch (zppError e) { std::cerr << "zppError: " << e.str << std::endl; } return 0; } <commit_msg>remove main<commit_after><|endoftext|>
<commit_before>5499b13e-5216-11e5-90e9-6c40088e03e4<commit_msg>54a3bf76-5216-11e5-a54e-6c40088e03e4<commit_after>54a3bf76-5216-11e5-a54e-6c40088e03e4<|endoftext|>
<commit_before>8fd04995-2d14-11e5-af21-0401358ea401<commit_msg>8fd04996-2d14-11e5-af21-0401358ea401<commit_after>8fd04996-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>350a8aa2-2e3a-11e5-a84e-c03896053bdd<commit_msg>35201258-2e3a-11e5-bc0d-c03896053bdd<commit_after>35201258-2e3a-11e5-bc0d-c03896053bdd<|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "Display.h" #include "InputValidator.h" #include "MetaParser.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <fstream> #include <cstdlib> #include <cctype> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #else #include <io.h> #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif using namespace clang; namespace cling { MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII( MetaProcessor* p) :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) { StringRef redirectionFile; if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); redirect(stdout, redirectionFile.str(), kSTDOUT); } if (!m_MetaProcessor->m_PrevStderrFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back(); // Deal with the case 2>&1 and 2&>1 if (strcmp(redirectionFile.data(), "_IO_2_1_stdout_") == 0) { // If out is redirected to a file. if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); } else { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } redirect(stderr, redirectionFile.str(), kSTDERR); } } void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file, const std::string& fileName, MetaProcessor::RedirectionScope scope) { if (!fileName.empty()) { FILE* redirectionFile = freopen(fileName.c_str(), "a", file); if (!redirectionFile) { llvm::errs()<<"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:" " Not succefully reopened the redirection file " << fileName.c_str() << "\n."; } else { m_isCurrentlyRedirecting |= scope; } } } void MetaProcessor::MaybeRedirectOutputRAII::pop() { if (m_isCurrentlyRedirecting & kSTDOUT) { unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout); } if (m_isCurrentlyRedirecting & kSTDERR) { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD, int expectedFD, FILE* file) { // Switch back to previous file after line is processed. // Flush the current content if there is any. if (!feof(file)) { fflush(file); } // Copy the original fd for the std. if (dup2(backupFD, expectedFD) != expectedFD) { llvm::errs() << "cling::MetaProcessor::unredirect " << "The unredirection file descriptor not valid " << backupFD << ".\n"; } } MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs) : m_Interp(interp), m_Outs(&outs) { m_InputValidator.reset(new InputValidator()); m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this))); m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO); m_backupFDStderr = copyFileDescriptor(STDERR_FILENO); } MetaProcessor::~MetaProcessor() {} int MetaProcessor::process(const char* input_text, Interpreter::CompilationResult& compRes, Value* result) { if (result) *result = Value(); compRes = Interpreter::kSuccess; int expectedIndent = m_InputValidator->getExpectedIndent(); if (expectedIndent) compRes = Interpreter::kMoreInputExpected; if (!input_text || !input_text[0]) { // nullptr / empty string, nothing to do. return expectedIndent; } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return expectedIndent; } // Check for and handle meta commands. m_MetaParser->enterNewInputLine(input_line); MetaSema::ActionResult actionResult = MetaSema::AR_Success; if (m_MetaParser->isMetaCommand(actionResult, result)) { if (m_MetaParser->isQuitRequested()) return -1; if (actionResult != MetaSema::AR_Success) compRes = Interpreter::kFailure; // ExpectedIndent might have changed after meta command. return m_InputValidator->getExpectedIndent(); } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) { compRes = Interpreter::kMoreInputExpected; return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input = m_InputValidator->getInput(); m_InputValidator->reset(); // if (m_Options.RawInput) // compResLocal = m_Interp.declare(input); // else compRes = m_Interp.process(input, result); return 0; } void MetaProcessor::cancelContinuation() const { m_InputValidator->reset(); } int MetaProcessor::getExpectedIndent() const { return m_InputValidator->getExpectedIndent(); } Interpreter::CompilationResult MetaProcessor::readInputFromFile(llvm::StringRef filename, Value* result, bool ignoreOutmostBlock /*=false*/) { { // check that it's not binary: std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary); char magic[1024] = {0}; in.read(magic, sizeof(magic)); size_t readMagic = in.gcount(); if (readMagic >= 4) { llvm::StringRef magicStr(magic,in.gcount()); llvm::sys::fs::file_magic fileType = llvm::sys::fs::identify_magic(magicStr); if (fileType != llvm::sys::fs::file_magic::unknown) { llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a binary file!\n"; return Interpreter::kFailure; } unsigned printable = 0; for (size_t i = 0; i < readMagic; ++i) if (isprint(magic[i])) ++printable; if (10 * printable < 5 * readMagic) { // 50% printable for ASCII files should be a safe guess. llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a (likely) binary file!\n" << printable; return Interpreter::kFailure; } } } std::ifstream in(filename.str().c_str()); in.seekg(0, std::ios::end); size_t size = in.tellg(); std::string content(size, ' '); in.seekg(0); in.read(&content[0], size); if (ignoreOutmostBlock && !content.empty()) { static const char whitespace[] = " \t\r\n"; std::string::size_type posNonWS = content.find_first_not_of(whitespace); // Handle comments before leading { while (content[posNonWS] == '/' && content[posNonWS+1] == '/') { // Remove the comment line posNonWS = content.find_first_of('\n', posNonWS+2)+1; } std::string::size_type replaced = posNonWS; if (posNonWS != std::string::npos) { if (content[posNonWS] == '{') { // hide the curly brace: content[posNonWS] = ' '; // and the matching closing '}' posNonWS = content.find_last_not_of(whitespace); if (posNonWS != std::string::npos) { if (content[posNonWS] == ';' && content[posNonWS-1] == '}') { content[posNonWS--] = ' '; // replace ';' and enter next if } if (content[posNonWS] == '}') { content[posNonWS] = ' '; // replace '}' } else { std::string::size_type posComment = content.find_last_of('}'); if (content[posComment] == '}') { content[posComment] = ' '; // replace '}' } posComment = content.find_first_not_of(whitespace, posComment); if (content[posComment] == '/' && content[posComment+1] == '/') { // More text (comments) are okay after the last '}', but // we can not easily find it to remove it (so we need to upgrade // this code to better handle the case with comments or // preprocessor code before and after the leading { and // trailing }) while (posComment <= posNonWS) { content[posComment++] = ' '; // replace '}' and comment } } else { content[replaced] = '{'; // By putting the '{' back, we keep the code as consistent as // the user wrote it ... but we should still warn that we not // goint to treat this file an unamed macro. llvm::errs() << "Warning in cling::MetaProcessor: can not find the closing '}', " << llvm::sys::path::filename(filename) << " is not handled as an unamed script!\n"; } // did not find '}'' } // remove comments after the trailing '}' } // find '}' } // have '{' } // have non-whitespace } // ignore outmost block std::string strFilename(filename.str()); m_CurrentlyExecutingFile = strFilename; bool topmost = !m_TopExecutingFile.data(); if (topmost) m_TopExecutingFile = m_CurrentlyExecutingFile; Interpreter::CompilationResult ret; // We don't want to value print the results of a unnamed macro. content = "#line 2 \"" + filename.str() + "\" \n" + content; if (process((content + ";").c_str(), ret, result)) { // Input file has to be complete. llvm::errs() << "Error in cling::MetaProcessor: file " << llvm::sys::path::filename(filename) << " is incomplete (missing parenthesis or similar)!\n"; ret = Interpreter::kFailure; } m_CurrentlyExecutingFile = llvm::StringRef(); if (topmost) m_TopExecutingFile = llvm::StringRef(); return ret; } void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd, llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) { // If we have a fileName to redirect to store it. if (!file.empty()) { prevFileStack.push_back(file); // pop and push a null terminating 0. // SmallVectorImpl<T> does not have a c_str(), thus instead of casting to // a SmallString<T> we null terminate the data that we have and pop the // 0 char back. prevFileStack.back().push_back(0); prevFileStack.back().pop_back(); if (!append) { FILE * f; if (!(f = fopen(file.data(), "w"))) { llvm::errs() << "cling::MetaProcessor::setFileStream:" " The file path " << file.data() << "is not valid."; } else { fclose(f); } } // Else unredirection, so switch to the previous file. } else { // If there is no previous file on the stack we pop the file if (!prevFileStack.empty()) { prevFileStack.pop_back(); } } } void MetaProcessor::setStdStream(llvm::StringRef file, RedirectionScope stream, bool append) { if (stream & kSTDOUT) { setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName); } if (stream & kSTDERR) { setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName); } } int MetaProcessor::copyFileDescriptor(int fd) { int backupFD = dup(fd); if (backupFD < 0) { llvm::errs() << "MetaProcessor::copyFileDescriptor: Duplicating the file" " descriptor " << fd << "resulted in an error." " Will not be able to unredirect."; } return backupFD; } void MetaProcessor::registerUnloadPoint(const Transaction* T, llvm::StringRef filename) { m_MetaParser->getActions().registerUnloadPoint(T, filename); } } // end namespace cling <commit_msg>Handle npos / not found (Coverity 55588); indentation; local vars.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "Display.h" #include "InputValidator.h" #include "MetaParser.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <fstream> #include <cstdlib> #include <cctype> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #else #include <io.h> #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif using namespace clang; namespace cling { MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII( MetaProcessor* p) :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) { StringRef redirectionFile; if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); redirect(stdout, redirectionFile.str(), kSTDOUT); } if (!m_MetaProcessor->m_PrevStderrFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back(); // Deal with the case 2>&1 and 2&>1 if (strcmp(redirectionFile.data(), "_IO_2_1_stdout_") == 0) { // If out is redirected to a file. if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); } else { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } redirect(stderr, redirectionFile.str(), kSTDERR); } } void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file, const std::string& fileName, MetaProcessor::RedirectionScope scope) { if (!fileName.empty()) { FILE* redirectionFile = freopen(fileName.c_str(), "a", file); if (!redirectionFile) { llvm::errs()<<"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:" " Not succefully reopened the redirection file " << fileName.c_str() << "\n."; } else { m_isCurrentlyRedirecting |= scope; } } } void MetaProcessor::MaybeRedirectOutputRAII::pop() { if (m_isCurrentlyRedirecting & kSTDOUT) { unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout); } if (m_isCurrentlyRedirecting & kSTDERR) { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD, int expectedFD, FILE* file) { // Switch back to previous file after line is processed. // Flush the current content if there is any. if (!feof(file)) { fflush(file); } // Copy the original fd for the std. if (dup2(backupFD, expectedFD) != expectedFD) { llvm::errs() << "cling::MetaProcessor::unredirect " << "The unredirection file descriptor not valid " << backupFD << ".\n"; } } MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs) : m_Interp(interp), m_Outs(&outs) { m_InputValidator.reset(new InputValidator()); m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this))); m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO); m_backupFDStderr = copyFileDescriptor(STDERR_FILENO); } MetaProcessor::~MetaProcessor() {} int MetaProcessor::process(const char* input_text, Interpreter::CompilationResult& compRes, Value* result) { if (result) *result = Value(); compRes = Interpreter::kSuccess; int expectedIndent = m_InputValidator->getExpectedIndent(); if (expectedIndent) compRes = Interpreter::kMoreInputExpected; if (!input_text || !input_text[0]) { // nullptr / empty string, nothing to do. return expectedIndent; } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return expectedIndent; } // Check for and handle meta commands. m_MetaParser->enterNewInputLine(input_line); MetaSema::ActionResult actionResult = MetaSema::AR_Success; if (m_MetaParser->isMetaCommand(actionResult, result)) { if (m_MetaParser->isQuitRequested()) return -1; if (actionResult != MetaSema::AR_Success) compRes = Interpreter::kFailure; // ExpectedIndent might have changed after meta command. return m_InputValidator->getExpectedIndent(); } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) { compRes = Interpreter::kMoreInputExpected; return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input = m_InputValidator->getInput(); m_InputValidator->reset(); // if (m_Options.RawInput) // compResLocal = m_Interp.declare(input); // else compRes = m_Interp.process(input, result); return 0; } void MetaProcessor::cancelContinuation() const { m_InputValidator->reset(); } int MetaProcessor::getExpectedIndent() const { return m_InputValidator->getExpectedIndent(); } Interpreter::CompilationResult MetaProcessor::readInputFromFile(llvm::StringRef filename, Value* result, bool ignoreOutmostBlock /*=false*/) { { // check that it's not binary: std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary); char magic[1024] = {0}; in.read(magic, sizeof(magic)); size_t readMagic = in.gcount(); if (readMagic >= 4) { llvm::StringRef magicStr(magic,in.gcount()); llvm::sys::fs::file_magic fileType = llvm::sys::fs::identify_magic(magicStr); if (fileType != llvm::sys::fs::file_magic::unknown) { llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a binary file!\n"; return Interpreter::kFailure; } unsigned printable = 0; for (size_t i = 0; i < readMagic; ++i) if (isprint(magic[i])) ++printable; if (10 * printable < 5 * readMagic) { // 50% printable for ASCII files should be a safe guess. llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a (likely) binary file!\n" << printable; return Interpreter::kFailure; } } } std::ifstream in(filename.str().c_str()); in.seekg(0, std::ios::end); size_t size = in.tellg(); std::string content(size, ' '); in.seekg(0); in.read(&content[0], size); if (ignoreOutmostBlock && !content.empty()) { static const char whitespace[] = " \t\r\n"; std::string::size_type posNonWS = content.find_first_not_of(whitespace); // Handle comments before leading { while (content[posNonWS] == '/' && content[posNonWS+1] == '/') { // Remove the comment line posNonWS = content.find_first_of('\n', posNonWS+2)+1; } std::string::size_type replaced = posNonWS; if (posNonWS != std::string::npos) { if (content[posNonWS] == '{') { // hide the curly brace: content[posNonWS] = ' '; // and the matching closing '}' posNonWS = content.find_last_not_of(whitespace); if (posNonWS != std::string::npos) { if (content[posNonWS] == ';' && content[posNonWS-1] == '}') { content[posNonWS--] = ' '; // replace ';' and enter next if } if (content[posNonWS] == '}') { content[posNonWS] = ' '; // replace '}' } else { std::string::size_type posBlockClose = content.find_last_of('}'); if (posBlockClose != std::string::npos) { content[posBlockClose] = ' '; // replace '}' } std::string::size_type posComment = content.find_first_not_of(whitespace, posComment); if (content[posComment] == '/' && content[posComment+1] == '/') { // More text (comments) are okay after the last '}', but // we can not easily find it to remove it (so we need to upgrade // this code to better handle the case with comments or // preprocessor code before and after the leading { and // trailing }) while (posComment <= posNonWS) { content[posComment++] = ' '; // replace '}' and comment } } else { content[replaced] = '{'; // By putting the '{' back, we keep the code as consistent as // the user wrote it ... but we should still warn that we not // goint to treat this file an unamed macro. llvm::errs() << "Warning in cling::MetaProcessor: can not find the closing '}', " << llvm::sys::path::filename(filename) << " is not handled as an unamed script!\n"; } // did not find '}'' } // remove comments after the trailing '}' } // find '}' } // have '{' } // have non-whitespace } // ignore outmost block std::string strFilename(filename.str()); m_CurrentlyExecutingFile = strFilename; bool topmost = !m_TopExecutingFile.data(); if (topmost) m_TopExecutingFile = m_CurrentlyExecutingFile; Interpreter::CompilationResult ret; // We don't want to value print the results of a unnamed macro. content = "#line 2 \"" + filename.str() + "\" \n" + content; if (process((content + ";").c_str(), ret, result)) { // Input file has to be complete. llvm::errs() << "Error in cling::MetaProcessor: file " << llvm::sys::path::filename(filename) << " is incomplete (missing parenthesis or similar)!\n"; ret = Interpreter::kFailure; } m_CurrentlyExecutingFile = llvm::StringRef(); if (topmost) m_TopExecutingFile = llvm::StringRef(); return ret; } void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd, llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) { // If we have a fileName to redirect to store it. if (!file.empty()) { prevFileStack.push_back(file); // pop and push a null terminating 0. // SmallVectorImpl<T> does not have a c_str(), thus instead of casting to // a SmallString<T> we null terminate the data that we have and pop the // 0 char back. prevFileStack.back().push_back(0); prevFileStack.back().pop_back(); if (!append) { FILE * f; if (!(f = fopen(file.data(), "w"))) { llvm::errs() << "cling::MetaProcessor::setFileStream:" " The file path " << file.data() << "is not valid."; } else { fclose(f); } } // Else unredirection, so switch to the previous file. } else { // If there is no previous file on the stack we pop the file if (!prevFileStack.empty()) { prevFileStack.pop_back(); } } } void MetaProcessor::setStdStream(llvm::StringRef file, RedirectionScope stream, bool append) { if (stream & kSTDOUT) { setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName); } if (stream & kSTDERR) { setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName); } } int MetaProcessor::copyFileDescriptor(int fd) { int backupFD = dup(fd); if (backupFD < 0) { llvm::errs() << "MetaProcessor::copyFileDescriptor: Duplicating the file" " descriptor " << fd << "resulted in an error." " Will not be able to unredirect."; } return backupFD; } void MetaProcessor::registerUnloadPoint(const Transaction* T, llvm::StringRef filename) { m_MetaParser->getActions().registerUnloadPoint(T, filename); } } // end namespace cling <|endoftext|>
<commit_before>f24bb399-2d3c-11e5-8d4e-c82a142b6f9b<commit_msg>f2d4e868-2d3c-11e5-b305-c82a142b6f9b<commit_after>f2d4e868-2d3c-11e5-b305-c82a142b6f9b<|endoftext|>
<commit_before>c341899c-4b02-11e5-a7dd-28cfe9171a43<commit_msg>No longer crashes if X<commit_after>c34fe7d9-4b02-11e5-bf28-28cfe9171a43<|endoftext|>