text
stringlengths
54
60.6k
<commit_before>72a8993d-2d3f-11e5-81fd-c82a142b6f9b<commit_msg>73212317-2d3f-11e5-bcbe-c82a142b6f9b<commit_after>73212317-2d3f-11e5-bcbe-c82a142b6f9b<|endoftext|>
<commit_before>#include <cstdlib> #include <cstdio> #include <signal.h> #include <getopt.h> int main(int argc, char** argv) { unsigned num_conn = 1; unsigned rem_port = 0; unsigned loc_port = 0; unsigned interval = 0; unsigned length = 0; int opt; while ((opt = getopt(argc, argv, ":hc:p:q:n:i:")) != -1) { char* ptr; switch (opt) { case ':': fprintf(stderr, "Option %s requires a value\n", argv[optind-1]); return ':'; case '?': fprintf(stderr, "Ignoring unknown option '%c'\n", optopt); break; case 'h': // TODO: Give usage return 'h'; case 'c': ptr = NULL; if ((num_conn = strtoul(optarg, &ptr, 0)) > 1024 || num_conn < 1 || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -c requires a valid number of connections [1-1024]\n"); return 'c'; } break; case 'p': ptr = NULL; if ((rem_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -p requires a valid port number [0-65535]\n"); return 'p'; } break; case 'q': ptr = NULL; if ((loc_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -q requires a valid port number [0-65535]\n"); return 'p'; } break; case 'n': ptr = NULL; if ((length = strtoul(optarg, &ptr, 0)) > BUFFER_SIZE || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -n requires a chunk size in bytes [1-%d] or 0 for off\n", BUFFER_SIZE); return 'n'; } break; case 'i': ptr = NULL; if ((interval = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -i requires an interval in milliseconds [1-65535] or 0 for off\n"); return 'i'; } break; } } if (optind < argc && rem_port == 0) { fprintf(stderr, "Option -p is required for client\n"); return 'p'; } else if (optind == argc && loc_port == 0) { fprintf(stderr, "Option -q is required for server\n"); return 'q'; } return 0; } <commit_msg>added comments<commit_after>#include <tr1/memory> #include <vector> #include <cstdlib> #include <cstdio> #include <signal.h> #include <getopt.h> #include "barrier.h" using std::vector; using std::tr1::shared_ptr; void terminate(void) { } int main(int argc, char** argv) { unsigned num_conn = 1; unsigned rem_port = 0; unsigned loc_port = 0; unsigned interval = 0; unsigned length = 0; // Parse program arguments and options int opt; while ((opt = getopt(argc, argv, ":hc:p:q:n:i:")) != -1) { char* ptr; switch (opt) { // Missing a value for the option case ':': fprintf(stderr, "Option %s requires a value\n", argv[optind-1]); return ':'; // Unknown option was given case '?': fprintf(stderr, "Ignoring unknown option '%c'\n", optopt); break; // Print program usage and quit case 'h': // TODO: Give usage return 'h'; // Set number of connections case 'c': ptr = NULL; if ((num_conn = strtoul(optarg, &ptr, 0)) > 1024 || num_conn < 1 || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -c requires a valid number of connections [1-1024]\n"); return 'c'; } break; // Set the remote starting port case 'p': ptr = NULL; if ((rem_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -p requires a valid port number [0-65535]\n"); return 'p'; } break; // Set the local starting port case 'q': ptr = NULL; if ((loc_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -q requires a valid port number [0-65535]\n"); return 'p'; } break; // Set the size of the byte chunk to be sent case 'n': ptr = NULL; if ((length = strtoul(optarg, &ptr, 0)) > BUFFER_SIZE || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -n requires a chunk size in bytes [1-%d] or 0 for off\n", BUFFER_SIZE); return 'n'; } break; // Set the interval between each time a chunk is sent case 'i': ptr = NULL; if ((interval = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -i requires an interval in milliseconds [1-65535] or 0 for off\n"); return 'i'; } break; } } // Check if all mandatory options were set if (optind < argc && rem_port == 0) { fprintf(stderr, "Option -p is required for client\n"); return 'p'; } else if (optind == argc && loc_port == 0) { fprintf(stderr, "Option -q is required for server\n"); return 'q'; } // Handle interrupt signal signal(SIGINT, (void (*)(int)) &terminate); // Create a barrier Barrier barrier(num_conn); return 0; } <|endoftext|>
<commit_before>856279a9-2d15-11e5-af21-0401358ea401<commit_msg>856279aa-2d15-11e5-af21-0401358ea401<commit_after>856279aa-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>520c32ee-2e4f-11e5-9df7-28cfe91dbc4b<commit_msg>5212f745-2e4f-11e5-a3a8-28cfe91dbc4b<commit_after>5212f745-2e4f-11e5-a3a8-28cfe91dbc4b<|endoftext|>
<commit_before>1c207bd4-2e4f-11e5-96b3-28cfe91dbc4b<commit_msg>1c27b938-2e4f-11e5-88f2-28cfe91dbc4b<commit_after>1c27b938-2e4f-11e5-88f2-28cfe91dbc4b<|endoftext|>
<commit_before>6e9b986b-2e4f-11e5-ba16-28cfe91dbc4b<commit_msg>6ea3e4c2-2e4f-11e5-bca2-28cfe91dbc4b<commit_after>6ea3e4c2-2e4f-11e5-bca2-28cfe91dbc4b<|endoftext|>
<commit_before>76432046-2d53-11e5-baeb-247703a38240<commit_msg>76439ce2-2d53-11e5-baeb-247703a38240<commit_after>76439ce2-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>9f8df67a-2e4f-11e5-bb54-28cfe91dbc4b<commit_msg>9f95dc02-2e4f-11e5-a771-28cfe91dbc4b<commit_after>9f95dc02-2e4f-11e5-a771-28cfe91dbc4b<|endoftext|>
<commit_before>e9d021dc-2e4e-11e5-a071-28cfe91dbc4b<commit_msg>e9d6cc8c-2e4e-11e5-9e27-28cfe91dbc4b<commit_after>e9d6cc8c-2e4e-11e5-9e27-28cfe91dbc4b<|endoftext|>
<commit_before>761e70ac-2d53-11e5-baeb-247703a38240<commit_msg>761eefd2-2d53-11e5-baeb-247703a38240<commit_after>761eefd2-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>e6f0f705-313a-11e5-8d00-3c15c2e10482<commit_msg>e6f71d8c-313a-11e5-a581-3c15c2e10482<commit_after>e6f71d8c-313a-11e5-a581-3c15c2e10482<|endoftext|>
<commit_before>e6f5ed42-327f-11e5-8ce7-9cf387a8033e<commit_msg>e6fbb6d1-327f-11e5-9b79-9cf387a8033e<commit_after>e6fbb6d1-327f-11e5-9b79-9cf387a8033e<|endoftext|>
<commit_before>#include <iostream> //GLEW #define GLEW_STATIC #include <G:\My Documents\comp 371\assgt2\glew-1.13.0-win32\glew-1.13.0\include\GL\glew.h> //GLFW #include <G:\My Documents\comp 371\assgt2\glfw-3.1.2.bin.WIN32\glfw-3.1.2.bin.WIN32\include\GLFW\glfw3.h> // GLM #include <G:\My Documents\comp 371\assgt2\glm-0.9.6.3\glm\glm\gtc\matrix_transform.hpp> #include <G:\My Documents\comp 371\assgt2\glm-0.9.6.3\glm\glm\gtc\type_ptr.hpp> #include <G:\My Documents\comp 371\assgt2\glm-0.9.6.3\glm\glm\glm.hpp> #include <G:\My Documents\comp 371\assgt2\assgt2\Shader.h> //set my window dimensions const GLuint WIDTH = 800, HEIGHT = 800; //set callback functions here void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); void cursor_position_callback(GLFWwindow* window, double xpos,double ypos); //certain useful variables double xpos, ypos; int numOfPoints; int pointsLeft; int currentIndex; bool keys[1024]; GLfloat fov = 45.0f; glm::vec3 arrayCoordinate[25]; glm::vec3 bezierCoordinate[800]; bool draw = false; //set certain functions float bezierX(double p1x, double p2x, double p3x, double p4x, double t); float bezierY(double p1y, double p2y, double p3y, double p4y, double t); void drawBezier(GLfloat controlPoints[], int j); int askForPoints(); GLfloat bezierCurve(float t, GLfloat P0, GLfloat P1, GLfloat P2, GLfloat P3); void bezierfunction(glm::vec3 array[]); GLfloat deltaTime = 0.0f; // Time between current frame and last frame GLfloat lastFrame = 0.0f; // Time of last frame //CAMERA SETUP glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 7.0f); glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f); glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f); //main program int main() { pointsLeft = askForPoints(); numOfPoints = pointsLeft; currentIndex = 0; //GLFW init glfwInit(); //All required options to make it work // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); //double buffering here glfwWindowHint(GLFW_DOUBLEBUFFER, GL_TRUE); //make window here GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Assignment 2", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions //keys glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, cursor_position_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); // Setup OpenGL options glEnable(GL_DEPTH_TEST); glEnable(GL_PROGRAM_POINT_SIZE); //Shader Shader ourShader("<G:\My Documents\comp 371\assgt2\assgt2\Shader.vs>","<G:\My Documents\comp 371\assgt2\assgt2\Shader.frag>"); //use this do draw the points after GLfloat vertices[] = { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }; //make the arrays GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); // specifies how vertex array will be processed. glEnableVertexAttribArray(0); // enables the setting above // Color attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); //specifies what position in data is refered to for color. glEnableVertexAttribArray(2); // enables the setting above. glBindVertexArray(0); // Unbinds the VAO glPointSize(4.5f); //loop while (!glfwWindowShouldClose(window)) { // Calculate deltatime of current frame GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwGetCursorPos(window, &xpos, &ypos); glClearColor(0.5f, 0.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ourShader.Use(); glm::mat4 view; glm::mat4 projection; projection = glm::ortho(0.0f, (GLfloat)WIDTH, (GLfloat)HEIGHT, 0.0f, 0.1f, 100.0f); view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); //get locations GLint modelLoc = glGetUniformLocation(ourShader.Program, "model"); GLint viewLoc = glGetUniformLocation(ourShader.Program, "view"); GLint projLoc = glGetUniformLocation(ourShader.Program, "projection"); //pass to shaders glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); // Draw points glBindVertexArray(VAO); if (draw == false) { for (GLuint j = 0; j < numOfPoints; j++) { glm::mat4 model; glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); model = glm::translate(model, arrayCoordinate[j]); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_POINTS, 0, 1); } } else { for (int i = 0; i < sizeof(bezierCoordinate); i++) { glm::mat4 model; glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); model = glm::translate(model, bezierCoordinate[i]); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_POINTS, 0, 1); } } glBindVertexArray(0); glfwSwapBuffers(window); } //clean up memory glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glfwTerminate(); return 0; } int askForPoints() { bool done = false; while (!done) { std::cout << "Please enter a number of points (N) for the Bezier Splines"<< std::endl; std::cin >> numOfPoints; if (numOfPoints <= 3) { std::cout << "The number you entered is not valid, please enter another number of points (N) for the bezier Splines (greater than 3)" << std::endl; } else { std::cout << "Your number of points (N) is :" << numOfPoints<< std::endl; done = true; } } return numOfPoints; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { //escape closes window if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ glfwSetWindowShouldClose(window, GL_TRUE); } if (key == GLFW_KEY_L && action == GLFW_PRESS) //draw spline as line { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } if (key == GLFW_KEY_H && action == GLFW_PRESS) { bezierfunction(arrayCoordinate); /*glPointSize(5.0); glColor3f(1.0, 1.0, 0.0); glBegin(GL_POINTS); for (int i = 0; i < sizeof(bezierCoordinate); i++){ GLfloat holder[1][3]; holder[0][0] = bezierCoordinate[i].x; holder[0][1] = bezierCoordinate[i].y; holder[0][2] = bezierCoordinate[i].z; glVertex3fv(holder[0]); } glEnd(); glFlush();*/ draw = true; } if (key == GLFW_KEY_ENTER && action == GLFW_PRESS)// draw spline as fill glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); if (key == GLFW_KEY_P && action == GLFW_PRESS) // draw spline as points { glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); } } void cursor_position_callback(GLFWwindow* window, double xpos, double ypos) { } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { if (pointsLeft != 0) { //double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); std::cout << "X :" << xpos << std::endl; std::cout << "Y :" << ypos << std::endl; //save them in an array arrayCoordinate[currentIndex].x = (GLfloat)xpos; arrayCoordinate[currentIndex].y = (GLfloat)ypos;//to fix inverted Y axis, do HEIGHT - ypos arrayCoordinate[currentIndex].z = 0.0f; currentIndex++; pointsLeft--; std::cout << "You have " << pointsLeft << " points left to chose." << std::endl; } } } //B(t) = (1-t^3)P0 + 3(1-t)^2P1 + 3(1-t)t^2P2 + t^3P3 float bezierX(double p1x, double p2x, double p3x, double p4x, double t) { float answer; answer = (pow((1-t),3.0)*p1x)+(3*pow((1-t),2)*t*p2x)+(3*(1-t)*t*t*p3x)+(pow(t,3)*p4x); return answer; } float bezierY(double p1y, double p2y, double p3y, double p4y, double t) { float answer; answer = (pow((1 - t), 3.0)*p1y) + (3 * pow((1 - t), 2)*t*p2y) + (3 * (1 - t)*t*t*p3y) + (pow(t, 3)*p4y); return answer; } void drawBezier(GLfloat controlPoints[], int j) { double t; float x; float y; for (int i = 1; i <= 40; i++)//40 is the number of segments we want in each one of our bezier splines { //go through T values t = i / 40.0; //calculate x coordinate and y coordinate x=bezierX(controlPoints[0], controlPoints[2], controlPoints[4], controlPoints[6],t); y=bezierY(controlPoints[1], controlPoints[3], controlPoints[5], controlPoints[7],t); //now save x and y into a new array, which only holds values of points on the spline bezierCoordinate[i-1+j*40].x = x; bezierCoordinate[i-1+j*40].y = y; bezierCoordinate[i-1+j*40].z = 0.0f; //DRAW THE bezierCoordinate array now } } void bezierfunction(glm::vec3 array[]) { int splineNum; GLfloat controlPoints[8]; splineNum = ((numOfPoints - 4) / 3) + 1;//number of seperate bezier splines we will print std::cout << "You will have " << splineNum << " bezier splines." << std::endl; for (int i = 0; i < splineNum; i++)//for each of these splines, save 4 clicked points (in the right order) { controlPoints[0] = (GLfloat)array[i*3].x; controlPoints[1] = (GLfloat)array[i * 3].y; controlPoints[2] = (GLfloat)array[i * 3 + 1].x; controlPoints[3] = (GLfloat)array[i * 3 + 1].y; controlPoints[4] = (GLfloat)array[i * 3 + 2].x; controlPoints[5] = (GLfloat)array[i * 3 + 2].y; controlPoints[6] = (GLfloat)array[i * 3 + 3].x; controlPoints[7] = (GLfloat)array[i * 3 + 3].y; drawBezier(controlPoints, i); } } <commit_msg>Delete main.cpp<commit_after><|endoftext|>
<commit_before>4f4e0219-2e4f-11e5-9835-28cfe91dbc4b<commit_msg>4f564b97-2e4f-11e5-b414-28cfe91dbc4b<commit_after>4f564b97-2e4f-11e5-b414-28cfe91dbc4b<|endoftext|>
<commit_before>b3f697ec-35ca-11e5-8df0-6c40088e03e4<commit_msg>b3fe17b8-35ca-11e5-a484-6c40088e03e4<commit_after>b3fe17b8-35ca-11e5-a484-6c40088e03e4<|endoftext|>
<commit_before>4db26f3a-5216-11e5-8fed-6c40088e03e4<commit_msg>4db97f70-5216-11e5-a2d8-6c40088e03e4<commit_after>4db97f70-5216-11e5-a2d8-6c40088e03e4<|endoftext|>
<commit_before>8cb2b2d8-35ca-11e5-bb91-6c40088e03e4<commit_msg>8cb9105e-35ca-11e5-b926-6c40088e03e4<commit_after>8cb9105e-35ca-11e5-b926-6c40088e03e4<|endoftext|>
<commit_before>1126816e-2d3d-11e5-b79c-c82a142b6f9b<commit_msg>11b7a426-2d3d-11e5-8eb2-c82a142b6f9b<commit_after>11b7a426-2d3d-11e5-8eb2-c82a142b6f9b<|endoftext|>
<commit_before>6f0a0bd9-4b02-11e5-9917-28cfe9171a43<commit_msg>Nooooooooooooooooooooooooooooooooooooo<commit_after>6f16cb66-4b02-11e5-bc29-28cfe9171a43<|endoftext|>
<commit_before>75de6c96-2d53-11e5-baeb-247703a38240<commit_msg>75deeb76-2d53-11e5-baeb-247703a38240<commit_after>75deeb76-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>f7f7831e-585a-11e5-85fd-6c40088e03e4<commit_msg>f7ff6dda-585a-11e5-ac21-6c40088e03e4<commit_after>f7ff6dda-585a-11e5-ac21-6c40088e03e4<|endoftext|>
<commit_before>75745f54-2d53-11e5-baeb-247703a38240<commit_msg>7574e47e-2d53-11e5-baeb-247703a38240<commit_after>7574e47e-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>c9436678-35ca-11e5-a81d-6c40088e03e4<commit_msg>c94a34f8-35ca-11e5-8456-6c40088e03e4<commit_after>c94a34f8-35ca-11e5-8456-6c40088e03e4<|endoftext|>
<commit_before>a3ee839c-4b02-11e5-9f8d-28cfe9171a43<commit_msg>Too poor for Dropbox<commit_after>a3fd22d1-4b02-11e5-b580-28cfe9171a43<|endoftext|>
<commit_before>b60ce2bd-2e4f-11e5-b2c8-28cfe91dbc4b<commit_msg>b613b2f5-2e4f-11e5-8720-28cfe91dbc4b<commit_after>b613b2f5-2e4f-11e5-8720-28cfe91dbc4b<|endoftext|>
<commit_before>a6316d24-35ca-11e5-8fa0-6c40088e03e4<commit_msg>a637d2e8-35ca-11e5-99de-6c40088e03e4<commit_after>a637d2e8-35ca-11e5-99de-6c40088e03e4<|endoftext|>
<commit_before>ebea52fa-2e4e-11e5-abc4-28cfe91dbc4b<commit_msg>ebf7d2f5-2e4e-11e5-86df-28cfe91dbc4b<commit_after>ebf7d2f5-2e4e-11e5-86df-28cfe91dbc4b<|endoftext|>
<commit_before>698cc800-2d3f-11e5-99f7-c82a142b6f9b<commit_msg>6a4e70d9-2d3f-11e5-9a51-c82a142b6f9b<commit_after>6a4e70d9-2d3f-11e5-9a51-c82a142b6f9b<|endoftext|>
<commit_before>#include <iostream> #include <boost/mpl/unique.hpp> #include <boost/mpl/equal.hpp> #include <boost/mpl/size.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/fusion/container/map.hpp> #include <boost/fusion/include/map.hpp> #include <boost/fusion/container/map/map_fwd.hpp> #include <boost/fusion/include/map_fwd.hpp> #include <boost/fusion/support/pair.hpp> #include <boost/fusion/include/pair.hpp> #include <boost/fusion/sequence/intrinsic/has_key.hpp> #include <boost/fusion/include/has_key.hpp> #include <boost/fusion/sequence/intrinsic/at_key.hpp> #include <boost/fusion/include/at_key.hpp> #include <boost/type_traits/is_same.hpp> /***************************************************************************/ template<typename... Types> struct impl_container { template<typename... Args> impl_container(const Args&... args) :cont(boost::fusion::make_pair<Types>(args...)...) {} template<typename Iface> Iface& get() { enum { value = boost::fusion::result_of::has_key<cont_type, Iface>::value }; static_assert(value, "doesn't contain implementation with this type"); return checker_helper<void, value>::template apply<Iface>(cont); } template<typename Iface> const Iface& get() const { enum { value = boost::fusion::result_of::has_key<cont_type, Iface>::value }; static_assert(value, "doesn't contain implementation with this type"); return checker_helper<void, value>::template apply<Iface>(cont); } private: template<typename, bool> struct checker_helper; template<typename Fake> struct checker_helper<Fake, true> { template<typename T, typename Map> static const T& apply(const Map& map) { return boost::fusion::at_key<T>(map); } template<typename T, typename Map> static T& apply(Map& map) { return boost::fusion::at_key<T>(map); } }; template<typename Fake> struct checker_helper<Fake, false> { template<typename T, typename Map> static const T& apply(const Map&) {} template<typename T, typename Map> static T& apply(Map&) {} }; private: using cont_type = boost::fusion::map< boost::fusion::pair<Types, Types>... >; cont_type cont; private: using _1 = boost::mpl::placeholders::_1; using _2 = boost::mpl::placeholders::_2; using types = boost::mpl::vector<Types...>; static_assert( boost::mpl::size< typename boost::mpl::unique<types, boost::is_same<_1, _2>>::type >::value == sizeof...(Types) ,"only unique types allowed" ); }; /***************************************************************************/ struct type1 { int v; type1(int v) :v(v) {} int m() const { return v+v; } }; struct type2 { int v; type2(int v) :v(v) {} int m() const { return v+v+v; } }; struct type3 { int v; type3(int v) :v(v) {} int m() const { return v+v+v+v; } }; struct type4 { int v; type4(int v) :v(v) {} int m() const { return v+v+v+v+v; } }; /***************************************************************************/ int main() { //impl_container<type1, type1> cont(2); // static assertion: 'only unique types allowed' impl_container<type1, type2, type3> cont(2); std::cout << cont.get<type1>().m() << std::endl; // 4 std::cout << cont.get<type2>().m() << std::endl; // 6 std::cout << cont.get<type3>().m() << std::endl; // 8 //std::cout << cont.get<type4>().m() << std::endl; // static assertion: 'doesn't contains implementation with this type' } /***************************************************************************/ <commit_msg>static assertion message fixed<commit_after>#include <iostream> #include <boost/mpl/unique.hpp> #include <boost/mpl/equal.hpp> #include <boost/mpl/size.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/fusion/container/map.hpp> #include <boost/fusion/include/map.hpp> #include <boost/fusion/container/map/map_fwd.hpp> #include <boost/fusion/include/map_fwd.hpp> #include <boost/fusion/support/pair.hpp> #include <boost/fusion/include/pair.hpp> #include <boost/fusion/sequence/intrinsic/has_key.hpp> #include <boost/fusion/include/has_key.hpp> #include <boost/fusion/sequence/intrinsic/at_key.hpp> #include <boost/fusion/include/at_key.hpp> #include <boost/type_traits/is_same.hpp> /***************************************************************************/ template<typename... Types> struct impl_container { template<typename... Args> impl_container(const Args&... args) :cont(boost::fusion::make_pair<Types>(args...)...) {} template<typename Iface> Iface& get() { enum { value = boost::fusion::result_of::has_key<cont_type, Iface>::value }; static_assert(value, "impl_container doesn't contains implementation with this type"); return checker_helper<void, value>::template apply<Iface>(cont); } template<typename Iface> const Iface& get() const { enum { value = boost::fusion::result_of::has_key<cont_type, Iface>::value }; static_assert(value, "impl_container doesn't contains implementation with this type"); return checker_helper<void, value>::template apply<Iface>(cont); } private: template<typename, bool> struct checker_helper; template<typename Fake> struct checker_helper<Fake, true> { template<typename T, typename Map> static const T& apply(const Map& map) { return boost::fusion::at_key<T>(map); } template<typename T, typename Map> static T& apply(Map& map) { return boost::fusion::at_key<T>(map); } }; template<typename Fake> struct checker_helper<Fake, false> { template<typename T, typename Map> static const T& apply(const Map&) {} template<typename T, typename Map> static T& apply(Map&) {} }; private: using cont_type = boost::fusion::map< boost::fusion::pair<Types, Types>... >; cont_type cont; private: using _1 = boost::mpl::placeholders::_1; using _2 = boost::mpl::placeholders::_2; using types = boost::mpl::vector<Types...>; static_assert( boost::mpl::size< typename boost::mpl::unique<types, boost::is_same<_1, _2>>::type >::value == sizeof...(Types) ,"only unique types allowed" ); }; /***************************************************************************/ struct type1 { int v; type1(int v) :v(v) {} int m() const { return v+v; } }; struct type2 { int v; type2(int v) :v(v) {} int m() const { return v+v+v; } }; struct type3 { int v; type3(int v) :v(v) {} int m() const { return v+v+v+v; } }; struct type4 { int v; type4(int v) :v(v) {} int m() const { return v+v+v+v+v; } }; /***************************************************************************/ int main() { //impl_container<type1, type1> cont(2); // static assertion: 'only unique types allowed' impl_container<type1, type2, type3> cont(2); std::cout << cont.get<type1>().m() << std::endl; // 4 std::cout << cont.get<type2>().m() << std::endl; // 6 std::cout << cont.get<type3>().m() << std::endl; // 8 //std::cout << cont.get<type4>().m() << std::endl; // static assertion: 'doesn't contains implementation with this type' } /***************************************************************************/ <|endoftext|>
<commit_before>8562790b-2d15-11e5-af21-0401358ea401<commit_msg>8562790c-2d15-11e5-af21-0401358ea401<commit_after>8562790c-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>1caf21a2-2e3a-11e5-9dfc-c03896053bdd<commit_msg>1cbe66a6-2e3a-11e5-a00e-c03896053bdd<commit_after>1cbe66a6-2e3a-11e5-a00e-c03896053bdd<|endoftext|>
<commit_before>404dd882-ad58-11e7-af0b-ac87a332f658<commit_msg>add file<commit_after>40b6b2cf-ad58-11e7-aa81-ac87a332f658<|endoftext|>
<commit_before>50006c64-5216-11e5-a875-6c40088e03e4<commit_msg>500710b0-5216-11e5-a378-6c40088e03e4<commit_after>500710b0-5216-11e5-a378-6c40088e03e4<|endoftext|>
<commit_before>93c42fd7-2d3d-11e5-9990-c82a142b6f9b<commit_msg>9438b52e-2d3d-11e5-8f91-c82a142b6f9b<commit_after>9438b52e-2d3d-11e5-8f91-c82a142b6f9b<|endoftext|>
<commit_before>/****************************************************************************** Copyright 2013 Allied Telesis Labs Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include <buildsys.h> #include <color.h> static bool quietly = false; void buildsys::log(const char *package, const char *fmt, ...) { char *message = NULL; va_list args; va_start(args, fmt); vasprintf(&message, fmt, args); va_end(args); fprintf(stderr, "%s: %s\n", package, message); free(message); } void buildsys::log(Package * P, const char *fmt, ...) { char *message = NULL; va_list args; va_start(args, fmt); vasprintf(&message, fmt, args); va_end(args); fprintf(quietly ? P->getLogFile() : stderr, "%s,%s: %s\n", P->getNS()->getName().c_str(), P->getName().c_str(), message); free(message); } static inline const char *get_color(const char *mesg) { if(strstr(mesg, "error:")) return COLOR_BOLD_RED; else if(strstr(mesg, "warning:")) return COLOR_BOLD_BLUE; return NULL; } void buildsys::program_output(Package * P, const char *mesg) { static int isATTY = isatty(fileno(stdout)); const char *color; if(!quietly && isATTY && ((color = get_color(mesg)) != NULL)) fprintf(stdout, "%s,%s: %s%s%s\n", P->getNS()->getName().c_str(), P->getName().c_str(), color, mesg, COLOR_RESET); else fprintf(quietly ? P->getLogFile() : stdout, "%s,%s: %s\n", P->getNS()->getName().c_str(), P->getName().c_str(), mesg); } int main(int argc, char *argv[]) { struct timespec start, end; clock_gettime(CLOCK_REALTIME, &start); log("BuildSys", "Buildsys (C++ version)"); log("BuildSys", "Built: %s %s", __TIME__, __DATE__); if(argc <= 1) { error("At least 1 parameter is required"); exit(-1); } World *WORLD = new World(argv[0]); hash_setup(); // process arguments ... // first we take a list of package names to exclusevily build // this will over-ride any dependency checks and force them to be built // without first building their dependencies int a = 2; bool foundDashDash = false; while(a < argc && !foundDashDash) { if(!strcmp(argv[a], "--clean")) { WORLD->setCleaning(); } else if(!strcmp(argv[a], "--no-output-prefix") || !strcmp(argv[a], "--nop")) { WORLD->clearOutputPrefix(); } else if(!strcmp(argv[a], "--cache-server") || !strcmp(argv[a], "--ff")) { WORLD->setFetchFrom(argv[a + 1]); a++; } else if(!strcmp(argv[a], "--tarball-cache")) { log("BuildSys", "Setting tarball cache to %s", argv[a + 1]); WORLD->setTarballCache(argv[a + 1]); a++; } else if(!strcmp(argv[a], "--overlay")) { WORLD->addOverlayPath(std::string(argv[a + 1])); a++; } else if(!strcmp(argv[a], "--extract-only")) { WORLD->setExtractOnly(); } else if(!strcmp(argv[a], "--build-info-ignore-fv")) { WORLD->ignoreFeature(std::string(argv[a + 1])); a++; } else if(!strcmp(argv[a], "--parse-only")) { WORLD->setParseOnly(); } else if(!strcmp(argv[a], "--keep-going")) { WORLD->setKeepGoing(); } else if(!strcmp(argv[a], "--quietly")) { quietly = true; } else if(!strcmp(argv[a], "--parallel-packages") || !strcmp(argv[a], "-j")) { WORLD->setThreadsLimit(atoi(argv[a + 1])); a++; } else if(!strcmp(argv[a], "--")) { foundDashDash = true; } else { WORLD->forceBuild(argv[a]); } a++; } // then we find a -- if(foundDashDash) { // then we can preload the feature set while(a < argc) { if(!WORLD->setFeature(argv[a])) { error("setFeature: Failed"); exit(-1); } a++; } } std::string target(""); int tn_len = strlen(argv[1]); if(argv[1][tn_len - 4] != '.') { target = string_format("%s.lua", argv[1]); } else { target = std::string(argv[1]); } if(WORLD->noIgnoredFeatures()) { // Implement old behaviour WORLD->ignoreFeature("job-limit"); WORLD->ignoreFeature("load-limit"); } if(!WORLD->basePackage(target)) { error("Building: Failed"); if(WORLD->areKeepGoing()) { delete WORLD; hash_shutdown(); } exit(-1); } if(WORLD->areParseOnly()) { // Print all the feature/values WORLD->printFeatureValues(); } // Write out the dependency graph WORLD->output_graph(); clock_gettime(CLOCK_REALTIME, &end); if(end.tv_nsec >= start.tv_nsec) log(argv[1], "Total time: %ds and %dms", (end.tv_sec - start.tv_sec), (end.tv_nsec - start.tv_nsec) / 1000000); else log(argv[1], "Total time: %ds and %dms", (end.tv_sec - start.tv_sec - 1), (1000 + end.tv_nsec / 1000000) - start.tv_nsec / 1000000); delete WORLD; hash_shutdown(); return 0; } <commit_msg>main: Use stack memory for WORLD, rather than heap<commit_after>/****************************************************************************** Copyright 2013 Allied Telesis Labs Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include <buildsys.h> #include <color.h> static bool quietly = false; void buildsys::log(const char *package, const char *fmt, ...) { char *message = NULL; va_list args; va_start(args, fmt); vasprintf(&message, fmt, args); va_end(args); fprintf(stderr, "%s: %s\n", package, message); free(message); } void buildsys::log(Package * P, const char *fmt, ...) { char *message = NULL; va_list args; va_start(args, fmt); vasprintf(&message, fmt, args); va_end(args); fprintf(quietly ? P->getLogFile() : stderr, "%s,%s: %s\n", P->getNS()->getName().c_str(), P->getName().c_str(), message); free(message); } static inline const char *get_color(const char *mesg) { if(strstr(mesg, "error:")) return COLOR_BOLD_RED; else if(strstr(mesg, "warning:")) return COLOR_BOLD_BLUE; return NULL; } void buildsys::program_output(Package * P, const char *mesg) { static int isATTY = isatty(fileno(stdout)); const char *color; if(!quietly && isATTY && ((color = get_color(mesg)) != NULL)) fprintf(stdout, "%s,%s: %s%s%s\n", P->getNS()->getName().c_str(), P->getName().c_str(), color, mesg, COLOR_RESET); else fprintf(quietly ? P->getLogFile() : stdout, "%s,%s: %s\n", P->getNS()->getName().c_str(), P->getName().c_str(), mesg); } int main(int argc, char *argv[]) { struct timespec start, end; clock_gettime(CLOCK_REALTIME, &start); log("BuildSys", "Buildsys (C++ version)"); log("BuildSys", "Built: %s %s", __TIME__, __DATE__); if(argc <= 1) { error("At least 1 parameter is required"); exit(-1); } World WORLD(argv[0]); hash_setup(); // process arguments ... // first we take a list of package names to exclusevily build // this will over-ride any dependency checks and force them to be built // without first building their dependencies int a = 2; bool foundDashDash = false; while(a < argc && !foundDashDash) { if(!strcmp(argv[a], "--clean")) { WORLD.setCleaning(); } else if(!strcmp(argv[a], "--no-output-prefix") || !strcmp(argv[a], "--nop")) { WORLD.clearOutputPrefix(); } else if(!strcmp(argv[a], "--cache-server") || !strcmp(argv[a], "--ff")) { WORLD.setFetchFrom(argv[a + 1]); a++; } else if(!strcmp(argv[a], "--tarball-cache")) { log("BuildSys", "Setting tarball cache to %s", argv[a + 1]); WORLD.setTarballCache(argv[a + 1]); a++; } else if(!strcmp(argv[a], "--overlay")) { WORLD.addOverlayPath(std::string(argv[a + 1])); a++; } else if(!strcmp(argv[a], "--extract-only")) { WORLD.setExtractOnly(); } else if(!strcmp(argv[a], "--build-info-ignore-fv")) { WORLD.ignoreFeature(std::string(argv[a + 1])); a++; } else if(!strcmp(argv[a], "--parse-only")) { WORLD.setParseOnly(); } else if(!strcmp(argv[a], "--keep-going")) { WORLD.setKeepGoing(); } else if(!strcmp(argv[a], "--quietly")) { quietly = true; } else if(!strcmp(argv[a], "--parallel-packages") || !strcmp(argv[a], "-j")) { WORLD.setThreadsLimit(atoi(argv[a + 1])); a++; } else if(!strcmp(argv[a], "--")) { foundDashDash = true; } else { WORLD.forceBuild(argv[a]); } a++; } // then we find a -- if(foundDashDash) { // then we can preload the feature set while(a < argc) { if(!WORLD.setFeature(argv[a])) { error("setFeature: Failed"); exit(-1); } a++; } } std::string target(""); int tn_len = strlen(argv[1]); if(argv[1][tn_len - 4] != '.') { target = string_format("%s.lua", argv[1]); } else { target = std::string(argv[1]); } if(WORLD.noIgnoredFeatures()) { // Implement old behaviour WORLD.ignoreFeature("job-limit"); WORLD.ignoreFeature("load-limit"); } if(!WORLD.basePackage(target)) { error("Building: Failed"); if(WORLD.areKeepGoing()) { hash_shutdown(); } exit(-1); } if(WORLD.areParseOnly()) { // Print all the feature/values WORLD.printFeatureValues(); } // Write out the dependency graph WORLD.output_graph(); clock_gettime(CLOCK_REALTIME, &end); if(end.tv_nsec >= start.tv_nsec) log(argv[1], "Total time: %ds and %dms", (end.tv_sec - start.tv_sec), (end.tv_nsec - start.tv_nsec) / 1000000); else log(argv[1], "Total time: %ds and %dms", (end.tv_sec - start.tv_sec - 1), (1000 + end.tv_nsec / 1000000) - start.tv_nsec / 1000000); hash_shutdown(); return 0; } <|endoftext|>
<commit_before>8431fca1-2d15-11e5-af21-0401358ea401<commit_msg>8431fca2-2d15-11e5-af21-0401358ea401<commit_after>8431fca2-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>83000e14-2d15-11e5-af21-0401358ea401<commit_msg>83000e15-2d15-11e5-af21-0401358ea401<commit_after>83000e15-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>59b59d94-2d3f-11e5-bb7e-c82a142b6f9b<commit_msg>5a4cdba1-2d3f-11e5-a095-c82a142b6f9b<commit_after>5a4cdba1-2d3f-11e5-a095-c82a142b6f9b<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <sstream> #include <tuple> using namespace std; class ChildStuntedness5 { // 普通の int testType; int scenario; vector<string> training; vector<string> testing; // 自分の vector< vector<string> > test_case_st; // main theorems public: vector<double> predict(int _testType, int _scenario, vector<string> _training, vector<string> _testing) { testType = _testType; scenario = _scenario; training = _training; testing = _testing; make_training(); vector<double> X; return X; } // lemmas private: vector<string> split(string S) { // コンマでsprit vector<string> ans; stringstream ss; string s; while(getline(ss, s, ',')) { ans.push_back(s); } return ans; } void make_test_case_st() { int N = testing.size(); for (auto i=0; i<N; i++) { vector<string> sps = split(testing[i]); test_case_st.push_back(sps); } } void make_training() { } }; <commit_msg>残差2乗和まで<commit_after>#include <iostream> #include <vector> #include <sstream> #include <tuple> #include <algorithm> using namespace std; class ChildStuntedness5 { private: // 普通の int testType; int scenario; vector<string> training; vector<string> testing; // 定数 const double NA = -1000; const int IQ_col = 26; const vector< vector<int> > used_col = { {11, 13, 14, 15, 16, 17}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {10, 12, 18, 19, 20, 21, 22, 23, 24, 25} }; // 自分の vector< vector<string> > test_case_st; vector< vector<double> > test_case; double A[100]; // 係数部分 double B[100]; // 定数部分 IQ = Ax + B double zansa[100]; // lemmas vector<string> split(string S) { // コンマでsprit vector<string> ans; stringstream ss(S); string s; while(getline(ss, s, ',')) { ans.push_back(s); } return ans; } void make_test_case_st() { // testingをsplit int N = testing.size(); for (auto i=0; i<N; i++) { vector<string> sps = split(testing[i]); test_case_st.push_back(sps); } } void convert_double() { // doubleにする test_case = vector< vector<double> >(test_case_st.size(), vector<double>()); for (auto i=0; i<test_case_st.size(); i++) { for (auto j=0; j<test_case_st[i].size(); j++) { if (test_case_st[i][j] == "NA") { test_case[i][j] = NA; } else { test_case[i][j] = stof(test_case_st[i][j]); } } } } void fill_iq() { // iq埋める int iq = NA; unsigned int ind = 0; while (ind < test_case.size()) { if (test_case[ind][IQ_col] == NA) { unsigned int atari = ind+1; while (test_case[atari][ind] == NA) atari++; iq = test_case[atari][ind]; for (auto i=ind; i<atari; i++) { test_case[i][IQ_col] = iq; } ind = atari; } ind++; } } bool issameline(int row, int col, vector< vector<double> >::iterator it) { return (row > 1 && it[row-1][0] == it[row][0] && it[row-1][col] == it[row][col]); } void calc_AB(int col) { // ABする int n = 0; int sumx = 0; int sumy = 0; int sumxy = 0; int sumx2 = 0; for (auto i=0; i<test_case.size(); i++) { if (issameline(i, col, test_case.begin())) { continue; } n++; double x = test_case[i][col]; double y = test_case[i][IQ_col]; sumx += x; sumy += y; sumxy += x * y; sumx2 += x * x; } A[col] = (n * sumxy - sumx * sumy) / (n * sumx2 - sumx * sumx); B[col] = (sumx2 * sumy - sumxy * sumx) / (n * sumx2 - sumx * sumx); } void zansa_2jouwa(int col) { zansa[col] = 0; int n = 0; for (auto i=0; i<test_case.size(); i++) { if (issameline(i, col, test_case.begin())) { continue; } n++; double x = test_case[i][col]; double y = test_case[i][IQ_col]; double sa = y - A[col] * x - B[col]; zansa[col] += sa * sa; } zansa[col] /= n; cerr << col << ": " << zansa[col] << endl; } void calc_all() { for (auto i=0; i<=scenario; i++) { for (auto j=0; j<used_col[i].size(); j++) { calc_AB(used_col[i][j]); zansa_2jouwa(used_col[i][j]); } } } void ranking() { } void make_training() { make_test_case_st(); convert_double(); fill_iq(); calc_all(); ranking(); } // main theorems public: vector<double> predict(int _testType, int _scenario, vector<string> _training, vector<string> _testing) { testType = _testType; scenario = _scenario; training = _training; testing = _testing; make_training(); vector<double> X; return X; } }; <|endoftext|>
<commit_before>a53ca480-2e4f-11e5-9d22-28cfe91dbc4b<commit_msg>a544d9a8-2e4f-11e5-97c6-28cfe91dbc4b<commit_after>a544d9a8-2e4f-11e5-97c6-28cfe91dbc4b<|endoftext|>
<commit_before><commit_msg>whoops. need to undef it too.<commit_after><|endoftext|>
<commit_before>1c2a7040-2e3a-11e5-ba85-c03896053bdd<commit_msg>1c38f1d8-2e3a-11e5-b3cf-c03896053bdd<commit_after>1c38f1d8-2e3a-11e5-b3cf-c03896053bdd<|endoftext|>
<commit_before>1c3ae3fd-ad58-11e7-948e-ac87a332f658<commit_msg>fixed bug<commit_after>1c9850a1-ad58-11e7-8e2d-ac87a332f658<|endoftext|>
<commit_before>0e765612-585b-11e5-a67f-6c40088e03e4<commit_msg>0e8130dc-585b-11e5-9381-6c40088e03e4<commit_after>0e8130dc-585b-11e5-9381-6c40088e03e4<|endoftext|>
<commit_before>dc699fc0-327f-11e5-9255-9cf387a8033e<commit_msg>dc6fd494-327f-11e5-afa1-9cf387a8033e<commit_after>dc6fd494-327f-11e5-afa1-9cf387a8033e<|endoftext|>
<commit_before>8d6dfd3c-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd3d-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd3d-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>da53d3be-585a-11e5-8424-6c40088e03e4<commit_msg>da5a8568-585a-11e5-bdb0-6c40088e03e4<commit_after>da5a8568-585a-11e5-bdb0-6c40088e03e4<|endoftext|>
<commit_before>8c3d2105-2d14-11e5-af21-0401358ea401<commit_msg>8c3d2106-2d14-11e5-af21-0401358ea401<commit_after>8c3d2106-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>/* * main.cpp * * Created on: Sep 21, 2013 * Author: tomas */ #include <stdlib.h> #include <stdio.h> #include <GL/glut.h> #include <iostream> // TODO unused? #include <math.h> /* fabs */ using namespace std; #define GRID_SIZE 32 int windowSizeH = 600; int windowSizeV = 600; bool shouldDrawUserLine = false; bool shouldDrawBresenhamLine = false; bool snapToGrid = true; float beginX = 0; float beginY = 0; float endX = 0; float endY = 0; // TODO better titles int gridBeginX = 0; int gridBeginY = 0; int gridEndX = 0; int gridEndY = 0; void transformScreenToWorldCoordinates(int screenX, int screenY, float &worldX, float &worldY) { worldX = ((float)screenX / (float)windowSizeH) * 2 - 1; worldY = ((float)screenY / (float)windowSizeV) * -2 + 1; } void transformWorldToGridCoordinates(float worldX, float worldY, int &gridX, int &gridY){ gridX = (int)( ( ( worldX+1)/2 ) * GRID_SIZE ); gridY = (int)( ( (-worldY+1)/2 ) * GRID_SIZE ); } void transformGridToWorldCoordinates(int gridX, int gridY, float &worldX, float &worldY){ float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize worldX = ( ( (float)gridX / GRID_SIZE) * 2 ) - 1 + (cornerLength/2); worldY = ( ( (float)gridY / GRID_SIZE) * -2 ) + 1 - (cornerLength/2); } void colorGridCell(int x, int y) { float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize float topLeftX = (cornerLength * x) - 1; float topLeftY = ((cornerLength * y) - 1) * -1; glColor3f(0, 0.5, 0.5); glBegin(GL_QUADS); glVertex2f(topLeftX, topLeftY); glVertex2f(topLeftX + cornerLength, topLeftY); glVertex2f(topLeftX + cornerLength, topLeftY - cornerLength); glVertex2f(topLeftX, topLeftY - cornerLength); glEnd(); } void drawBresenhamLine(int gridBeginX, int gridBeginY, int gridEndX, int gridEndY){ bool steep = abs(gridEndY - gridBeginY) > abs(gridEndX - gridBeginX); if (steep){ swap(gridBeginX, gridBeginY); swap(gridEndX, gridEndY); } if (gridBeginX > gridEndX){ swap(gridBeginX, gridEndX); swap(gridBeginY, gridEndY); } int deltaX = gridEndX - gridBeginX; int deltay = abs (gridEndY - gridBeginY); int error = deltaX / 2; int currentY = gridBeginY; int yStep = 1; if (gridBeginY >= gridEndY){ yStep = -1; } for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) { if (steep) { colorGridCell(currentY, currentX); } else { colorGridCell(currentX, currentY); } error = error - deltay; if (error < 0) { currentY = currentY + yStep; error = error + deltaX; } } } void mouseClickCallback (int button, int state, int x, int y){ if (button == GLUT_LEFT_BUTTON){ if ((state == GLUT_DOWN)){ transformScreenToWorldCoordinates(x, y, beginX, beginY); endX = beginX; endY = beginY; shouldDrawUserLine = true; transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY); gridEndX = gridBeginX; gridEndY = gridBeginY; shouldDrawBresenhamLine = true; } // else if (state == GLUT_UP) { // transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY); // transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY); // // } glutPostRedisplay(); } } void mouseDragCallback(int x, int y){ transformScreenToWorldCoordinates(x, y, endX, endY); transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY); glutPostRedisplay(); } void drawUserLine(){ float lineBeginX = 0; float lineBeginY = 0; float lineEndX = 0; float lineEndY = 0; if (snapToGrid) { transformGridToWorldCoordinates(gridBeginX, gridBeginY, lineBeginX, lineBeginY); transformGridToWorldCoordinates(gridEndX, gridEndY, lineEndX, lineEndY); } else { lineBeginX = beginX; lineBeginY = beginY; lineEndX = endX; lineEndY = endY; } glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); glVertex2f(lineBeginX, lineBeginY); glVertex2f(lineEndX, lineEndY); glEnd(); } void drawGrid(){ glColor3f(0.5, 0.5, 0.5); int i; glBegin(GL_LINES); for (i = -(GRID_SIZE / 2); i <= (GRID_SIZE / 2); i++) { //TODO optimize float x = i / (float) (GRID_SIZE / 2); glVertex2f(x, -1.0); glVertex2f(x, 1.0); glVertex2f(-1.0, x); glVertex2f(1.0, x); } glEnd(); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); drawGrid(); if (shouldDrawBresenhamLine){ drawBresenhamLine(gridBeginX, gridBeginY, gridEndX, gridEndY); } if (shouldDrawUserLine) { drawUserLine(); } glFlush(); } void init(void) { } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowSize(windowSizeH, windowSizeV); glutInitWindowPosition(100, 50); glutCreateWindow("CG1"); init(); glutDisplayFunc(display); glutMouseFunc(mouseClickCallback); glutMotionFunc(mouseDragCallback); glutMainLoop(); return 0; } <commit_msg>Added line drawing algorithm execution time test<commit_after>/* * main.cpp * * Created on: Sep 21, 2013 * Author: tomas */ #include <stdlib.h> #include <stdio.h> #include <GL/glut.h> #include <iostream> // TODO unused? #include <math.h> /* fabs */ #include <sys/time.h> #include <unistd.h> using namespace std; #define GRID_SIZE 32 #define RAND_SEED 1 int windowSizeH = 600; int windowSizeV = 600; bool shouldDrawUserLine = false; bool shouldDrawBresenhamLine = false; bool snapToGrid = true; float beginX = 0; float beginY = 0; float endX = 0; float endY = 0; // TODO better titles int gridBeginX = 0; int gridBeginY = 0; int gridEndX = 0; int gridEndY = 0; void transformScreenToWorldCoordinates(int screenX, int screenY, float &worldX, float &worldY) { worldX = ((float)screenX / (float)windowSizeH) * 2 - 1; worldY = ((float)screenY / (float)windowSizeV) * -2 + 1; } void transformWorldToGridCoordinates(float worldX, float worldY, int &gridX, int &gridY){ gridX = (int)( ( ( worldX+1)/2 ) * GRID_SIZE ); gridY = (int)( ( (-worldY+1)/2 ) * GRID_SIZE ); } void transformGridToWorldCoordinates(int gridX, int gridY, float &worldX, float &worldY){ float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize worldX = ( ( (float)gridX / GRID_SIZE) * 2 ) - 1 + (cornerLength/2); worldY = ( ( (float)gridY / GRID_SIZE) * -2 ) + 1 - (cornerLength/2); } void colorGridCell(int x, int y) { float cornerLength = (float)(1.0/(GRID_SIZE/2)); // TODO optimize float topLeftX = (cornerLength * x) - 1; float topLeftY = ((cornerLength * y) - 1) * -1; glColor3f(0, 0.5, 0.5); glBegin(GL_QUADS); glVertex2f(topLeftX, topLeftY); glVertex2f(topLeftX + cornerLength, topLeftY); glVertex2f(topLeftX + cornerLength, topLeftY - cornerLength); glVertex2f(topLeftX, topLeftY - cornerLength); glEnd(); } void drawBresenhamLine(int gridBeginX, int gridBeginY, int gridEndX, int gridEndY, bool useInts, bool draw) { bool steep = abs(gridEndY - gridBeginY) > abs(gridEndX - gridBeginX); if (steep) { swap(gridBeginX, gridBeginY); swap(gridEndX, gridEndY); } if (gridBeginX > gridEndX) { swap(gridBeginX, gridEndX); swap(gridBeginY, gridEndY); } if (useInts) { int deltaX = gridEndX - gridBeginX; int deltay = abs(gridEndY - gridBeginY); int error = deltaX / 2; int currentY = gridBeginY; int yStep = 1; if (gridBeginY >= gridEndY) { yStep = -1; } for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) { if (draw) { if (steep) { colorGridCell(currentY, currentX); } else { colorGridCell(currentX, currentY); } } error = error - deltay; if (error < 0) { currentY = currentY + yStep; error = error + deltaX; } } } else { int deltaX = gridEndX - gridBeginX; int deltay = abs(gridEndY - gridBeginY); float error = 0; float deltaError = fabs((float) deltay / (float) deltaX); int currentY = gridBeginY; int yStep = 1; if (gridBeginY >= gridEndY) { yStep = -1; } for (int currentX = gridBeginX; currentX <= gridEndX; currentX++) { if (draw){ if (steep) { colorGridCell(currentY, currentX); } else { colorGridCell(currentX, currentY); } } error = error + deltaError; if (error >= 0.5) { currentY = currentY + yStep; error = error - 1.0; } } } } void mouseClickCallback (int button, int state, int x, int y){ if (button == GLUT_LEFT_BUTTON){ if ((state == GLUT_DOWN)){ transformScreenToWorldCoordinates(x, y, beginX, beginY); endX = beginX; endY = beginY; shouldDrawUserLine = true; transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY); gridEndX = gridBeginX; gridEndY = gridBeginY; shouldDrawBresenhamLine = true; } // else if (state == GLUT_UP) { // transformWorldToGridCoordinates(beginX, beginY, gridBeginX, gridBeginY); // transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY); // // } glutPostRedisplay(); } } void mouseDragCallback(int x, int y){ transformScreenToWorldCoordinates(x, y, endX, endY); transformWorldToGridCoordinates(endX, endY, gridEndX, gridEndY); glutPostRedisplay(); } void drawUserLine(){ float lineBeginX = 0; float lineBeginY = 0; float lineEndX = 0; float lineEndY = 0; if (snapToGrid) { transformGridToWorldCoordinates(gridBeginX, gridBeginY, lineBeginX, lineBeginY); transformGridToWorldCoordinates(gridEndX, gridEndY, lineEndX, lineEndY); } else { lineBeginX = beginX; lineBeginY = beginY; lineEndX = endX; lineEndY = endY; } glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); glVertex2f(lineBeginX, lineBeginY); glVertex2f(lineEndX, lineEndY); glEnd(); } void drawGrid(){ glColor3f(0.5, 0.5, 0.5); int i; glBegin(GL_LINES); for (i = -(GRID_SIZE / 2); i <= (GRID_SIZE / 2); i++) { //TODO optimize float x = i / (float) (GRID_SIZE / 2); glVertex2f(x, -1.0); glVertex2f(x, 1.0); glVertex2f(-1.0, x); glVertex2f(1.0, x); } glEnd(); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); drawGrid(); if (shouldDrawBresenhamLine){ drawBresenhamLine(gridBeginX, gridBeginY, gridEndX, gridEndY, false, true); } if (shouldDrawUserLine) { drawUserLine(); } glFlush(); } int getRandomIntInRange(int min, int max) { return min + (rand() % (int)(max - min + 1)); // TODO review algorithm // TODO make random seed always the same } long getLineDrawingExecutionSpeedMicroseconds(bool useInts, long lineDraws){ int min = 0; int max = GRID_SIZE - 1; int randBeginX; int randBeginY; int randEndX; int randEndY; srand(RAND_SEED); struct timeval start, end; gettimeofday(&start, NULL); for (long i = 0; i < lineDraws; i++) { randBeginX = getRandomIntInRange(min, max); randBeginY = getRandomIntInRange(min, max); randEndX = getRandomIntInRange(min, max); randEndY = getRandomIntInRange(min, max); drawBresenhamLine(randBeginX, randBeginY, randEndX, randEndY, useInts, false); // cout << randBeginX << " " << randBeginX << " to " << randEndX << " " << randEndY << endl; } gettimeofday(&end, NULL); return end.tv_usec - start.tv_usec; } void testBresenhamLineAlgorithmExecutionSpeed(long numberOfCalls){ long execTimeUsingInt = getLineDrawingExecutionSpeedMicroseconds(true, numberOfCalls); long execTimeUsingFloat = getLineDrawingExecutionSpeedMicroseconds(false, numberOfCalls); cout << execTimeUsingInt << " " << execTimeUsingFloat << endl; } void init(void) { } int main(int argc, char *argv[]) { // testBresenhamLineAlgorithmExecutionSpeed(10000); // return 0; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowSize(windowSizeH, windowSizeV); glutInitWindowPosition(100, 50); glutCreateWindow("CG1"); init(); glutDisplayFunc(display); glutMouseFunc(mouseClickCallback); glutMotionFunc(mouseDragCallback); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>412124a3-2e4f-11e5-877d-28cfe91dbc4b<commit_msg>4127ecc7-2e4f-11e5-93d4-28cfe91dbc4b<commit_after>4127ecc7-2e4f-11e5-93d4-28cfe91dbc4b<|endoftext|>
<commit_before>e00e8e5c-ad58-11e7-9520-ac87a332f658<commit_msg>Does anyone even read these anymore???<commit_after>e081d7c2-ad58-11e7-9ac3-ac87a332f658<|endoftext|>
<commit_before>5e58940e-2d16-11e5-af21-0401358ea401<commit_msg>5e58940f-2d16-11e5-af21-0401358ea401<commit_after>5e58940f-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>1151180a-2e4f-11e5-b5ec-28cfe91dbc4b<commit_msg>115991b8-2e4f-11e5-a4ac-28cfe91dbc4b<commit_after>115991b8-2e4f-11e5-a4ac-28cfe91dbc4b<|endoftext|>
<commit_before>d7ff24ab-313a-11e5-8993-3c15c2e10482<commit_msg>d8050d99-313a-11e5-9a9f-3c15c2e10482<commit_after>d8050d99-313a-11e5-9a9f-3c15c2e10482<|endoftext|>
<commit_before>7892f286-2d53-11e5-baeb-247703a38240<commit_msg>78937134-2d53-11e5-baeb-247703a38240<commit_after>78937134-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>64b85462-5216-11e5-ab59-6c40088e03e4<commit_msg>64bf0262-5216-11e5-99a6-6c40088e03e4<commit_after>64bf0262-5216-11e5-99a6-6c40088e03e4<|endoftext|>
<commit_before>87928214-4b02-11e5-af5f-28cfe9171a43<commit_msg>I finished programming, there is nothing left to program<commit_after>879f3df5-4b02-11e5-a3d9-28cfe9171a43<|endoftext|>
<commit_before>bdebc814-2d3d-11e5-827b-c82a142b6f9b<commit_msg>be36b7ca-2d3d-11e5-ab42-c82a142b6f9b<commit_after>be36b7ca-2d3d-11e5-ab42-c82a142b6f9b<|endoftext|>
<commit_before>#include <sstream> #include <fstream> #include <stdio.h> #include <iostream> #include <string> using namespace std; int similarity_score(char a, char b) { int score; if ((a == b) || (a == '?' || b == '?')) { score = 2; } else { score = -1; } return score; } int max_score(int scores[]) { int score = 0; for (int i = 0; i < 3; i++) { if (scores[i] > score) { score = scores[i]; } } return score; } string slurp(const string &filename) { ifstream in(filename, ifstream::in); stringstream sstr; sstr << in.rdbuf(); string file = sstr.str(); return file; } int main(int argc, char *argv[]) { int c; bool showtime = false; string file1 = argv[1]; string file2 = argv[2]; if (argc > 1) { for (c = 1; c < argc; c++) { if (strcmp(argv[c], "-t") == 0) { showtime = true; } } } if (argc < 3) { cout << "Usage: sequence-alignment filename_sequence_a filename_sequence_b " "[-t]"; return 0; } cout << "Starting alignment with files: " << file1 << ", " << file2 << endl; clock_t begin_read = clock(); string seq_a = slurp(file1); string seq_b = slurp(file2); clock_t end_read = clock(); double elapsed_secs_read = double(end_read - begin_read) / CLOCKS_PER_SEC; // create the matrices size_t length_m = seq_a.size(); size_t length_n = seq_b.size(); cout << "length m " << length_m << endl; cout << "length n " << length_n << endl; int H_matrix[length_m + 1][length_n + 1]; // set first row and first column to zero for (int i = 0; i < length_m + 1; i++) { H_matrix[0][i] = 0; } for (int j = 0; j < length_n + 1; j++) { H_matrix[j][0] = 0; } int max_options[3]; for (int i = 1; i < length_m + 1; i++) { for (int j = 1; j < length_n + 1; j++) { max_options[0] = H_matrix[i - 1][j - 1] + similarity_score(seq_a.at(i - 1), seq_b.at(j - 1)); max_options[1] = H_matrix[i - 1][j] - 2; max_options[2] = H_matrix[i][j - 1] - 2; H_matrix[i][j] = max_score(max_options); } } for (int i = 0; i < length_m + 1; i++) { for (int j = 0; j < length_n + 1; j++) { cout << H_matrix[i][j] << ' '; } cout << endl; } return 0; } <commit_msg>non threaded version<commit_after>#include <sstream> #include <fstream> #include <stdio.h> #include <iostream> #include <string> #include <pthread.h> using namespace std; #define MATCH 1 #define GAP_PENALTY 2 #define MISMATCH_PENALTY 1 int similarity_score(char a, char b) { int score; if ((a == b) || (a == '?' || b == '?')) { score = MATCH; } else { score = -MISMATCH_PENALTY; } return score; } int max_score(int scores[]) { int score = 0; for (int i = 0; i < 3; i++) { if (scores[i] > score) { score = scores[i]; } } return score; } string slurp(const string &filename) { ifstream in(filename, ifstream::in); stringstream sstr; sstr << in.rdbuf(); string file = sstr.str(); return file; } int main(int argc, char *argv[]) { int c; bool showtime = false; string file1 = argv[1]; string file2 = argv[2]; if (argc > 1) { for (c = 1; c < argc; c++) { if (strcmp(argv[c], "-t") == 0) { showtime = true; } } } if (argc < 3) { cout << "Usage: sequence-alignment filename_sequence_a filename_sequence_b " "[-t]"; return 0; } cout << "Starting alignment with files: " << file1 << ", " << file2 << endl; clock_t begin_read = clock(); string seq_a = slurp(file1); string seq_b = slurp(file2); clock_t end_read = clock(); double elapsed_secs_read = double(end_read - begin_read) / CLOCKS_PER_SEC; // create the matrices size_t length_m = seq_a.size(); size_t length_n = seq_b.size(); // cout << "length m " << length_m << endl; // cout << "length n " << length_n << endl; int H_matrix[length_m][length_n]; // set first row and first column to zero for (int i = 0; i < length_m; i++) { H_matrix[0][i] = 0; } for (int j = 0; j < length_n; j++) { H_matrix[j][0] = 0; } int max_options[3]; clock_t begin_matrix_calc = clock(); for (int i = 1; i < length_m; i++) { for (int j = 1; j < length_n; j++) { max_options[0] = H_matrix[i - 1][j - 1] + similarity_score(seq_a.at(i - 1), seq_b.at(j - 1)); max_options[1] = H_matrix[i - 1][j] - GAP_PENALTY; max_options[2] = H_matrix[i][j - 1] - GAP_PENALTY; H_matrix[i][j] = max_score(max_options); } } clock_t end_matrix_calc = clock(); double elapsed_secs_matrix_calc = double(end_matrix_calc - begin_matrix_calc) / CLOCKS_PER_SEC; for (int i = 0; i < length_m; i++) { for (int j = 0; j < length_n; j++) { cout << H_matrix[i][j] << ' '; } cout << endl; } cout << "Elapsed Calculation Time: " << elapsed_secs_matrix_calc << endl; return 0; } <|endoftext|>
<commit_before>90e194ba-2e4f-11e5-9d68-28cfe91dbc4b<commit_msg>90eab0f5-2e4f-11e5-ba9b-28cfe91dbc4b<commit_after>90eab0f5-2e4f-11e5-ba9b-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <sstream> #include <cstdlib> #include <vector> #include <fstream> #include <ctime> #include "Map.h" #include "Zombie.h" #include "Player.h" #include "Plant.h" using namespace std; bool allZombiesDie(const Zombie * zombie); bool enoughMoney(const vector<Plant*> & plant, const Player * player); void printInfor(const Map & map, const Player & player, const Zombie * zombie); int main() { //game start cout << " -----------------------------" << endl << "| Plants v.s Zombies |" << endl << " -----------------------------" << endl; constexpr int LAND_DEFAULT=8; constexpr int LAND_MAX=10; constexpr int LAND_MIN=1; constexpr int ZOMBIE_DEFAULT=3; constexpr int ZOMBIE_MAX=10; constexpr int ZOMBIE_MIN=1; string input; //initialize game setting cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>"; int value = LAND_DEFAULT; getline(cin, input); if(!input.empty()) { istringstream stream( input ); stream >> value; if(value > LAND_MAX) value = LAND_MAX; if(value < LAND_MIN) value = LAND_MIN; } const int LANDS=value; cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>"; value=ZOMBIE_DEFAULT; getline(cin, input); if(!input.empty()) { istringstream stream( input ); stream >> value; if(value > ZOMBIE_MAX) value = ZOMBIE_MAX; if(value < ZOMBIE_MIN) value = ZOMBIE_MIN; } const int ZOMBIES=value; //game rules cout << "=============================================================================" << endl << "Plants vs. Zombies Rule:" << endl << endl << "How to win:" << endl << " (1) All zombies are dead." << endl << " (2) At least one plant is live." << endl << " (3) The number of dead bomb plants cannot exceed the number of zombies." << endl << endl << "How to lose:" << endl << " All plants are dead." << endl << "=============================================================================" << endl; system("pause"); system("cls"); //construct srand(time(0)); // random number seed Player *player = new Player; Zombie *zombie = new Zombie[ZOMBIES]; Zombie::TotalNum = ZOMBIES; Map *map = new Map(LANDS); vector<Plant*> plant; fstream fin("plants.txt", fstream::in); string str; if(fin) { while(fin >> str) { Plant *tmp = nullptr; switch(str[0]) { case 'C': { tmp = new CoinPlant(fin); break; } case 'S': { tmp = new HornPlant(fin); break; } case 'B': { tmp = new BombPlant(fin); break; } case 'H': { tmp = new HealPlant(fin); break; } default: continue; } if(tmp) { plant.push_back(tmp); } } } player->Move(rand()%LANDS); for (int i=0; i<ZOMBIES; ++i) zombie[i].Move(rand()%LANDS); int choice = plant.size(); while(true) { int position; printInfor(*map, *player, zombie); do { position = player->Pos(); Land * land = map->GetLand(position); if(!land->IsEmpty()) { Plant *p = land->GetPlant(); int visit = p->Visit(*player); if(visit < 0) { map->Healing(p->HpBack()); cout << "All your plants have recovered "<< p->HpBack() << " HP!" << endl; break; } else if (visit) { cout << "You have earned $" << visit << "! Now you have $" << player->Money(); break; } else break; } else { if (!enoughMoney(plant, player)) { cout << "You don't have enough money to plant anything" << endl; break; } else { for(size_t i=0; i<plant.size(); ++i) { cout << "[" << i << "] " ; plant[i]->Print(); cout << endl; } cout << endl << "Player $" << player->Money() ; cout << ":\tEnter your choice (" << plant.size() << " to give up, default: " << choice << ")...>"; getline(cin, input); if(!input.empty()) { istringstream stream( input ); stream >> choice; if(choice > plant.size() || choice < 0) choice = plant.size(); } if(choice != plant.size()) { map->GetLand(player->Pos())->Planting(*player, *plant[choice]); cout << "You have planted " << plant[choice]->Name() << " at land " << player->Pos() << " !" << endl; } break; } if(choice != plant.size() && plant[choice]->Price() > player->Money()) { cout << "Not enough money! Please input again!" << endl; system("pause"); } } } while (true); system("pause"); system("cls"); for (int i=0; i<ZOMBIES; ++i) { if (zombie[i].isAlive()) { printInfor(*map, *player, zombie); position = rand()%LANDS; zombie[i].Move(position); cout << "Zombie [" << i << "] moves to land " << position << "." << endl; Land * land = map->GetLand(position); if(!land->IsEmpty()) { Plant *p = land->GetPlant(); p->Visit(zombie[i]); if(p->Attack()) { cout << p->Name() << " gives " << p->Attack() << " damage to the zombie!" << endl; } cout << "Zombie eats plant " << p->Name() << " and cause damage " << zombie[i].Attack() << endl; if(!zombie[i].isAlive()) cout << "Zombie is killed!" << endl; if(!p->isAlive()) { land->Dead(); cout << "Plant " << p->Name() << " is dead!" << endl; } } system("pause"); system("cls"); } } position = rand()%LANDS; player->Move(position); // end game condition if (map->IsNonPlant()) { cout << "Oh no... You have no plant on the map ...." << endl; } else if (BombPlant::deadNum >= ZOMBIES/2) { cout << "You lose the game since you cannot use that many bomb plants!" << endl; } else if (allZombiesDie(zombie)) { cout << "Congratulations! You have killed all zombies!" << endl; } system("cls"); //break; } // destruct while(!plant.empty()) { delete plant.back(); plant.pop_back(); } delete player; delete map; delete [] zombie; return 0; } bool allZombiesDie(const Zombie * zombie) { for(int i=0; i<Zombie::TotalNum && !zombie[i].isAlive(); ++i) return (i==Zombie::TotalNum-1); } bool enoughMoney(const vector<Plant*> & plant, const Player * player) { for (Plant* p : plant) if (p->Price() <= player->Money()) return true; return false; } void printInfor(const Map & map, const Player & player, const Zombie * zombie) { map.Display(player, zombie); cout << "------------------------------------------------" << endl; cout << "Zombie information:" << endl; for(int i=0; i<Zombie::TotalNum; ++i) { if(zombie[i].isAlive()) cout << '[' << i << "] " << zombie[i]; } cout << "================================================" << endl; } <commit_msg>add endGame function<commit_after>#include <iostream> #include <string> #include <sstream> #include <cstdlib> #include <vector> #include <fstream> #include <ctime> #include "Map.h" #include "Zombie.h" #include "Player.h" #include "Plant.h" using namespace std; bool endGame(const Map & map, const Zombie * zombie); bool allZombiesDie(const Zombie * zombie); bool enoughMoney(const vector<Plant*> & plant, const Player * player); void printInfor(const Map & map, const Player & player, const Zombie * zombie); int main() { //game start cout << " -----------------------------" << endl << "| Plants v.s Zombies |" << endl << " -----------------------------" << endl; constexpr int LAND_DEFAULT=8; constexpr int LAND_MAX=10; constexpr int LAND_MIN=1; constexpr int ZOMBIE_DEFAULT=3; constexpr int ZOMBIE_MAX=10; constexpr int ZOMBIE_MIN=1; string input; //initialize game setting cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>"; int value = LAND_DEFAULT; getline(cin, input); if(!input.empty()) { istringstream stream( input ); stream >> value; if(value > LAND_MAX) value = LAND_MAX; if(value < LAND_MIN) value = LAND_MIN; } const int LANDS=value; cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>"; value=ZOMBIE_DEFAULT; getline(cin, input); if(!input.empty()) { istringstream stream( input ); stream >> value; if(value > ZOMBIE_MAX) value = ZOMBIE_MAX; if(value < ZOMBIE_MIN) value = ZOMBIE_MIN; } const int ZOMBIES=value; //game rules cout << "=============================================================================" << endl << "Plants vs. Zombies Rule:" << endl << endl << "How to win:" << endl << " (1) All zombies are dead." << endl << " (2) At least one plant is live." << endl << " (3) The number of dead bomb plants cannot exceed the number of zombies." << endl << endl << "How to lose:" << endl << " All plants are dead." << endl << "=============================================================================" << endl; system("pause"); system("cls"); //construct srand(time(0)); // random number seed Player *player = new Player; Zombie *zombie = new Zombie[ZOMBIES]; Zombie::TotalNum = ZOMBIES; Map *map = new Map(LANDS); vector<Plant*> plant; fstream fin("plants.txt", fstream::in); string str; if(fin) { while(fin >> str) { Plant *tmp = nullptr; switch(str[0]) { case 'C': { tmp = new CoinPlant(fin); break; } case 'S': { tmp = new HornPlant(fin); break; } case 'B': { tmp = new BombPlant(fin); break; } case 'H': { tmp = new HealPlant(fin); break; } default: continue; } if(tmp) { plant.push_back(tmp); } } } player->Move(rand()%LANDS); for (int i=0; i<ZOMBIES; ++i) zombie[i].Move(rand()%LANDS); int choice = plant.size(); while(true) { int position; printInfor(*map, *player, zombie); do { position = player->Pos(); Land * land = map->GetLand(position); if(!land->IsEmpty()) { Plant *p = land->GetPlant(); int visit = p->Visit(*player); if(visit < 0) { map->Healing(p->HpBack()); cout << "All your plants have recovered "<< p->HpBack() << " HP!" << endl; break; } else if (visit) { cout << "You have earned $" << visit << "! Now you have $" << player->Money(); break; } else break; } else { if (!enoughMoney(plant, player)) { cout << "You don't have enough money to plant anything" << endl; break; } else { for(size_t i=0; i<plant.size(); ++i) { cout << "[" << i << "] " ; plant[i]->Print(); cout << endl; } cout << endl << "Player $" << player->Money() ; cout << ":\tEnter your choice (" << plant.size() << " to give up, default: " << choice << ")...>"; getline(cin, input); if(!input.empty()) { istringstream stream( input ); stream >> choice; if(choice > plant.size() || choice < 0) choice = plant.size(); } if(choice != plant.size()) { map->GetLand(player->Pos())->Planting(*player, *plant[choice]); cout << "You have planted " << plant[choice]->Name() << " at land " << player->Pos() << " !" << endl; } break; } if(choice != plant.size() && plant[choice]->Price() > player->Money()) { cout << "Not enough money! Please input again!" << endl; system("pause"); } } } while (true); system("pause"); system("cls"); for (int i=0; i<ZOMBIES; ++i) { if (zombie[i].isAlive()) { printInfor(*map, *player, zombie); position = rand()%LANDS; zombie[i].Move(position); cout << "Zombie [" << i << "] moves to land " << position << "." << endl; Land * land = map->GetLand(position); if(!land->IsEmpty()) { Plant *p = land->GetPlant(); p->Visit(zombie[i]); if(p->Attack()) { cout << p->Name() << " gives " << p->Attack() << " damage to the zombie!" << endl; } cout << "Zombie eats plant " << p->Name() << " and cause damage " << zombie[i].Attack() << endl; if(!zombie[i].isAlive()) cout << "Zombie is killed!" << endl; if(!p->isAlive()) { land->Dead(); cout << "Plant " << p->Name() << " is dead!" << endl; } } system("pause"); system("cls"); } } position = rand()%LANDS; player->Move(position); // end game condition system("cls"); //break; } // destruct while(!plant.empty()) { delete plant.back(); plant.pop_back(); } delete player; delete map; delete [] zombie; return 0; } bool endGame(const Map & map, const Zombie * zombie) { if (map.IsNonPlant()) { cout << "Oh no... You have no plant on the map ...." << endl; } else if (BombPlant::deadNum >= ZOMBIES/2) { cout << "You lose the game since you cannot use that many bomb plants!" << endl; } else if (allZombiesDie(zombie)) { cout << "Congratulations! You have killed all zombies!" << endl; } } bool allZombiesDie(const Zombie * zombie) { for(int i=0; i<Zombie::TotalNum && !zombie[i].isAlive(); ++i) return (i==Zombie::TotalNum-1); } bool enoughMoney(const vector<Plant*> & plant, const Player * player) { for (Plant* p : plant) if (p->Price() <= player->Money()) return true; return false; } void printInfor(const Map & map, const Player & player, const Zombie * zombie) { map.Display(player, zombie); cout << "------------------------------------------------" << endl; cout << "Zombie information:" << endl; for(int i=0; i<Zombie::TotalNum; ++i) { if(zombie[i].isAlive()) cout << '[' << i << "] " << zombie[i]; } cout << "================================================" << endl; } <|endoftext|>
<commit_before>/****************************************************************************** axelwrap First commit 06 Apr 2016 by Mike Seery https://github.com/roleohibachi/axlewrap An Intel Edison motion tracking tool, intended for sports coaching. Uses Sparkfun 9DOF and gnuplot-iostream. Development environment specifics: Uses i2c only, as it uses Sparkfun's library for comms. Code developed in vim, by rubbing two sticks together. This code requires the Intel mraa library to function; for more information see https://github.com/intel-iot-devkit/mraa This code is protected by an Apache v2.0 license. See LICENSE for more information. Distributed as-is; no warranty is given. Which is probably good, because I'm a rank amateur coder. If you can do better, please offer your help to the project! ******************************************************************************/ #include "mraa.hpp" #include <vector> #include <iostream> #include <unistd.h> #include "SFE_LSM9DS0.h" #include <fstream> //#define GNUPLOT_ENABLE_PTY //not working? #include "gnuplot-iostream.h" using namespace std; int buffSize = 100; std::vector<float> x_pts(buffSize, 0.0); LSM9DS0 *imu; bool newAccelData = false; const uint16_t chipID = 0x49d4; void getData(int howMany){ bool overflow = false; // Of course, we may care if an overflow occurred; we can check that // easily enough from an internal register on the part. There are functions // to check for overflow per device. overflow = imu->xDataOverflow(); if (overflow) { cerr<<"WARNING: Data overflow has occurred."<<endl; } cout << "DEBUG: getting " << howMany << " datapoints.\n"; for(int i=0;i<howMany;i++){ while ((newAccelData) != true){ if (newAccelData != true) { newAccelData = imu->newXData(); } } newAccelData = false; cout << "." << flush;//DEBUG // Calling these functions causes the data to be read from the IMU into // 10 16-bit signed integer public variables, as seen below. There is no // automated check on whether the data is new; you need to do that // manually as above. Also, there's no check on overflow, so you may miss // a sample and not know it. // cout << "DEBUG: Pulling the hot data...\n"; imu->readAccel(); // cout << "DEBUG: Pulled the hot data.\n"; // cout << "DEBUG: Storing the new data...\n"; x_pts.push_back(imu->calcAccel(imu->ax)); // cout << "DEBUG: Stored the new data (" <<x_pts.back() << ").\n"; // cout << "DEBUG: Resizing the vector...\n"; x_pts.erase(x_pts.begin()); // cout << "DEBUG: Resized the vector.\n"; } cout << endl; } int main() { //Gnuplot gp(stdout); //Gnuplot gp; //Gnuplot gp("tee out.gp | gnuplot -persist"); //gp << "set terminal png"<<endl; //gp << "set output out.png"<<endl; //cout << "DEBUG: gp configured\n"; imu = new LSM9DS0(0x6B, 0x1D); //the pinout addresses of the gyro and xm, respectively imu -> setAccelScale(imu -> A_SCALE_2G); imu -> setAccelODR(imu -> A_ODR_800); // 800 Hz (0x9) //cout << "DEBUG: IMU configured.\n"; uint16_t imuResult = imu->begin(); //cout<<hex<<"Chip ID: 0x"<<imuResult<<dec<<" (should be 0x49d4)"<<endl; //TODO fix this test to exit if the chip is bad if(imuResult != chipID){ cout << "The chip is enabled.\n"; }else{ cout << "The chip reported ID " << imuResult << endl; } //cout << "DEBUG: filling buffer...\n"; getData(buffSize); //fill with data, be patient. //cout << "DEBUG: Buffer full!\n"; // Loop and report data while (1) { getData(10); //cout << "DEBUG: Plotting data...\n"; //gp << "plot '-' using (column(0)):1 with lines"<<endl; //gp.send1d(x_pts); //cout << "DEBUG: latest is " << x_pts.back() << endl; //cout<<"Accel y: "<<imu->calcAccel(imu->ay)<<" g"<<endl; //cout<<"Accel z: "<<imu->calcAccel(imu->az)<<" g"<<endl; //sleep(1); } return MRAA_SUCCESS; } <commit_msg>first working prototype<commit_after>/****************************************************************************** axelwrap First commit 06 Apr 2016 by Mike Seery https://github.com/roleohibachi/axlewrap An Intel Edison motion tracking tool, intended for sports coaching. Uses Sparkfun 9DOF and gnuplot-iostream. Development environment specifics: Uses i2c only, as it uses Sparkfun's library for comms. Code developed in vim, by rubbing two sticks together. This code requires the Intel mraa library to function; for more information see https://github.com/intel-iot-devkit/mraa This code is protected by an Apache v2.0 license. See LICENSE for more information. Distributed as-is; no warranty is given. Which is probably good, because I'm a rank amateur coder. If you can do better, please offer your help to the project! ******************************************************************************/ #include "mraa.hpp" #include <vector> #include <iostream> #include <unistd.h> #include "SFE_LSM9DS0.h" #include <fstream> #include "gnuplot-iostream.h" using namespace std; int buffSize = 100; std::vector<float> x_pts(buffSize, 0.0); LSM9DS0 *imu; bool newAccelData = false; const uint16_t chipID = 0x49d4; void getData(int howMany){ bool overflow = false; // Of course, we may care if an overflow occurred; we can check that // easily enough from an internal register on the part. There are functions // to check for overflow per device. overflow = imu->xDataOverflow(); if (overflow) { cerr<<"WARNING: Data overflow has occurred."<<endl; } cout << "DEBUG: getting " << howMany << " datapoints.\n"; for(int i=0;i<howMany;i++){ while ((newAccelData) != true){ if (newAccelData != true) { newAccelData = imu->newXData(); } } newAccelData = false; cout << "." << flush;//DEBUG // Calling these functions causes the data to be read from the IMU into // 10 16-bit signed integer public variables, as seen below. There is no // automated check on whether the data is new; you need to do that // manually as above. Also, there's no check on overflow, so you may miss // a sample and not know it. // cout << "DEBUG: Pulling the hot data...\n"; imu->readAccel(); // cout << "DEBUG: Pulled the hot data.\n"; // cout << "DEBUG: Storing the new data...\n"; x_pts.push_back(imu->calcAccel(imu->ax)); // cout << "DEBUG: Stored the new data (" <<x_pts.back() << ").\n"; // cout << "DEBUG: Resizing the vector...\n"; x_pts.erase(x_pts.begin()); // cout << "DEBUG: Resized the vector.\n"; } cout << endl; } int main() { //Gnuplot gp(stdout); //Gnuplot gp; //Gnuplot gp(fopen("script.gp", "w")); Gnuplot gp("tee out.gp | gnuplot"); gp << "set terminal png\n"; cout << "DEBUG: gp configured\n"; imu = new LSM9DS0(0x6B, 0x1D); //the pinout addresses of the gyro and xm, respectively imu -> setAccelScale(imu -> A_SCALE_2G); imu -> setAccelODR(imu -> A_ODR_800); // 800 Hz (0x9) //cout << "DEBUG: IMU configured.\n"; uint16_t imuResult = imu->begin(); //cout<<hex<<"Chip ID: 0x"<<imuResult<<dec<<" (should be 0x49d4)"<<endl; //TODO fix this test to exit if the chip is bad if(imuResult != chipID){ cout << "The chip is enabled.\n"; }else{ cout << "The chip reported ID " << imuResult << endl; } //cout << "DEBUG: filling buffer...\n"; getData(buffSize); //fill with data, be patient. //cout << "DEBUG: Buffer full!\n"; // Loop and report data while (1) { getData(10); //cout << "DEBUG: Plotting data...\n"; rename("/var/www/stage.png","/var/www/out.png"); gp << "set output \"/var/www/stage.png\"\n"; gp << "plot '-' using (column(0)):1 with lines\n"; gp.send1d(x_pts); //gp << "plot" << gp.file1d(x_pts, "in.dat") << "with lines\n"; //cout << "DEBUG: plotted up through datapoint " << x_pts.back() << endl; //cout<<"Accel y: "<<imu->calcAccel(imu->ay)<<" g"<<endl; //cout<<"Accel z: "<<imu->calcAccel(imu->az)<<" g"<<endl; //sleep(1); } return MRAA_SUCCESS; } <|endoftext|>
<commit_before>9fb3f028-35ca-11e5-aef0-6c40088e03e4<commit_msg>9fbd7adc-35ca-11e5-a766-6c40088e03e4<commit_after>9fbd7adc-35ca-11e5-a766-6c40088e03e4<|endoftext|>
<commit_before>b16956a8-327f-11e5-8d48-9cf387a8033e<commit_msg>b16f3251-327f-11e5-83f7-9cf387a8033e<commit_after>b16f3251-327f-11e5-83f7-9cf387a8033e<|endoftext|>
<commit_before>#include "qtcamera.h" #include "qtcamscanner.h" #include "qtcamconfig.h" #include "qtcamdevice.h" #include <gst/gst.h> class QtCameraPrivate { public: QtCamConfig *conf; QtCamScanner *scanner; }; QtCamera::QtCamera(QObject *parent) : QObject(parent), d_ptr(new QtCameraPrivate) { gst_init(0, 0); d_ptr->conf = new QtCamConfig(this); d_ptr->scanner = new QtCamScanner(d_ptr->conf, this); refreshDevices(); } QtCamera::QtCamera(const QString& configPath, QObject *parent) : QObject(parent), d_ptr(new QtCameraPrivate) { gst_init(0, 0); d_ptr->conf = new QtCamConfig(configPath, this); d_ptr->scanner = new QtCamScanner(d_ptr->conf, this); refreshDevices(); } QtCamera::QtCamera(QtCamConfig *config, QObject *parent) : QObject(parent), d_ptr(new QtCameraPrivate) { gst_init(0, 0); d_ptr->conf = config; d_ptr->scanner = new QtCamScanner(d_ptr->conf, this); refreshDevices(); } QtCamera::~QtCamera() { delete d_ptr; d_ptr = 0; gst_deinit(); } void QtCamera::refreshDevices() { d_ptr->scanner->refresh(); } QList<QPair<QString, QVariant> > QtCamera::devices() const { return d_ptr->scanner->devices(); } QtCamDevice *QtCamera::device(const QVariant& id, QObject *parent) { QList<QPair<QString, QVariant> > devs = devices(); // G++ barfs with foreach and class templates. typedef QPair<QString, QVariant> Dev; foreach (const Dev& dev, devs) { if (dev.second == id) { return new QtCamDevice(d_ptr->conf, dev.first, dev.second, parent ? parent : this); } } return 0; } QtCamConfig *QtCamera::config() const { return d_ptr->conf; } <commit_msg>Removed extra new line<commit_after>#include "qtcamera.h" #include "qtcamscanner.h" #include "qtcamconfig.h" #include "qtcamdevice.h" #include <gst/gst.h> class QtCameraPrivate { public: QtCamConfig *conf; QtCamScanner *scanner; }; QtCamera::QtCamera(QObject *parent) : QObject(parent), d_ptr(new QtCameraPrivate) { gst_init(0, 0); d_ptr->conf = new QtCamConfig(this); d_ptr->scanner = new QtCamScanner(d_ptr->conf, this); refreshDevices(); } QtCamera::QtCamera(const QString& configPath, QObject *parent) : QObject(parent), d_ptr(new QtCameraPrivate) { gst_init(0, 0); d_ptr->conf = new QtCamConfig(configPath, this); d_ptr->scanner = new QtCamScanner(d_ptr->conf, this); refreshDevices(); } QtCamera::QtCamera(QtCamConfig *config, QObject *parent) : QObject(parent), d_ptr(new QtCameraPrivate) { gst_init(0, 0); d_ptr->conf = config; d_ptr->scanner = new QtCamScanner(d_ptr->conf, this); refreshDevices(); } QtCamera::~QtCamera() { delete d_ptr; d_ptr = 0; gst_deinit(); } void QtCamera::refreshDevices() { d_ptr->scanner->refresh(); } QList<QPair<QString, QVariant> > QtCamera::devices() const { return d_ptr->scanner->devices(); } QtCamDevice *QtCamera::device(const QVariant& id, QObject *parent) { QList<QPair<QString, QVariant> > devs = devices(); // G++ barfs with foreach and class templates. typedef QPair<QString, QVariant> Dev; foreach (const Dev& dev, devs) { if (dev.second == id) { return new QtCamDevice(d_ptr->conf, dev.first, dev.second, parent ? parent : this); } } return 0; } QtCamConfig *QtCamera::config() const { return d_ptr->conf; } <|endoftext|>
<commit_before>9101add8-2d14-11e5-af21-0401358ea401<commit_msg>9101add9-2d14-11e5-af21-0401358ea401<commit_after>9101add9-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>9bd04e82-ad5c-11e7-80c1-ac87a332f658<commit_msg>having coffee<commit_after>9c6440d9-ad5c-11e7-bdd9-ac87a332f658<|endoftext|>
<commit_before>a6de4ada-35ca-11e5-987c-6c40088e03e4<commit_msg>a6e69348-35ca-11e5-977b-6c40088e03e4<commit_after>a6e69348-35ca-11e5-977b-6c40088e03e4<|endoftext|>
<commit_before>/* * events.cpp * * Created on: 26 mars 2013 * Author: dom */ #include <iostream> #include <sstream> #include "events.h" #include "scheduler.h" #include "blockCode.h" int Event::nextId = 0; unsigned int Event::nbLivingEvents = 0; using namespace std; using namespace BaseSimulator; //=========================================================================================================== // // Event (class) // //=========================================================================================================== Event::Event(Time t) { id = nextId; nextId++; nbLivingEvents++; date = t; eventType = EVENT_GENERIC; randomNumber = 0; EVENT_CONSTRUCTOR_INFO(); } Event::Event(Event *ev) { id = nextId; nextId++; nbLivingEvents++; date = ev->date; eventType = ev->eventType; randomNumber = 0; EVENT_CONSTRUCTOR_INFO(); } Event::~Event() { EVENT_DESTRUCTOR_INFO(); nbLivingEvents--; } const string Event::getEventName() { return("Generic Event"); } unsigned int Event::getNextId() { return(nextId); } unsigned int Event::getNbLivingEvents() { return(nbLivingEvents); } //=========================================================================================================== // // BlockEvent (class) // //=========================================================================================================== BlockEvent::BlockEvent(Time t, BaseSimulator::BuildingBlock *conBlock) : Event(t) { EVENT_CONSTRUCTOR_INFO(); concernedBlock = conBlock; eventType = BLOCKEVENT_GENERIC; } BlockEvent::BlockEvent(BlockEvent *ev) : Event(ev) { EVENT_CONSTRUCTOR_INFO(); concernedBlock = ev->concernedBlock; } BlockEvent::~BlockEvent() { EVENT_DESTRUCTOR_INFO(); } const string BlockEvent::getEventName() { return("Generic BlockEvent"); } //=========================================================================================================== // // CodeStartEvent (class) // //=========================================================================================================== CodeStartEvent::CodeStartEvent(Time t, BaseSimulator::BuildingBlock *conBlock): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_CODE_START; } CodeStartEvent::~CodeStartEvent() { EVENT_DESTRUCTOR_INFO(); } void CodeStartEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->blockCode->startup(); } const string CodeStartEvent::getEventName() { return("CodeStart Event"); } //=========================================================================================================== // // CodeEndSimulationEvent (class) // //=========================================================================================================== CodeEndSimulationEvent::CodeEndSimulationEvent(Time t): Event(t) { eventType = EVENT_END_SIMULATION; EVENT_CONSTRUCTOR_INFO(); } CodeEndSimulationEvent::~CodeEndSimulationEvent() { EVENT_DESTRUCTOR_INFO(); } void CodeEndSimulationEvent::consume() { EVENT_CONSUME_INFO(); BaseSimulator::getScheduler()->setState(BaseSimulator::Scheduler::ENDED); } const string CodeEndSimulationEvent::getEventName() { return("CodeEndSimulation Event"); } //=========================================================================================================== // // ProcessLocalEvent (class) // //=========================================================================================================== ProcessLocalEvent::ProcessLocalEvent(Time t, BaseSimulator::BuildingBlock *conBlock): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_PROCESS_LOCAL_EVENT; } ProcessLocalEvent::~ProcessLocalEvent() { EVENT_DESTRUCTOR_INFO(); } void ProcessLocalEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->processLocalEvent(); } const string ProcessLocalEvent::getEventName() { return("ProcessLocal Event"); } //=========================================================================================================== // // NetworkInterfaceStartTransmittingEvent (class) // //=========================================================================================================== NetworkInterfaceStartTransmittingEvent::NetworkInterfaceStartTransmittingEvent(Time t, P2PNetworkInterface *ni):Event(t) { eventType = EVENT_NI_START_TRANSMITTING; interface = ni; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceStartTransmittingEvent::~NetworkInterfaceStartTransmittingEvent() { EVENT_DESTRUCTOR_INFO(); } void NetworkInterfaceStartTransmittingEvent::consume() { EVENT_CONSUME_INFO(); interface->send(); } const string NetworkInterfaceStartTransmittingEvent::getEventName() { return("NetworkInterfaceStartTransmitting Event"); } //=========================================================================================================== // // NetworkInterfaceStopTransmittingEvent (class) // //=========================================================================================================== NetworkInterfaceStopTransmittingEvent::NetworkInterfaceStopTransmittingEvent(Time t, P2PNetworkInterface *ni):Event(t) { eventType = EVENT_NI_STOP_TRANSMITTING; interface = ni; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceStopTransmittingEvent::~NetworkInterfaceStopTransmittingEvent() { EVENT_DESTRUCTOR_INFO(); } void NetworkInterfaceStopTransmittingEvent::consume() { EVENT_CONSUME_INFO(); if (!interface->connectedInterface) { cerr << "Warning: connection loss, untransmitted message!" << endl; } else { interface->connectedInterface->hostBlock->scheduleLocalEvent(EventPtr(new NetworkInterfaceReceiveEvent(BaseSimulator::getScheduler()->now(), interface->connectedInterface, interface->messageBeingTransmitted))); } interface->messageBeingTransmitted.reset(); interface->availabilityDate = BaseSimulator::getScheduler()->now(); if (interface->outgoingQueue.size() > 0) { //cout << "one more to send !!" << endl; interface->send(); } } const string NetworkInterfaceStopTransmittingEvent::getEventName() { return("NetworkInterfaceStopTransmitting Event"); } //=========================================================================================================== // // NetworkInterfaceReceiveEvent (class) // //=========================================================================================================== NetworkInterfaceReceiveEvent::NetworkInterfaceReceiveEvent(Time t, P2PNetworkInterface *ni, MessagePtr mes):Event(t) { eventType = EVENT_NI_RECEIVE; interface = ni; message = mes; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceReceiveEvent::~NetworkInterfaceReceiveEvent() { message.reset(); EVENT_DESTRUCTOR_INFO(); } void NetworkInterfaceReceiveEvent::consume() { EVENT_CONSUME_INFO(); } const string NetworkInterfaceReceiveEvent::getEventName() { return("NetworkInterfaceReceiveEvent Event"); } //=========================================================================================================== // // NetworkInterfaceEnqueueOutgoingEvent (class) // //=========================================================================================================== NetworkInterfaceEnqueueOutgoingEvent::NetworkInterfaceEnqueueOutgoingEvent(Time t, Message *mes, P2PNetworkInterface *ni):Event(t) { eventType = EVENT_NI_ENQUEUE_OUTGOING_MESSAGE; message = MessagePtr(mes); sourceInterface = ni; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceEnqueueOutgoingEvent::NetworkInterfaceEnqueueOutgoingEvent(Time t, MessagePtr mes, P2PNetworkInterface *ni):Event(t) { eventType = EVENT_NI_ENQUEUE_OUTGOING_MESSAGE; message = mes; sourceInterface = ni; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceEnqueueOutgoingEvent::~NetworkInterfaceEnqueueOutgoingEvent() { message.reset(); EVENT_DESTRUCTOR_INFO(); } void NetworkInterfaceEnqueueOutgoingEvent::consume() { EVENT_CONSUME_INFO(); sourceInterface->addToOutgoingBuffer(message); } const string NetworkInterfaceEnqueueOutgoingEvent::getEventName() { return("NetworkInterfaceEnqueueOutgoingEvent Event"); } //=========================================================================================================== // // SetColorEvent (class) // //=========================================================================================================== SetColorEvent::SetColorEvent(Time t, BuildingBlock *conBlock, float r, float g, float b, float a): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_SET_COLOR; randomNumber = conBlock->getNextRandomNumber(); color = Color(r, g, b, a); } SetColorEvent::SetColorEvent(Time t, BuildingBlock *conBlock, Color &c): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_SET_COLOR; randomNumber = conBlock->getNextRandomNumber(); color = c; } SetColorEvent::SetColorEvent(SetColorEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); color = ev->color; //randomNumber = ev->randomNumber; } SetColorEvent::~SetColorEvent() { EVENT_DESTRUCTOR_INFO(); } void SetColorEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new SetColorEvent(this))); } const string SetColorEvent::getEventName() { return("SetColor Event"); } //=========================================================================================================== // // AddNeighborEvent (class) // //=========================================================================================================== AddNeighborEvent::AddNeighborEvent(Time t, BuildingBlock *conBlock, uint64_t f, uint64_t ta): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_ADD_NEIGHBOR; face = f; target = ta; } AddNeighborEvent::AddNeighborEvent(AddNeighborEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); face = ev->face; target = ev->target; } AddNeighborEvent::~AddNeighborEvent() { EVENT_DESTRUCTOR_INFO(); } void AddNeighborEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new AddNeighborEvent(this))); } const string AddNeighborEvent::getEventName() { return("AddNeighbor Event"); } //=========================================================================================================== // // RemoveNeighborEvent (class) // //=========================================================================================================== RemoveNeighborEvent::RemoveNeighborEvent(Time t, BuildingBlock *conBlock, uint64_t f): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_REMOVE_NEIGHBOR; face = f; } RemoveNeighborEvent::RemoveNeighborEvent(RemoveNeighborEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); face = ev->face; } RemoveNeighborEvent::~RemoveNeighborEvent() { EVENT_DESTRUCTOR_INFO(); } void RemoveNeighborEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new RemoveNeighborEvent(this))); } const string RemoveNeighborEvent::getEventName() { return("RemoveNeighbor Event"); } //=========================================================================================================== // // TapEvent (class) // //=========================================================================================================== TapEvent::TapEvent(Time t, BuildingBlock *conBlock, const int face): BlockEvent(t, conBlock), tappedFace(face) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_TAP; } TapEvent::TapEvent(TapEvent *ev) : BlockEvent(ev), tappedFace(ev->tappedFace) { EVENT_CONSTRUCTOR_INFO(); } TapEvent::~TapEvent() { EVENT_DESTRUCTOR_INFO(); } void TapEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new TapEvent(this))); } const string TapEvent::getEventName() { return("Tap Event"); } //=========================================================================================================== // // AccelEvent (class) // //=========================================================================================================== AccelEvent::AccelEvent(Time t, BuildingBlock *conBlock, uint64_t xx, uint64_t yy, uint64_t zz): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_ACCEL; x = xx; y = yy; z = zz; } AccelEvent::AccelEvent(AccelEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); x = ev->x; y = ev->y; z = ev->z; } AccelEvent::~AccelEvent() { EVENT_DESTRUCTOR_INFO(); } void AccelEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new AccelEvent(this))); } const string AccelEvent::getEventName() { return("Accel Event"); } //=========================================================================================================== // // ShakeEvent (class) // //=========================================================================================================== ShakeEvent::ShakeEvent(Time t, BuildingBlock *conBlock, uint64_t f): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_SHAKE; force = f; } ShakeEvent::ShakeEvent(ShakeEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); force = ev->force; } ShakeEvent::~ShakeEvent() { EVENT_DESTRUCTOR_INFO(); } void ShakeEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new ShakeEvent(this))); } const string ShakeEvent::getEventName() { return("Shake Event"); } <commit_msg>Warning for message loss due to disconnection is now printed in the simulation log file.<commit_after>/* * events.cpp * * Created on: 26 mars 2013 * Author: dom */ #include <iostream> #include <sstream> #include "events.h" #include "scheduler.h" #include "blockCode.h" int Event::nextId = 0; unsigned int Event::nbLivingEvents = 0; using namespace std; using namespace BaseSimulator; //=========================================================================================================== // // Event (class) // //=========================================================================================================== Event::Event(Time t) { id = nextId; nextId++; nbLivingEvents++; date = t; eventType = EVENT_GENERIC; randomNumber = 0; EVENT_CONSTRUCTOR_INFO(); } Event::Event(Event *ev) { id = nextId; nextId++; nbLivingEvents++; date = ev->date; eventType = ev->eventType; randomNumber = 0; EVENT_CONSTRUCTOR_INFO(); } Event::~Event() { EVENT_DESTRUCTOR_INFO(); nbLivingEvents--; } const string Event::getEventName() { return("Generic Event"); } unsigned int Event::getNextId() { return(nextId); } unsigned int Event::getNbLivingEvents() { return(nbLivingEvents); } //=========================================================================================================== // // BlockEvent (class) // //=========================================================================================================== BlockEvent::BlockEvent(Time t, BaseSimulator::BuildingBlock *conBlock) : Event(t) { EVENT_CONSTRUCTOR_INFO(); concernedBlock = conBlock; eventType = BLOCKEVENT_GENERIC; } BlockEvent::BlockEvent(BlockEvent *ev) : Event(ev) { EVENT_CONSTRUCTOR_INFO(); concernedBlock = ev->concernedBlock; } BlockEvent::~BlockEvent() { EVENT_DESTRUCTOR_INFO(); } const string BlockEvent::getEventName() { return("Generic BlockEvent"); } //=========================================================================================================== // // CodeStartEvent (class) // //=========================================================================================================== CodeStartEvent::CodeStartEvent(Time t, BaseSimulator::BuildingBlock *conBlock): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_CODE_START; } CodeStartEvent::~CodeStartEvent() { EVENT_DESTRUCTOR_INFO(); } void CodeStartEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->blockCode->startup(); } const string CodeStartEvent::getEventName() { return("CodeStart Event"); } //=========================================================================================================== // // CodeEndSimulationEvent (class) // //=========================================================================================================== CodeEndSimulationEvent::CodeEndSimulationEvent(Time t): Event(t) { eventType = EVENT_END_SIMULATION; EVENT_CONSTRUCTOR_INFO(); } CodeEndSimulationEvent::~CodeEndSimulationEvent() { EVENT_DESTRUCTOR_INFO(); } void CodeEndSimulationEvent::consume() { EVENT_CONSUME_INFO(); BaseSimulator::getScheduler()->setState(BaseSimulator::Scheduler::ENDED); } const string CodeEndSimulationEvent::getEventName() { return("CodeEndSimulation Event"); } //=========================================================================================================== // // ProcessLocalEvent (class) // //=========================================================================================================== ProcessLocalEvent::ProcessLocalEvent(Time t, BaseSimulator::BuildingBlock *conBlock): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_PROCESS_LOCAL_EVENT; } ProcessLocalEvent::~ProcessLocalEvent() { EVENT_DESTRUCTOR_INFO(); } void ProcessLocalEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->processLocalEvent(); } const string ProcessLocalEvent::getEventName() { return("ProcessLocal Event"); } //=========================================================================================================== // // NetworkInterfaceStartTransmittingEvent (class) // //=========================================================================================================== NetworkInterfaceStartTransmittingEvent::NetworkInterfaceStartTransmittingEvent(Time t, P2PNetworkInterface *ni):Event(t) { eventType = EVENT_NI_START_TRANSMITTING; interface = ni; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceStartTransmittingEvent::~NetworkInterfaceStartTransmittingEvent() { EVENT_DESTRUCTOR_INFO(); } void NetworkInterfaceStartTransmittingEvent::consume() { EVENT_CONSUME_INFO(); interface->send(); } const string NetworkInterfaceStartTransmittingEvent::getEventName() { return("NetworkInterfaceStartTransmitting Event"); } //=========================================================================================================== // // NetworkInterfaceStopTransmittingEvent (class) // //=========================================================================================================== NetworkInterfaceStopTransmittingEvent::NetworkInterfaceStopTransmittingEvent(Time t, P2PNetworkInterface *ni):Event(t) { eventType = EVENT_NI_STOP_TRANSMITTING; interface = ni; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceStopTransmittingEvent::~NetworkInterfaceStopTransmittingEvent() { EVENT_DESTRUCTOR_INFO(); } void NetworkInterfaceStopTransmittingEvent::consume() { EVENT_CONSUME_INFO(); if (!interface->connectedInterface) { ERRPUT << "Warning: connection loss, untransmitted message!" << endl; } else { interface->connectedInterface->hostBlock->scheduleLocalEvent(EventPtr(new NetworkInterfaceReceiveEvent(BaseSimulator::getScheduler()->now(), interface->connectedInterface, interface->messageBeingTransmitted))); } interface->messageBeingTransmitted.reset(); interface->availabilityDate = BaseSimulator::getScheduler()->now(); if (interface->outgoingQueue.size() > 0) { //cout << "one more to send !!" << endl; interface->send(); } } const string NetworkInterfaceStopTransmittingEvent::getEventName() { return("NetworkInterfaceStopTransmitting Event"); } //=========================================================================================================== // // NetworkInterfaceReceiveEvent (class) // //=========================================================================================================== NetworkInterfaceReceiveEvent::NetworkInterfaceReceiveEvent(Time t, P2PNetworkInterface *ni, MessagePtr mes):Event(t) { eventType = EVENT_NI_RECEIVE; interface = ni; message = mes; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceReceiveEvent::~NetworkInterfaceReceiveEvent() { message.reset(); EVENT_DESTRUCTOR_INFO(); } void NetworkInterfaceReceiveEvent::consume() { EVENT_CONSUME_INFO(); } const string NetworkInterfaceReceiveEvent::getEventName() { return("NetworkInterfaceReceiveEvent Event"); } //=========================================================================================================== // // NetworkInterfaceEnqueueOutgoingEvent (class) // //=========================================================================================================== NetworkInterfaceEnqueueOutgoingEvent::NetworkInterfaceEnqueueOutgoingEvent(Time t, Message *mes, P2PNetworkInterface *ni):Event(t) { eventType = EVENT_NI_ENQUEUE_OUTGOING_MESSAGE; message = MessagePtr(mes); sourceInterface = ni; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceEnqueueOutgoingEvent::NetworkInterfaceEnqueueOutgoingEvent(Time t, MessagePtr mes, P2PNetworkInterface *ni):Event(t) { eventType = EVENT_NI_ENQUEUE_OUTGOING_MESSAGE; message = mes; sourceInterface = ni; EVENT_CONSTRUCTOR_INFO(); } NetworkInterfaceEnqueueOutgoingEvent::~NetworkInterfaceEnqueueOutgoingEvent() { message.reset(); EVENT_DESTRUCTOR_INFO(); } void NetworkInterfaceEnqueueOutgoingEvent::consume() { EVENT_CONSUME_INFO(); sourceInterface->addToOutgoingBuffer(message); } const string NetworkInterfaceEnqueueOutgoingEvent::getEventName() { return("NetworkInterfaceEnqueueOutgoingEvent Event"); } //=========================================================================================================== // // SetColorEvent (class) // //=========================================================================================================== SetColorEvent::SetColorEvent(Time t, BuildingBlock *conBlock, float r, float g, float b, float a): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_SET_COLOR; randomNumber = conBlock->getNextRandomNumber(); color = Color(r, g, b, a); } SetColorEvent::SetColorEvent(Time t, BuildingBlock *conBlock, Color &c): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_SET_COLOR; randomNumber = conBlock->getNextRandomNumber(); color = c; } SetColorEvent::SetColorEvent(SetColorEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); color = ev->color; //randomNumber = ev->randomNumber; } SetColorEvent::~SetColorEvent() { EVENT_DESTRUCTOR_INFO(); } void SetColorEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new SetColorEvent(this))); } const string SetColorEvent::getEventName() { return("SetColor Event"); } //=========================================================================================================== // // AddNeighborEvent (class) // //=========================================================================================================== AddNeighborEvent::AddNeighborEvent(Time t, BuildingBlock *conBlock, uint64_t f, uint64_t ta): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_ADD_NEIGHBOR; face = f; target = ta; } AddNeighborEvent::AddNeighborEvent(AddNeighborEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); face = ev->face; target = ev->target; } AddNeighborEvent::~AddNeighborEvent() { EVENT_DESTRUCTOR_INFO(); } void AddNeighborEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new AddNeighborEvent(this))); } const string AddNeighborEvent::getEventName() { return("AddNeighbor Event"); } //=========================================================================================================== // // RemoveNeighborEvent (class) // //=========================================================================================================== RemoveNeighborEvent::RemoveNeighborEvent(Time t, BuildingBlock *conBlock, uint64_t f): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_REMOVE_NEIGHBOR; face = f; } RemoveNeighborEvent::RemoveNeighborEvent(RemoveNeighborEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); face = ev->face; } RemoveNeighborEvent::~RemoveNeighborEvent() { EVENT_DESTRUCTOR_INFO(); } void RemoveNeighborEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new RemoveNeighborEvent(this))); } const string RemoveNeighborEvent::getEventName() { return("RemoveNeighbor Event"); } //=========================================================================================================== // // TapEvent (class) // //=========================================================================================================== TapEvent::TapEvent(Time t, BuildingBlock *conBlock, const int face): BlockEvent(t, conBlock), tappedFace(face) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_TAP; } TapEvent::TapEvent(TapEvent *ev) : BlockEvent(ev), tappedFace(ev->tappedFace) { EVENT_CONSTRUCTOR_INFO(); } TapEvent::~TapEvent() { EVENT_DESTRUCTOR_INFO(); } void TapEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new TapEvent(this))); } const string TapEvent::getEventName() { return("Tap Event"); } //=========================================================================================================== // // AccelEvent (class) // //=========================================================================================================== AccelEvent::AccelEvent(Time t, BuildingBlock *conBlock, uint64_t xx, uint64_t yy, uint64_t zz): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_ACCEL; x = xx; y = yy; z = zz; } AccelEvent::AccelEvent(AccelEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); x = ev->x; y = ev->y; z = ev->z; } AccelEvent::~AccelEvent() { EVENT_DESTRUCTOR_INFO(); } void AccelEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new AccelEvent(this))); } const string AccelEvent::getEventName() { return("Accel Event"); } //=========================================================================================================== // // ShakeEvent (class) // //=========================================================================================================== ShakeEvent::ShakeEvent(Time t, BuildingBlock *conBlock, uint64_t f): BlockEvent(t, conBlock) { EVENT_CONSTRUCTOR_INFO(); eventType = EVENT_SHAKE; force = f; } ShakeEvent::ShakeEvent(ShakeEvent *ev) : BlockEvent(ev) { EVENT_CONSTRUCTOR_INFO(); force = ev->force; } ShakeEvent::~ShakeEvent() { EVENT_DESTRUCTOR_INFO(); } void ShakeEvent::consumeBlockEvent() { EVENT_CONSUME_INFO(); concernedBlock->scheduleLocalEvent(EventPtr(new ShakeEvent(this))); } const string ShakeEvent::getEventName() { return("Shake Event"); } <|endoftext|>
<commit_before><commit_msg>fix double-delete<commit_after><|endoftext|>
<commit_before><commit_msg>Set default cycle time to 0<commit_after><|endoftext|>
<commit_before>#include <assert.h> #include <stdio.h> #include <atomic> #include <new> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <pthread.h> #include <signal.h> #include <setjmp.h> #include <sys/wait.h> #include <sys/mman.h> #include "mtrace.h" #include "fstest.h" #include "libutil.h" #include "spinbarrier.hh" extern char _end[]; __thread sigjmp_buf pf_jmpbuf; __thread int pf_active; class double_barrier { spin_barrier enter_; spin_barrier exit_; public: double_barrier() : enter_(2), exit_(2) {} void sync() { enter(); exit(); } void enter() { enter_.join(); } void exit() { exit_.join(); } }; struct testproc { double_barrier setup; std::atomic<void (*)(void)> setupf; testproc(void (*s)(void)) : setupf(s) {} void run() { setup.enter(); setupf(); setup.exit(); } }; struct testfunc { double_barrier start; double_barrier stop; std::atomic<int (*)(void)> func; std::atomic<int> retval; testfunc(int (*f)(void)) : func(f) {} void run() { start.sync(); retval = func(); stop.sync(); } }; static void* testfunc_thread(void* arg) { madvise(0, (size_t) _end, MADV_WILLNEED); testfunc* f = (testfunc*) arg; f->run(); return nullptr; } static void run_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin) { assert(first_func == 0 || first_func == 1); if (do_pin) setaffinity(2); for (int i = 0; i < 2; i++) new (&tp[i]) testproc(t->proc[i].setup_proc); for (int i = 0; i < 2; i++) new (&tf[i]) testfunc(t->func[i].call); pid_t pids[2] = { 0, 0 }; for (int p = 0; p < 2; p++) { int nfunc = 0; for (int f = 0; f < 2; f++) if (t->func[f].callproc == p) nfunc++; if (nfunc == 0) continue; pids[p] = fork(); assert(pids[p] >= 0); if (pids[p] == 0) { madvise(0, (size_t) _end, MADV_WILLNEED); tp[p].run(); int ndone = 0; pthread_t tid[2]; for (int f = 0; f < 2; f++) { if (t->func[f].callproc == p) { if (do_pin) setaffinity(f); ndone++; if (ndone == nfunc) testfunc_thread(&tf[f]); else pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]); } } if (nfunc == 2) pthread_join(tid[0], nullptr); exit(0); } } t->setup_common(); for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync(); t->setup_final(); for (int i = 0; i < 2; i++) tf[i].start.enter(); char mtname[64]; snprintf(mtname, sizeof(mtname), "%s", t->testname); mtenable_type(mtrace_record_ascope, mtname); for (int i = 0; i < 2; i++) { tf[first_func ^ i].start.exit(); tf[first_func ^ i].stop.enter(); } mtdisable(mtname); for (int i = 0; i < 2; i++) tf[i].stop.exit(); for (int p = 0; p < 2; p++) if (pids[p]) assert(waitpid(pids[p], nullptr, 0) >= 0); t->cleanup(); } static void pf_handler(int signo) { if (pf_active) siglongjmp(pf_jmpbuf, signo); // Let the error happen signal(signo, SIG_DFL); } static bool verbose = false; static bool check_commutativity = false; static bool run_threads = false; static void usage(const char* prog) { fprintf(stderr, "Usage: %s [-v] [-c] [-t] [-n NPARTS] [-p THISPART] [min[-max]]\n", prog); } int main(int ac, char** av) { uint32_t min = 0; uint32_t max = UINT_MAX; int nparts = -1; int thispart = -1; uint32_t ntests = 0; for (ntests = min; fstests[ntests].testname; ntests++) ; for (;;) { int opt = getopt(ac, av, "vctp:n:"); if (opt == -1) break; switch (opt) { case 'v': verbose = true; break; case 'c': check_commutativity = true; break; case 't': run_threads = true; break; case 'n': nparts = atoi(optarg); break; case 'p': thispart = atoi(optarg); break; default: usage(av[0]); return -1; } } if (optind < ac) { char* dash = strchr(av[optind], '-'); if (!dash) { min = max = atoi(av[optind]); } else { *dash = '\0'; min = atoi(av[optind]); max = atoi(dash + 1); } } else if (nparts >= 0 || thispart >= 0) { if (nparts < 0 || thispart < 0) { usage(av[0]); return -1; } uint32_t partsize = (ntests + nparts - 1) /nparts; min = partsize * thispart; max = partsize * (thispart + 1) - 1; } if (!check_commutativity && !run_threads) { fprintf(stderr, "Must specify one of -c or -t\n"); usage(av[0]); return -1; } printf("fstest:"); if (verbose) printf(" verbose"); if (check_commutativity) printf(" check"); if (run_threads) printf(" threads"); if (min == 0 && max == UINT_MAX) printf(" all"); else if (min == max) printf(" %d", min); else printf(" %d-%d", min, max); printf("\n"); testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); assert(tp != MAP_FAILED); assert(2*sizeof(*tp) <= 4096); testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); assert(tf != MAP_FAILED); assert(2*sizeof(*tf) <= 4096); madvise(0, (size_t) _end, MADV_WILLNEED); signal(SIGBUS, pf_handler); signal(SIGSEGV, pf_handler); for (uint32_t t = min; t <= max && t < ntests; t++) { if (check_commutativity) { run_test(tp, tf, &fstests[t], 0, false); int ra0 = tf[0].retval; int ra1 = tf[1].retval; run_test(tp, tf, &fstests[t], 1, false); int rb0 = tf[0].retval; int rb1 = tf[1].retval; if (ra0 == rb0 && ra1 == rb1) { if (verbose) printf("%s: commutes: %s->%d %s->%d\n", fstests[t].testname, fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1); } else { printf("%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\n", fstests[t].testname, fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1, fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0); } } if (run_threads) { run_test(tp, tf, &fstests[t], 0, true); printf("%s: threads done\n", fstests[t].testname); } } } <commit_msg>fstest: Flush stdout before forking<commit_after>#include <assert.h> #include <stdio.h> #include <atomic> #include <new> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <pthread.h> #include <signal.h> #include <setjmp.h> #include <sys/wait.h> #include <sys/mman.h> #include "mtrace.h" #include "fstest.h" #include "libutil.h" #include "spinbarrier.hh" extern char _end[]; __thread sigjmp_buf pf_jmpbuf; __thread int pf_active; class double_barrier { spin_barrier enter_; spin_barrier exit_; public: double_barrier() : enter_(2), exit_(2) {} void sync() { enter(); exit(); } void enter() { enter_.join(); } void exit() { exit_.join(); } }; struct testproc { double_barrier setup; std::atomic<void (*)(void)> setupf; testproc(void (*s)(void)) : setupf(s) {} void run() { setup.enter(); setupf(); setup.exit(); } }; struct testfunc { double_barrier start; double_barrier stop; std::atomic<int (*)(void)> func; std::atomic<int> retval; testfunc(int (*f)(void)) : func(f) {} void run() { start.sync(); retval = func(); stop.sync(); } }; static void* testfunc_thread(void* arg) { madvise(0, (size_t) _end, MADV_WILLNEED); testfunc* f = (testfunc*) arg; f->run(); return nullptr; } static void run_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin) { assert(first_func == 0 || first_func == 1); if (do_pin) setaffinity(2); for (int i = 0; i < 2; i++) new (&tp[i]) testproc(t->proc[i].setup_proc); for (int i = 0; i < 2; i++) new (&tf[i]) testfunc(t->func[i].call); pid_t pids[2] = { 0, 0 }; for (int p = 0; p < 2; p++) { int nfunc = 0; for (int f = 0; f < 2; f++) if (t->func[f].callproc == p) nfunc++; if (nfunc == 0) continue; fflush(stdout); pids[p] = fork(); assert(pids[p] >= 0); if (pids[p] == 0) { madvise(0, (size_t) _end, MADV_WILLNEED); tp[p].run(); int ndone = 0; pthread_t tid[2]; for (int f = 0; f < 2; f++) { if (t->func[f].callproc == p) { if (do_pin) setaffinity(f); ndone++; if (ndone == nfunc) testfunc_thread(&tf[f]); else pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]); } } if (nfunc == 2) pthread_join(tid[0], nullptr); exit(0); } } t->setup_common(); for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync(); t->setup_final(); for (int i = 0; i < 2; i++) tf[i].start.enter(); char mtname[64]; snprintf(mtname, sizeof(mtname), "%s", t->testname); mtenable_type(mtrace_record_ascope, mtname); for (int i = 0; i < 2; i++) { tf[first_func ^ i].start.exit(); tf[first_func ^ i].stop.enter(); } mtdisable(mtname); for (int i = 0; i < 2; i++) tf[i].stop.exit(); for (int p = 0; p < 2; p++) if (pids[p]) assert(waitpid(pids[p], nullptr, 0) >= 0); t->cleanup(); } static void pf_handler(int signo) { if (pf_active) siglongjmp(pf_jmpbuf, signo); // Let the error happen signal(signo, SIG_DFL); } static bool verbose = false; static bool check_commutativity = false; static bool run_threads = false; static void usage(const char* prog) { fprintf(stderr, "Usage: %s [-v] [-c] [-t] [-n NPARTS] [-p THISPART] [min[-max]]\n", prog); } int main(int ac, char** av) { uint32_t min = 0; uint32_t max = UINT_MAX; int nparts = -1; int thispart = -1; uint32_t ntests = 0; for (ntests = min; fstests[ntests].testname; ntests++) ; for (;;) { int opt = getopt(ac, av, "vctp:n:"); if (opt == -1) break; switch (opt) { case 'v': verbose = true; break; case 'c': check_commutativity = true; break; case 't': run_threads = true; break; case 'n': nparts = atoi(optarg); break; case 'p': thispart = atoi(optarg); break; default: usage(av[0]); return -1; } } if (optind < ac) { char* dash = strchr(av[optind], '-'); if (!dash) { min = max = atoi(av[optind]); } else { *dash = '\0'; min = atoi(av[optind]); max = atoi(dash + 1); } } else if (nparts >= 0 || thispart >= 0) { if (nparts < 0 || thispart < 0) { usage(av[0]); return -1; } uint32_t partsize = (ntests + nparts - 1) /nparts; min = partsize * thispart; max = partsize * (thispart + 1) - 1; } if (!check_commutativity && !run_threads) { fprintf(stderr, "Must specify one of -c or -t\n"); usage(av[0]); return -1; } printf("fstest:"); if (verbose) printf(" verbose"); if (check_commutativity) printf(" check"); if (run_threads) printf(" threads"); if (min == 0 && max == UINT_MAX) printf(" all"); else if (min == max) printf(" %d", min); else printf(" %d-%d", min, max); printf("\n"); testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); assert(tp != MAP_FAILED); assert(2*sizeof(*tp) <= 4096); testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); assert(tf != MAP_FAILED); assert(2*sizeof(*tf) <= 4096); madvise(0, (size_t) _end, MADV_WILLNEED); signal(SIGBUS, pf_handler); signal(SIGSEGV, pf_handler); for (uint32_t t = min; t <= max && t < ntests; t++) { if (check_commutativity) { run_test(tp, tf, &fstests[t], 0, false); int ra0 = tf[0].retval; int ra1 = tf[1].retval; run_test(tp, tf, &fstests[t], 1, false); int rb0 = tf[0].retval; int rb1 = tf[1].retval; if (ra0 == rb0 && ra1 == rb1) { if (verbose) printf("%s: commutes: %s->%d %s->%d\n", fstests[t].testname, fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1); } else { printf("%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\n", fstests[t].testname, fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1, fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0); } } if (run_threads) { run_test(tp, tf, &fstests[t], 0, true); printf("%s: threads done\n", fstests[t].testname); } } } <|endoftext|>
<commit_before>/** * Copyright 2016, Quickstep Research Group, Computer Sciences Department, * University of Wisconsin—Madison. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_ #define QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_ #include <tuple> #include <utility> namespace quickstep { /** \addtogroup Utility * @{ */ /** * @brief Represents a compile-time sequence of integers. * * Seq is defined here for C++11 compatibility. For C++14 and above, * std::integer_sequence can be used to achieve the same functionality. */ template<std::size_t ...> struct Seq {}; /** * @brief The helper class for creating Seq. GenSeq<N>::type is equivalent to * Seq<1,2,...,N>. * * GenSeq is defined here for C++11 compatibility. For C++14 and above, * std::make_interger_sequence can be used to achieve the same functionality. */ template<std::size_t N, std::size_t ...S> struct GenSeq : GenSeq<N-1, N-1, S...> {}; template<std::size_t ...S> struct GenSeq<0, S...> { typedef Seq<S...> type; }; /** * @brief Final step of CreateBoolInstantiatedInstance. Now all bool_values are * ready. Instantiate the template and create (i.e. new) an instance. */ template <template <bool ...> class T, class ReturnT, bool ...bool_values, std::size_t ...i, typename Tuple> inline ReturnT* CreateBoolInstantiatedInstanceInner(Tuple&& args, Seq<i...>&& indices) { return new T<bool_values...>(std::get<i>(std::forward<Tuple>(args))...); } /** * @brief Edge case of the recursive CreateBoolInstantiatedInstance function * when all bool variables have been branched and replaced with compile-time * bool constants. */ template <template <bool ...> class T, class ReturnT, bool ...bool_values, typename Tuple> inline ReturnT* CreateBoolInstantiatedInstance(Tuple&& args) { // Note that the constructor arguments have been forwarded as a tuple (args). // Here we generate a compile-time index sequence (i.e. typename GenSeq<n_args>::type()) // for the tuple, so that the tuple can be unpacked as a sequence of constructor // parameters in CreateBoolInstantiatedInstanceInner. constexpr std::size_t n_args = std::tuple_size<Tuple>::value; return CreateBoolInstantiatedInstanceInner<T, ReturnT, bool_values...>( std::forward<Tuple>(args), typename GenSeq<n_args>::type()); } /** * @brief A helper function for creating bool branched templates. * * The scenario for using this helper function is that, suppose we have a class * where all template parameters are bools: * -- * template <bool c1, bool c2, bool c3> * class SomeClass : BaseClass { * // This simple function will be invoked in computationally-intensive loops. * inline SomeType someSimpleFunction(...) { * if (c1) { * doSomeThing1(); * } * if (c2) { * doSomeThing2(); * } * if (c3) { * doSomeThing3(); * } * } * }; * -- * Typically, this bool-paramterized template is for performance consideration. * That is, we would like to make a copy of code for each configuration of bool * values, so that there will be no branchings in someSimpleFunction(). * * The problem is that, to conditionally instantiate the template, given bool * variables c1, c2, c3, we have to do something like this: * -- * if (c1) { * if (c2) { * if (c3) { * return new SomeClass<true, true, true>(some_args...); * } else { * return new SomeClass<true, true, false>(some_args...); * } * } else { * if (c3) { * return new SomeClass<true, false, true>(some_args...); * } else { * return new SomeClass<true, false, false>(some_args...); * } * } else { * ... * } * -- * Then there will be power(2,N) branches if the template has N bool parameters, * making it tedious to do the instantiating. * * Now, this helper function can achieve the branched instantiation in one * statement as: * -- * return CreateBoolInstantiatedInstance<SomeClass,BaseClass>( * std::forward_as_tuple(some_args...), c1, c2, c3); * -- */ template <template <bool ...> class T, class ReturnT, bool ...bool_values, typename ...Bools, typename Tuple> inline ReturnT* CreateBoolInstantiatedInstance(Tuple&& args, bool tparam, Bools ...rest_tparams) { if (tparam) { return CreateBoolInstantiatedInstance<T, ReturnT, bool_values..., true>( std::forward<Tuple>(args), rest_tparams...); } else { return CreateBoolInstantiatedInstance<T, ReturnT, bool_values..., false>( std::forward<Tuple>(args), rest_tparams...); } } /** @} */ } // namespace quickstep #endif // QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_ <commit_msg>Update TemplateUtil.hpp<commit_after>/** * Copyright 2016, Quickstep Research Group, Computer Sciences Department, * University of Wisconsin—Madison. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_ #define QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_ #include <tuple> #include <utility> namespace quickstep { /** \addtogroup Utility * @{ */ /** * @brief Represents a compile-time sequence of integers. * * Seq is defined here for C++11 compatibility. For C++14 and above, * std::integer_sequence can be used to achieve the same functionality. */ template<std::size_t ...> struct Seq {}; /** * @brief The helper class for creating Seq. GenSeq<N>::type is equivalent to * Seq<1,2,...,N>. * * GenSeq is defined here for C++11 compatibility. For C++14 and above, * std::make_integer_sequence can be used to achieve the same functionality. */ template<std::size_t N, std::size_t ...S> struct GenSeq : GenSeq<N-1, N-1, S...> {}; template<std::size_t ...S> struct GenSeq<0, S...> { typedef Seq<S...> type; }; /** * @brief Final step of CreateBoolInstantiatedInstance. Now all bool_values are * ready. Instantiate the template and create (i.e. new) an instance. */ template <template <bool ...> class T, class ReturnT, bool ...bool_values, std::size_t ...i, typename Tuple> inline ReturnT* CreateBoolInstantiatedInstanceInner(Tuple&& args, Seq<i...>&& indices) { return new T<bool_values...>(std::get<i>(std::forward<Tuple>(args))...); } /** * @brief Edge case of the recursive CreateBoolInstantiatedInstance function * when all bool variables have been branched and replaced with compile-time * bool constants. */ template <template <bool ...> class T, class ReturnT, bool ...bool_values, typename Tuple> inline ReturnT* CreateBoolInstantiatedInstance(Tuple&& args) { // Note that the constructor arguments have been forwarded as a tuple (args). // Here we generate a compile-time index sequence (i.e. typename GenSeq<n_args>::type()) // for the tuple, so that the tuple can be unpacked as a sequence of constructor // parameters in CreateBoolInstantiatedInstanceInner. constexpr std::size_t n_args = std::tuple_size<Tuple>::value; return CreateBoolInstantiatedInstanceInner<T, ReturnT, bool_values...>( std::forward<Tuple>(args), typename GenSeq<n_args>::type()); } /** * @brief A helper function for creating bool branched templates. * * The scenario for using this helper function is that, suppose we have a class * where all template parameters are bools: * -- * template <bool c1, bool c2, bool c3> * class SomeClass : BaseClass { * // This simple function will be invoked in computationally-intensive loops. * inline SomeType someSimpleFunction(...) { * if (c1) { * doSomeThing1(); * } * if (c2) { * doSomeThing2(); * } * if (c3) { * doSomeThing3(); * } * } * }; * -- * Typically, this bool-paramterized template is for performance consideration. * That is, we would like to make a copy of code for each configuration of bool * values, so that there will be no branchings in someSimpleFunction(). * * The problem is that, to conditionally instantiate the template, given bool * variables c1, c2, c3, we have to do something like this: * -- * if (c1) { * if (c2) { * if (c3) { * return new SomeClass<true, true, true>(some_args...); * } else { * return new SomeClass<true, true, false>(some_args...); * } * } else { * if (c3) { * return new SomeClass<true, false, true>(some_args...); * } else { * return new SomeClass<true, false, false>(some_args...); * } * } else { * ... * } * -- * Then there will be power(2,N) branches if the template has N bool parameters, * making it tedious to do the instantiating. * * Now, this helper function can achieve the branched instantiation in one * statement as: * -- * return CreateBoolInstantiatedInstance<SomeClass,BaseClass>( * std::forward_as_tuple(some_args...), c1, c2, c3); * -- */ template <template <bool ...> class T, class ReturnT, bool ...bool_values, typename ...Bools, typename Tuple> inline ReturnT* CreateBoolInstantiatedInstance(Tuple&& args, bool tparam, Bools ...rest_tparams) { if (tparam) { return CreateBoolInstantiatedInstance<T, ReturnT, bool_values..., true>( std::forward<Tuple>(args), rest_tparams...); } else { return CreateBoolInstantiatedInstance<T, ReturnT, bool_values..., false>( std::forward<Tuple>(args), rest_tparams...); } } /** @} */ } // namespace quickstep #endif // QUICKSTEP_UTILITY_TEMPLATE_UTIL_HPP_ <|endoftext|>
<commit_before>#include "editingcamera.h" #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/UI/UI.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Graphics/Drawable.h> #include <Urho3D/Graphics/OctreeQuery.h> #include <Urho3D/Graphics/Octree.h> #include <Urho3D/IO/Log.h> #include "../terraincontext.h" EditingCamera::EditingCamera(Context *context) : LogicComponent(context), pitch_(30), yaw_(180), follow_(10), minfollow_(0), maxfollow_(20), curfollow_(10), followvel_(0), zoomspeed_(1000.0f), offset_(2), clipdistance_(600), scrollspeed_(64.0f), allowpitch_(true), allowspin_(true), allowzoom_(true), clipsolid_(false), tracksurface_(true), anglenode_(nullptr), cameranode_(nullptr), terrainContext_(nullptr), camera_(nullptr) { SetUpdateEventMask(USE_UPDATE); } void EditingCamera::DelayedStart() { anglenode_ = node_->CreateChild("AngleNode"); cameranode_ = anglenode_->CreateChild("CameraNode"); camera_ = cameranode_->CreateComponent<Camera>(); viewport_ = new Viewport(context_, node_->GetScene(), camera_); GetSubsystem<Renderer>()->SetViewport(0, viewport_); node_->SetRotation(Quaternion(yaw_, Vector3(0,1,0))); cameranode_->SetPosition(Vector3(0,0,-follow_)); anglenode_->SetRotation(Quaternion(pitch_, Vector3(1,0,0))); node_->SetPosition(Vector3(0,0,0)); } Ray EditingCamera::GetScreenRay(const IntVector2 &mousepos) { auto graphics=GetSubsystem<Graphics>(); if(!camera_) return Ray(); return camera_->GetScreenRay((float)mousepos.x_ / (float)graphics->GetWidth(), (float)mousepos.y_/(float)graphics->GetHeight()); } Ray EditingCamera::GetMouseRay() { if(!camera_) return Ray(); auto input=GetSubsystem<Input>(); auto ui=GetSubsystem<UI>(); if(input->IsMouseVisible()) return GetScreenRay(input->GetMousePosition()); else return GetScreenRay(ui->GetCursor()->GetPosition()); } bool EditingCamera::GetScreenGround(Vector3 &out, const IntVector2 &mousepos) { if(!camera_) return false; Ray ray=GetScreenRay(mousepos); float hitdist=ray.HitDistance(Plane(Vector3(0,1,0), Vector3(0,0,0))); if(hitdist==M_INFINITY) return false; out=ray.origin_ + ray.direction_*hitdist; return true; } bool EditingCamera::GetMouseGround(Vector3 &out) { if(!camera_) return false; auto input=GetSubsystem<Input>(); auto ui=GetSubsystem<UI>(); if(input->IsMouseVisible()) return GetScreenGround(out, input->GetMousePosition()); else return GetScreenGround(out, ui->GetCursorPosition()); } bool EditingCamera::PickGround(Vector3 &ground, const IntVector2 &mousepos, float maxdistance) { auto ui=GetSubsystem<UI>(); auto input=GetSubsystem<Input>(); Scene *scene=node_->GetScene(); Octree *octree=node_->GetScene()->GetComponent<Octree>(); float hitpos=0; Drawable *hitdrawable=nullptr; //if(ui->GetCursor() && ui->GetCursor()->IsVisible()==false && input->IsMouseVisible()==false) return false; Ray ray=GetScreenRay(mousepos); static ea::vector<RayQueryResult> result; result.clear(); RayOctreeQuery query(result, ray, RAY_TRIANGLE, maxdistance, DRAWABLE_GEOMETRY); octree->Raycast(query); if(result.size()==0) return false; for(unsigned int i=0; i<result.size(); ++i) { if(result[i].distance_>=0) { ground=ray.origin_+ray.direction_*result[i].distance_; return true; } } return false; } void EditingCamera::Update(float dt) { if(!camera_) return; auto ui=GetSubsystem<UI>(); auto input=GetSubsystem<Input>(); auto graphics=GetSubsystem<Graphics>(); IntVector2 mousepos; if(ui->GetCursor()) mousepos=ui->GetCursor()->GetPosition(); else mousepos=input->GetMousePosition(); if(allowzoom_ && !ui->GetElementAt(mousepos)) { float wheel=input->GetMouseMoveWheel(); follow_=follow_-wheel*dt*zoomspeed_; follow_=std::max(minfollow_, std::min(maxfollow_, follow_)); } if(input->GetMouseButtonDown(MOUSEB_MIDDLE) && (allowspin_ || allowpitch_)) { if(ui->GetCursor()) ui->GetCursor()->SetVisible(false); else input->SetMouseVisible(false); if(allowpitch_) { float mmovey=(float)input->GetMouseMoveY() / (float)graphics->GetHeight(); pitch_+=mmovey*600.0f; pitch_=std::max(-89.0f, std::min(89.0f, pitch_)); } if(allowspin_) { float mmovex=(float)input->GetMouseMoveX() / (float)graphics->GetWidth(); yaw_+=mmovex*800.0f; while(yaw_<0.0f) yaw_+=360.0f; while(yaw_>=360.0f) yaw_-=360.0f; } } else { if(ui->GetCursor()) ui->GetCursor()->SetVisible(true); else input->SetMouseVisible(true); } Vector3 trans(0,0,0); if(input->GetMouseButtonPress(MOUSEB_RIGHT)) { lastmouse_=mousepos; } if(input->GetMouseButtonDown(MOUSEB_RIGHT)) { trans=Vector3(0,0,0); Vector3 oldground; bool s=GetScreenGround(oldground, lastmouse_); if(s) { Vector3 newground; bool t=GetScreenGround(newground, mousepos); if(t) { trans=oldground-newground; lastmouse_=mousepos; } } } else { Quaternion quat(yaw_,Vector3(0,1,0)); if(input->GetKeyDown(KEY_W)) trans.z_+=1.0f; if(input->GetKeyDown(KEY_S)) trans.z_-=1.0f; if(input->GetKeyDown(KEY_A)) trans.x_-=1.0f; if(input->GetKeyDown(KEY_D)) trans.x_+=1.0f; trans=quat*trans*dt*scrollspeed_; } Vector3 mypos=node_->GetPosition(); Vector3 np=mypos+trans; np.x_=std::max(minbounds_.x_, std::min(maxbounds_.x_, np.x_)); np.z_=std::max(minbounds_.y_, std::min(maxbounds_.y_, np.z_)); if(tracksurface_ && terrainContext_) { float ht=terrainContext_->GetHeight(np); np.y_=ht+offset_; } node_->SetPosition(np); SpringFollow(dt); if(clipsolid_) { Ray ray=camera_->GetScreenRay(0.5f, 0.5f); Ray revray=Ray(node_->GetPosition(), ray.direction_*Vector3(-1,-1,-1)); curfollow_=CameraClipPick(revray, curfollow_); } node_->SetRotation(Quaternion(yaw_, Vector3(0,1,0))); cameranode_->SetPosition(Vector3(0,0,-curfollow_)); anglenode_->SetRotation(Quaternion(pitch_, Vector3(1,0,0))); camera_->SetFarClip(clipdistance_); } float EditingCamera::CameraClipPick(const Ray &ray, float followdist) { Scene *scene=node_->GetScene(); Octree *octree=scene->GetComponent<Octree>(); static ea::vector<RayQueryResult> result; result.clear(); RayOctreeQuery query(result, ray, RAY_TRIANGLE, followdist, DRAWABLE_GEOMETRY); octree->Raycast(query); if(result.size()==0) return followdist; for(unsigned int i=0; i<result.size(); ++i) { Node *n=TopLevelNodeFromDrawable(result[i].drawable_, scene); return std::min(result[i].distance_-0.0f, followdist); } return followdist; } void EditingCamera::SpringFollow(float dt) { float df=follow_-curfollow_; float af=9.0f*df-6.0f*followvel_; followvel_+=dt*af; curfollow_+=dt*followvel_; } void EditingCamera::SetGroundHeight(float e) { Vector3 pos=node_->GetPosition(); pos.y_=e+offset_; node_->SetPosition(pos); } Node *EditingCamera::TopLevelNodeFromDrawable(Drawable *d, Scene *s) { Node *n=d->GetNode(); if(!n) return nullptr; while(n->GetParent() != s) { if(n->GetParent()==nullptr) return n; n=n->GetParent(); } return n; } <commit_msg>Raise camera offset from ground a bit.<commit_after>#include "editingcamera.h" #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/UI/UI.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Graphics/Drawable.h> #include <Urho3D/Graphics/OctreeQuery.h> #include <Urho3D/Graphics/Octree.h> #include <Urho3D/IO/Log.h> #include "../terraincontext.h" EditingCamera::EditingCamera(Context *context) : LogicComponent(context), pitch_(30), yaw_(180), follow_(10), minfollow_(0), maxfollow_(20), curfollow_(10), followvel_(0), zoomspeed_(1000.0f), offset_(6.0f), clipdistance_(600), scrollspeed_(64.0f), allowpitch_(true), allowspin_(true), allowzoom_(true), clipsolid_(false), tracksurface_(true), anglenode_(nullptr), cameranode_(nullptr), terrainContext_(nullptr), camera_(nullptr) { SetUpdateEventMask(USE_UPDATE); } void EditingCamera::DelayedStart() { anglenode_ = node_->CreateChild("AngleNode"); cameranode_ = anglenode_->CreateChild("CameraNode"); camera_ = cameranode_->CreateComponent<Camera>(); viewport_ = new Viewport(context_, node_->GetScene(), camera_); GetSubsystem<Renderer>()->SetViewport(0, viewport_); node_->SetRotation(Quaternion(yaw_, Vector3(0,1,0))); cameranode_->SetPosition(Vector3(0,0,-follow_)); anglenode_->SetRotation(Quaternion(pitch_, Vector3(1,0,0))); node_->SetPosition(Vector3(0,0,0)); } Ray EditingCamera::GetScreenRay(const IntVector2 &mousepos) { auto graphics=GetSubsystem<Graphics>(); if(!camera_) return Ray(); return camera_->GetScreenRay((float)mousepos.x_ / (float)graphics->GetWidth(), (float)mousepos.y_/(float)graphics->GetHeight()); } Ray EditingCamera::GetMouseRay() { if(!camera_) return Ray(); auto input=GetSubsystem<Input>(); auto ui=GetSubsystem<UI>(); if(input->IsMouseVisible()) return GetScreenRay(input->GetMousePosition()); else return GetScreenRay(ui->GetCursor()->GetPosition()); } bool EditingCamera::GetScreenGround(Vector3 &out, const IntVector2 &mousepos) { if(!camera_) return false; Ray ray=GetScreenRay(mousepos); float hitdist=ray.HitDistance(Plane(Vector3(0,1,0), Vector3(0,0,0))); if(hitdist==M_INFINITY) return false; out=ray.origin_ + ray.direction_*hitdist; return true; } bool EditingCamera::GetMouseGround(Vector3 &out) { if(!camera_) return false; auto input=GetSubsystem<Input>(); auto ui=GetSubsystem<UI>(); if(input->IsMouseVisible()) return GetScreenGround(out, input->GetMousePosition()); else return GetScreenGround(out, ui->GetCursorPosition()); } bool EditingCamera::PickGround(Vector3 &ground, const IntVector2 &mousepos, float maxdistance) { auto ui=GetSubsystem<UI>(); auto input=GetSubsystem<Input>(); Scene *scene=node_->GetScene(); Octree *octree=node_->GetScene()->GetComponent<Octree>(); float hitpos=0; Drawable *hitdrawable=nullptr; //if(ui->GetCursor() && ui->GetCursor()->IsVisible()==false && input->IsMouseVisible()==false) return false; Ray ray=GetScreenRay(mousepos); static ea::vector<RayQueryResult> result; result.clear(); RayOctreeQuery query(result, ray, RAY_TRIANGLE, maxdistance, DRAWABLE_GEOMETRY); octree->Raycast(query); if(result.size()==0) return false; for(unsigned int i=0; i<result.size(); ++i) { if(result[i].distance_>=0) { ground=ray.origin_+ray.direction_*result[i].distance_; return true; } } return false; } void EditingCamera::Update(float dt) { if(!camera_) return; auto ui=GetSubsystem<UI>(); auto input=GetSubsystem<Input>(); auto graphics=GetSubsystem<Graphics>(); IntVector2 mousepos; if(ui->GetCursor()) mousepos=ui->GetCursor()->GetPosition(); else mousepos=input->GetMousePosition(); if(allowzoom_ && !ui->GetElementAt(mousepos)) { float wheel=input->GetMouseMoveWheel(); follow_=follow_-wheel*dt*zoomspeed_; follow_=std::max(minfollow_, std::min(maxfollow_, follow_)); } if(input->GetMouseButtonDown(MOUSEB_MIDDLE) && (allowspin_ || allowpitch_)) { if(ui->GetCursor()) ui->GetCursor()->SetVisible(false); else input->SetMouseVisible(false); if(allowpitch_) { float mmovey=(float)input->GetMouseMoveY() / (float)graphics->GetHeight(); pitch_+=mmovey*600.0f; pitch_=std::max(-89.0f, std::min(89.0f, pitch_)); } if(allowspin_) { float mmovex=(float)input->GetMouseMoveX() / (float)graphics->GetWidth(); yaw_+=mmovex*800.0f; while(yaw_<0.0f) yaw_+=360.0f; while(yaw_>=360.0f) yaw_-=360.0f; } } else { if(ui->GetCursor()) ui->GetCursor()->SetVisible(true); else input->SetMouseVisible(true); } Vector3 trans(0,0,0); if(input->GetMouseButtonPress(MOUSEB_RIGHT)) { lastmouse_=mousepos; } if(input->GetMouseButtonDown(MOUSEB_RIGHT)) { trans=Vector3(0,0,0); Vector3 oldground; bool s=GetScreenGround(oldground, lastmouse_); if(s) { Vector3 newground; bool t=GetScreenGround(newground, mousepos); if(t) { trans=oldground-newground; lastmouse_=mousepos; } } } else { Quaternion quat(yaw_,Vector3(0,1,0)); if(input->GetKeyDown(KEY_W)) trans.z_+=1.0f; if(input->GetKeyDown(KEY_S)) trans.z_-=1.0f; if(input->GetKeyDown(KEY_A)) trans.x_-=1.0f; if(input->GetKeyDown(KEY_D)) trans.x_+=1.0f; trans=quat*trans*dt*scrollspeed_; } Vector3 mypos=node_->GetPosition(); Vector3 np=mypos+trans; np.x_=std::max(minbounds_.x_, std::min(maxbounds_.x_, np.x_)); np.z_=std::max(minbounds_.y_, std::min(maxbounds_.y_, np.z_)); if(tracksurface_ && terrainContext_) { float ht=terrainContext_->GetHeight(np); np.y_=ht+offset_; } node_->SetPosition(np); SpringFollow(dt); if(clipsolid_) { Ray ray=camera_->GetScreenRay(0.5f, 0.5f); Ray revray=Ray(node_->GetPosition(), ray.direction_*Vector3(-1,-1,-1)); curfollow_=CameraClipPick(revray, curfollow_); } node_->SetRotation(Quaternion(yaw_, Vector3(0,1,0))); cameranode_->SetPosition(Vector3(0,0,-curfollow_)); anglenode_->SetRotation(Quaternion(pitch_, Vector3(1,0,0))); camera_->SetFarClip(clipdistance_); } float EditingCamera::CameraClipPick(const Ray &ray, float followdist) { Scene *scene=node_->GetScene(); Octree *octree=scene->GetComponent<Octree>(); static ea::vector<RayQueryResult> result; result.clear(); RayOctreeQuery query(result, ray, RAY_TRIANGLE, followdist, DRAWABLE_GEOMETRY); octree->Raycast(query); if(result.size()==0) return followdist; for(unsigned int i=0; i<result.size(); ++i) { Node *n=TopLevelNodeFromDrawable(result[i].drawable_, scene); return std::min(result[i].distance_-0.0f, followdist); } return followdist; } void EditingCamera::SpringFollow(float dt) { float df=follow_-curfollow_; float af=9.0f*df-6.0f*followvel_; followvel_+=dt*af; curfollow_+=dt*followvel_; } void EditingCamera::SetGroundHeight(float e) { Vector3 pos=node_->GetPosition(); pos.y_=e+offset_; node_->SetPosition(pos); } Node *EditingCamera::TopLevelNodeFromDrawable(Drawable *d, Scene *s) { Node *n=d->GetNode(); if(!n) return nullptr; while(n->GetParent() != s) { if(n->GetParent()==nullptr) return n; n=n->GetParent(); } return n; } <|endoftext|>
<commit_before>629547d1-2e4f-11e5-a7c5-28cfe91dbc4b<commit_msg>629e1e40-2e4f-11e5-a864-28cfe91dbc4b<commit_after>629e1e40-2e4f-11e5-a864-28cfe91dbc4b<|endoftext|>
<commit_before>// Requires Adafruit_ASFcore library! // Be careful to use a platform-specific conditional include to only make the // code visible for the appropriate platform. Arduino will try to compile and // link all .cpp files regardless of platform. #if defined(ARDUINO_ARCH_SAMD) #include <sam.h> #include "WatchdogSAMD.h" int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { // Enable the watchdog with a period up to the specified max period in // milliseconds. // Review the watchdog section from the SAMD21 datasheet section 17: // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf int cycles; uint8_t bits; if(!_initialized) _initialize_wdt(); #if defined(__SAMD51__) WDT->CTRLA.reg = 0; // Disable watchdog for config while(WDT->SYNCBUSY.reg); #else WDT->CTRL.reg = 0; // Disable watchdog for config while(WDT->STATUS.bit.SYNCBUSY); #endif // You'll see some occasional conversion here compensating between // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- // power oscillator used by the WDT ostensibly runs at 32,768 Hz with // a 1:32 prescale, thus 1024 Hz, though probably not super precise. if((maxPeriodMS >= 16000) || !maxPeriodMS) { cycles = 16384; bits = 0xB; } else { cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles if(cycles >= 8192) { cycles = 8192; bits = 0xA; } else if(cycles >= 4096) { cycles = 4096; bits = 0x9; } else if(cycles >= 2048) { cycles = 2048; bits = 0x8; } else if(cycles >= 1024) { cycles = 1024; bits = 0x7; } else if(cycles >= 512) { cycles = 512; bits = 0x6; } else if(cycles >= 256) { cycles = 256; bits = 0x5; } else if(cycles >= 128) { cycles = 128; bits = 0x4; } else if(cycles >= 64) { cycles = 64; bits = 0x3; } else if(cycles >= 32) { cycles = 32; bits = 0x2; } else if(cycles >= 16) { cycles = 16; bits = 0x1; } else { cycles = 8; bits = 0x0; } } // Watchdog timer on SAMD is a slightly different animal than on AVR. // On AVR, the WTD timeout is configured in one register and then an // interrupt can optionally be enabled to handle the timeout in code // (as in waking from sleep) vs resetting the chip. Easy. // On SAMD, when the WDT fires, that's it, the chip's getting reset. // Instead, it has an "early warning interrupt" with a different set // interval prior to the reset. For equivalent behavior to the AVR // library, this requires a slightly different configuration depending // whether we're coming from the sleep() function (which needs the // interrupt), or just enable() (no interrupt, we want the chip reset // unless the WDT is cleared first). In the sleep case, 'windowed' // mode is used in order to allow access to the longest available // sleep interval (about 16 sec); the WDT 'period' (when a reset // occurs) follows this and is always just set to the max, since the // interrupt will trigger first. In the enable case, windowed mode // is not used, the WDT period is set and that's that. // The 'isForSleep' argument determines which behavior is used; // this isn't present in the AVR code, just here. It defaults to // 'false' so existing Arduino code works as normal, while the sleep() // function (later in this file) explicitly passes 'true' to get the // alternate behavior. #if defined(__SAMD51__) if(isForSleep) { WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->EWCTRL.bit.EWOFFSET = 0x0; // Early warning offset WDT->CTRLA.bit.WEN = 1; // Enable window mode while(WDT->SYNCBUSY.reg); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRLA.bit.WEN = 0; // Disable window mode while(WDT->SYNCBUSY.reg); // Sync CTRL write } reset(); // Clear watchdog interval WDT->CTRLA.bit.ENABLE = 1; // Start watchdog now! while(WDT->SYNCBUSY.reg); #else if(isForSleep) { WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->CTRL.bit.WEN = 1; // Enable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRL.bit.WEN = 0; // Disable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } reset(); // Clear watchdog interval WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! while(WDT->STATUS.bit.SYNCBUSY); #endif return (cycles * 1000L + 512) / 1024; // WDT cycles -> ms } void WatchdogSAMD::reset() { // Write the watchdog clear key value (0xA5) to the watchdog // clear register to clear the watchdog timer and reset it. #if defined(__SAMD51__) while(WDT->SYNCBUSY.reg); #else while(WDT->STATUS.bit.SYNCBUSY); #endif WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; } uint8_t WatchdogSAMD::resetCause() { return RSTC->RCAUSE.reg; } void WatchdogSAMD::disable() { #if defined(__SAMD51__) WDT->CTRLA.bit.ENABLE = 0; while(WDT->SYNCBUSY.reg); #else WDT->CTRL.bit.ENABLE = 0; while(WDT->STATUS.bit.SYNCBUSY); #endif } void WDT_Handler(void) { // ISR for watchdog early warning, DO NOT RENAME! #if defined(__SAMD51__) WDT->CTRLA.bit.ENABLE = 0; // Disable watchdog while(WDT->SYNCBUSY.reg); #else WDT->CTRL.bit.ENABLE = 0; // Disable watchdog while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write #endif WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag } int WatchdogSAMD::sleep(int maxPeriodMS) { int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep // Enable standby sleep mode (deepest sleep) and activate. // Insights from Atmel ASF library. #if (SAMD20 || SAMD21) // Don't fully power down flash when in sleep NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; #endif #if defined(__SAMD51__) PM->SLEEPCFG.bit.SLEEPMODE = 0x4; // Standby sleep mode while(PM->SLEEPCFG.bit.SLEEPMODE != 0x4); // Wait for it to take #else SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; #endif __DSB(); // Data sync to ensure outgoing memory accesses complete __WFI(); // Wait for interrupt (places device in sleep mode) // Code resumes here on wake (WDT early warning interrupt). // Bug: the return value assumes the WDT has run its course; // incorrect if the device woke due to an external interrupt. // Without an external RTC there's no way to provide a correct // sleep period in the latter case...but at the very least, // might indicate said condition occurred by returning 0 instead // (assuming we can pin down which interrupt caused the wake). return actualPeriodMS; } void WatchdogSAMD::_initialize_wdt() { // One-time initialization of watchdog timer. // Insights from rickrlh and rbrucemtl in Arduino forum! #if defined(__SAMD51__) // SAMD51 WDT uses OSCULP32k as input clock now // section: 20.5.3 OSC32KCTRL->OSCULP32K.bit.EN1K = 1; // Enable out 1K (for WDT) OSC32KCTRL->OSCULP32K.bit.EN32K = 0; // Disable out 32K // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); while(WDT->SYNCBUSY.reg); USB->DEVICE.CTRLA.bit.ENABLE = 0; // Disable the USB peripheral while(USB->DEVICE.SYNCBUSY.bit.ENABLE); // Wait for synchronization USB->DEVICE.CTRLA.bit.RUNSTDBY = 0; // Deactivate run on standby USB->DEVICE.CTRLA.bit.ENABLE = 1; // Enable the USB peripheral while(USB->DEVICE.SYNCBUSY.bit.ENABLE); // Wait for synchronization #else // Generic clock generator 2, divisor = 32 (2^(DIV+1)) GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); // Enable clock generator 2 using low-power 32KHz oscillator. // With /32 divisor above, this yields 1024Hz(ish) clock. GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_DIVSEL; while(GCLK->STATUS.bit.SYNCBUSY); // WDT clock = clock gen 2 GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK2; // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); #endif _initialized = true; } #endif // defined(ARDUINO_ARCH_SAMD) <commit_msg>fix samd21<commit_after>// Requires Adafruit_ASFcore library! // Be careful to use a platform-specific conditional include to only make the // code visible for the appropriate platform. Arduino will try to compile and // link all .cpp files regardless of platform. #if defined(ARDUINO_ARCH_SAMD) #include <sam.h> #include "WatchdogSAMD.h" int WatchdogSAMD::enable(int maxPeriodMS, bool isForSleep) { // Enable the watchdog with a period up to the specified max period in // milliseconds. // Review the watchdog section from the SAMD21 datasheet section 17: // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf int cycles; uint8_t bits; if(!_initialized) _initialize_wdt(); #if defined(__SAMD51__) WDT->CTRLA.reg = 0; // Disable watchdog for config while(WDT->SYNCBUSY.reg); #else WDT->CTRL.reg = 0; // Disable watchdog for config while(WDT->STATUS.bit.SYNCBUSY); #endif // You'll see some occasional conversion here compensating between // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- // power oscillator used by the WDT ostensibly runs at 32,768 Hz with // a 1:32 prescale, thus 1024 Hz, though probably not super precise. if((maxPeriodMS >= 16000) || !maxPeriodMS) { cycles = 16384; bits = 0xB; } else { cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles if(cycles >= 8192) { cycles = 8192; bits = 0xA; } else if(cycles >= 4096) { cycles = 4096; bits = 0x9; } else if(cycles >= 2048) { cycles = 2048; bits = 0x8; } else if(cycles >= 1024) { cycles = 1024; bits = 0x7; } else if(cycles >= 512) { cycles = 512; bits = 0x6; } else if(cycles >= 256) { cycles = 256; bits = 0x5; } else if(cycles >= 128) { cycles = 128; bits = 0x4; } else if(cycles >= 64) { cycles = 64; bits = 0x3; } else if(cycles >= 32) { cycles = 32; bits = 0x2; } else if(cycles >= 16) { cycles = 16; bits = 0x1; } else { cycles = 8; bits = 0x0; } } // Watchdog timer on SAMD is a slightly different animal than on AVR. // On AVR, the WTD timeout is configured in one register and then an // interrupt can optionally be enabled to handle the timeout in code // (as in waking from sleep) vs resetting the chip. Easy. // On SAMD, when the WDT fires, that's it, the chip's getting reset. // Instead, it has an "early warning interrupt" with a different set // interval prior to the reset. For equivalent behavior to the AVR // library, this requires a slightly different configuration depending // whether we're coming from the sleep() function (which needs the // interrupt), or just enable() (no interrupt, we want the chip reset // unless the WDT is cleared first). In the sleep case, 'windowed' // mode is used in order to allow access to the longest available // sleep interval (about 16 sec); the WDT 'period' (when a reset // occurs) follows this and is always just set to the max, since the // interrupt will trigger first. In the enable case, windowed mode // is not used, the WDT period is set and that's that. // The 'isForSleep' argument determines which behavior is used; // this isn't present in the AVR code, just here. It defaults to // 'false' so existing Arduino code works as normal, while the sleep() // function (later in this file) explicitly passes 'true' to get the // alternate behavior. #if defined(__SAMD51__) if(isForSleep) { WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->EWCTRL.bit.EWOFFSET = 0x0; // Early warning offset WDT->CTRLA.bit.WEN = 1; // Enable window mode while(WDT->SYNCBUSY.reg); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRLA.bit.WEN = 0; // Disable window mode while(WDT->SYNCBUSY.reg); // Sync CTRL write } reset(); // Clear watchdog interval WDT->CTRLA.bit.ENABLE = 1; // Start watchdog now! while(WDT->SYNCBUSY.reg); #else if(isForSleep) { WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->CTRL.bit.WEN = 1; // Enable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRL.bit.WEN = 0; // Disable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } reset(); // Clear watchdog interval WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! while(WDT->STATUS.bit.SYNCBUSY); #endif return (cycles * 1000L + 512) / 1024; // WDT cycles -> ms } void WatchdogSAMD::reset() { // Write the watchdog clear key value (0xA5) to the watchdog // clear register to clear the watchdog timer and reset it. #if defined(__SAMD51__) while(WDT->SYNCBUSY.reg); #else while(WDT->STATUS.bit.SYNCBUSY); #endif WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; } uint8_t WatchdogSAMD::resetCause() { #if defined(__SAMD51__) return RSTC->RCAUSE.reg; #else return PM->RCAUSE.reg; #endif } void WatchdogSAMD::disable() { #if defined(__SAMD51__) WDT->CTRLA.bit.ENABLE = 0; while(WDT->SYNCBUSY.reg); #else WDT->CTRL.bit.ENABLE = 0; while(WDT->STATUS.bit.SYNCBUSY); #endif } void WDT_Handler(void) { // ISR for watchdog early warning, DO NOT RENAME! #if defined(__SAMD51__) WDT->CTRLA.bit.ENABLE = 0; // Disable watchdog while(WDT->SYNCBUSY.reg); #else WDT->CTRL.bit.ENABLE = 0; // Disable watchdog while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write #endif WDT->INTFLAG.bit.EW = 1; // Clear interrupt flag } int WatchdogSAMD::sleep(int maxPeriodMS) { int actualPeriodMS = enable(maxPeriodMS, true); // true = for sleep // Enable standby sleep mode (deepest sleep) and activate. // Insights from Atmel ASF library. #if (SAMD20 || SAMD21) // Don't fully power down flash when in sleep NVMCTRL->CTRLB.bit.SLEEPPRM = NVMCTRL_CTRLB_SLEEPPRM_DISABLED_Val; #endif #if defined(__SAMD51__) PM->SLEEPCFG.bit.SLEEPMODE = 0x4; // Standby sleep mode while(PM->SLEEPCFG.bit.SLEEPMODE != 0x4); // Wait for it to take #else SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; #endif __DSB(); // Data sync to ensure outgoing memory accesses complete __WFI(); // Wait for interrupt (places device in sleep mode) // Code resumes here on wake (WDT early warning interrupt). // Bug: the return value assumes the WDT has run its course; // incorrect if the device woke due to an external interrupt. // Without an external RTC there's no way to provide a correct // sleep period in the latter case...but at the very least, // might indicate said condition occurred by returning 0 instead // (assuming we can pin down which interrupt caused the wake). return actualPeriodMS; } void WatchdogSAMD::_initialize_wdt() { // One-time initialization of watchdog timer. // Insights from rickrlh and rbrucemtl in Arduino forum! #if defined(__SAMD51__) // SAMD51 WDT uses OSCULP32k as input clock now // section: 20.5.3 OSC32KCTRL->OSCULP32K.bit.EN1K = 1; // Enable out 1K (for WDT) OSC32KCTRL->OSCULP32K.bit.EN32K = 0; // Disable out 32K // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); while(WDT->SYNCBUSY.reg); USB->DEVICE.CTRLA.bit.ENABLE = 0; // Disable the USB peripheral while(USB->DEVICE.SYNCBUSY.bit.ENABLE); // Wait for synchronization USB->DEVICE.CTRLA.bit.RUNSTDBY = 0; // Deactivate run on standby USB->DEVICE.CTRLA.bit.ENABLE = 1; // Enable the USB peripheral while(USB->DEVICE.SYNCBUSY.bit.ENABLE); // Wait for synchronization #else // Generic clock generator 2, divisor = 32 (2^(DIV+1)) GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); // Enable clock generator 2 using low-power 32KHz oscillator. // With /32 divisor above, this yields 1024Hz(ish) clock. GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_DIVSEL; while(GCLK->STATUS.bit.SYNCBUSY); // WDT clock = clock gen 2 GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK2; // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); #endif _initialized = true; } #endif // defined(ARDUINO_ARCH_SAMD) <|endoftext|>
<commit_before> #include <atomic> #include <thread> #include <iostream> #include <algorithm> #include <iomanip> #include <cstring> #include <mutex> #include <condition_variable> #include <chrono> #include "stress_instance.h" static constexpr std::size_t max_threads = 256; typedef std::chrono::system_clock Clock; typedef std::chrono::time_point<Clock> TimePoint; typedef std::chrono::duration<double> Duration; static void error(char const* message, int exitcode = 2) { std::cerr << message << std::endl; exit(exitcode); } static int run_stress(int cpucount, int timeLimit) { // Sidestep all the issues with copying // and ensure flat memory layout std::unique_ptr<stress_instance[]> instances(new stress_instance[cpucount]); stress_instance* begin = &instances[0]; stress_instance* end = &instances[cpucount]; std::for_each(begin, end, [](stress_instance& instance) { instance.run(); }); // Use a condition variable wait for delays // It looks more like we are doing work than // it would if we were calling sleep_for std::mutex dummyMutex; std::condition_variable dummyConditionVariable; std::unique_lock<std::mutex> lock(dummyMutex); do { dummyConditionVariable.wait_until(lock, Clock::now() + Duration(1)); std::for_each(begin, end, [](stress_instance& instance) { std::cout << std::setw(5) << (instance.getCount() / 1000000) << "M "; }); std::cout << std::endl; // Only decrement it if it is positive timeLimit -= (timeLimit > 0); } while (timeLimit != 0); } int main(int argc, char** argv) { int threads = 0; bool force = false; int timeLimit = -1; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-t")) { if (i + 1 >= argc) error("Missing argument to thread count option (-t)"); threads = atoi(argv[++i]); } else if (!strcmp(argv[i], "-i")) { if (i + 1 >= argc) error("Missing argument to iteration count option (-i)"); timeLimit = atoi(argv[++i]); } else if (!strcmp(argv[i], "-f")) { force = true; } else { error((std::string("Invalid switch: ") + argv[i]).c_str()); } } std::size_t cpuCount = std::thread::hardware_concurrency(); if (threads <= 0) { std::cerr << "Using all " << cpuCount << " CPUs" << std::endl; threads = cpuCount; } if (threads > cpuCount) { if (force) { std::cerr << "Warning, forced to use more threads" " than CPUs, " << threads << " threads," " but only " << cpuCount << " CPUs detected!" << std::endl; } else { std::cerr << "Capping to " << cpuCount << ". Use -f to override." << std::endl; threads = cpuCount; } } if (threads > max_threads) { std::cerr << "Capping to " << max_threads << ". Use -f to override." << std::endl; threads = max_threads; } return run_stress(threads, timeLimit); } <commit_msg>Improved command line interface<commit_after> #include <atomic> #include <thread> #include <iostream> #include <algorithm> #include <iomanip> #include <cstring> #include <mutex> #include <condition_variable> #include <chrono> #include "stress_instance.h" // This is only to limit the number of threads to a sane number static constexpr std::size_t max_threads = 256; typedef std::chrono::system_clock Clock; typedef std::chrono::time_point<Clock> TimePoint; typedef std::chrono::duration<double> Duration; static void error(char const* message, int exitcode = 2) { std::cerr << message << std::endl; exit(exitcode); } static int run_stress(int cpucount, int timeLimit) { // Sidestep all the issues with copying // and ensure flat memory layout std::unique_ptr<stress_instance[]> instances(new stress_instance[cpucount]); stress_instance* begin = &instances[0]; stress_instance* end = &instances[cpucount]; std::for_each(begin, end, [](stress_instance& instance) { instance.run(); }); // Use a condition variable wait for delays // It looks more like we are doing work than // it would if we were calling sleep_for std::mutex dummyMutex; std::condition_variable dummyConditionVariable; std::unique_lock<std::mutex> lock(dummyMutex); do { dummyConditionVariable.wait_until(lock, Clock::now() + Duration(1)); std::for_each(begin, end, [](stress_instance& instance) { std::cout << std::setw(5) << (instance.getCount() / 1000000) << "M "; }); std::cout << std::endl; // Only decrement it if it is positive timeLimit -= (timeLimit > 0); } while (timeLimit != 0); } int main(int argc, char** argv) { int threads = 0; bool force = false; int timeLimit = -1; for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-t")) { if (i + 1 >= argc) error("Missing argument to thread count option (-t)"); threads = atoi(argv[++i]); } else if (!strcmp(argv[i], "-i")) { if (i + 1 >= argc) error("Missing argument to iteration count option (-i)"); timeLimit = atoi(argv[++i]); } else if (!strcmp(argv[i], "-f")) { force = true; } else if (!strcmp(argv[i], "--help")) { std::cerr << argv[0] << " [-t threads] [-f]" << std::endl << "threads is the number of CPUs to use. Default=0. 0=All" << std::endl << "Use -f to force it to use more than the number of CPUs" << std::endl; exit(1); } else { error((std::string("Invalid switch: ") + argv[i]).c_str()); } } std::size_t cpuCount = std::thread::hardware_concurrency(); if (threads <= 0) { std::cerr << "Using all " << cpuCount << " CPUs" << std::endl; threads = cpuCount; } if (threads > cpuCount) { if (force) { std::cerr << "Warning, forced to use more threads" " than CPUs, " << threads << " threads," " but only " << cpuCount << " CPUs detected!" << std::endl; } else { std::cerr << "Capping to " << cpuCount << ". Use -f to override." << std::endl; threads = cpuCount; } } if (threads > max_threads) { std::cerr << "Capping to " << max_threads << ". Recompile with higher max_threads." << std::endl; threads = max_threads; } return run_stress(threads, timeLimit); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2011 J-P Nurmi <jpnurmi@gmail.com> * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. */ #include <QtDeclarative> #include <IrcSession> #include <IrcCommand> #include <IrcMessage> #include <IrcPrefix> #include <Irc> class DeclarativeIrcPrefix : public QObject { Q_OBJECT public: explicit DeclarativeIrcPrefix(QObject* parent = 0) : QObject(parent) { } Q_INVOKABLE static QString name(const QString& prefix) { return IrcPrefix(prefix).name(); } Q_INVOKABLE static QString user(const QString& prefix) { return IrcPrefix(prefix).user(); } Q_INVOKABLE static QString host(const QString& prefix) { return IrcPrefix(prefix).host(); } }; QML_DECLARE_TYPE(Irc) QML_DECLARE_TYPE(IrcCommand) QML_DECLARE_TYPE(IrcMessage) QML_DECLARE_TYPE(IrcSession) QML_DECLARE_TYPE(DeclarativeIrcPrefix) class CommuniPlugin : public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void initializeEngine(QDeclarativeEngine* engine, const char* uri) { QDeclarativeExtensionPlugin::initializeEngine(engine, uri); } void registerTypes(const char *uri) { qmlRegisterType<IrcSession>(uri, 1, 0, "IrcSession"); qmlRegisterType<IrcCommand>(uri, 1, 0, "IrcCommand"); qmlRegisterUncreatableType<Irc>(uri, 1, 0, "Irc", ""); qmlRegisterUncreatableType<IrcMessage>(uri, 1, 0, "IrcMessage", ""); qmlRegisterUncreatableType<DeclarativeIrcPrefix>(uri, 1, 0, "IrcPrefix", ""); } }; #include "plugin.moc" Q_EXPORT_PLUGIN2(communiplugin, CommuniPlugin); <commit_msg>Updated the declarative plugin<commit_after>/* * Copyright (C) 2008-2011 J-P Nurmi <jpnurmi@gmail.com> * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. */ #include <QtDeclarative> #include <IrcSession> #include <IrcCommand> #include <IrcMessage> #include <IrcPrefix> #include <Irc> class DeclarativeIrcPrefix : public QObject { Q_OBJECT public: explicit DeclarativeIrcPrefix(QObject* parent = 0) : QObject(parent) { } Q_INVOKABLE static QString name(const IrcPrefix& prefix) { return prefix.name(); } Q_INVOKABLE static QString user(const IrcPrefix& prefix) { return prefix.user(); } Q_INVOKABLE static QString host(const IrcPrefix& prefix) { return prefix.host(); } }; QML_DECLARE_TYPE(Irc) QML_DECLARE_TYPE(IrcCommand) QML_DECLARE_TYPE(IrcMessage) QML_DECLARE_TYPE(IrcSession) QML_DECLARE_TYPE(DeclarativeIrcPrefix) class CommuniPlugin : public QDeclarativeExtensionPlugin { Q_OBJECT public: virtual void initializeEngine(QDeclarativeEngine* engine, const char* uri) { QDeclarativeExtensionPlugin::initializeEngine(engine, uri); QDeclarativeContext* context = engine->rootContext(); context->setContextProperty("IrcPrefix", new DeclarativeIrcPrefix(context)); } void registerTypes(const char *uri) { qmlRegisterType<IrcSession>(uri, 1, 0, "IrcSession"); qmlRegisterType<IrcCommand>(uri, 1, 0, "IrcCommand"); qmlRegisterUncreatableType<Irc>(uri, 1, 0, "Irc", ""); qmlRegisterUncreatableType<IrcMessage>(uri, 1, 0, "IrcMessage", ""); } }; #include "plugin.moc" Q_EXPORT_PLUGIN2(communiplugin, CommuniPlugin); <|endoftext|>
<commit_before>dc5ff614-2e4e-11e5-bef3-28cfe91dbc4b<commit_msg>dc67911c-2e4e-11e5-9b25-28cfe91dbc4b<commit_after>dc67911c-2e4e-11e5-9b25-28cfe91dbc4b<|endoftext|>
<commit_before>fbef6fe8-ad5a-11e7-b436-ac87a332f658<commit_msg>oh my, I hate roselyn<commit_after>fc85b657-ad5a-11e7-9b50-ac87a332f658<|endoftext|>
<commit_before>59e375e8-2e4f-11e5-b69c-28cfe91dbc4b<commit_msg>59ea4640-2e4f-11e5-a957-28cfe91dbc4b<commit_after>59ea4640-2e4f-11e5-a957-28cfe91dbc4b<|endoftext|>
<commit_before>13908a5c-2f67-11e5-b160-6c40088e03e4<commit_msg>139775da-2f67-11e5-a4f5-6c40088e03e4<commit_after>139775da-2f67-11e5-a4f5-6c40088e03e4<|endoftext|>
<commit_before>8b33258e-2d14-11e5-af21-0401358ea401<commit_msg>8b33258f-2d14-11e5-af21-0401358ea401<commit_after>8b33258f-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8e9fac24-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac25-2d14-11e5-af21-0401358ea401<commit_after>8e9fac25-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>27f8a8bd-2e4f-11e5-858b-28cfe91dbc4b<commit_msg>27ffacfd-2e4f-11e5-bcd4-28cfe91dbc4b<commit_after>27ffacfd-2e4f-11e5-bcd4-28cfe91dbc4b<|endoftext|>
<commit_before>6aed60ac-5216-11e5-9cba-6c40088e03e4<commit_msg>6af41034-5216-11e5-a745-6c40088e03e4<commit_after>6af41034-5216-11e5-a745-6c40088e03e4<|endoftext|>
<commit_before>#include <QWidget> #include <QString> #include <QFont> #include <QMainWindow> #include <QVBoxLayout> #include <QApplication> #include <QEvent> #include "textedit.h" // ### TODO ### // ### Should clear selection when something else selects something. // ### Line break. Could vastly simplify textlayout if not breaking lines. // ### saving to same file. Need something there. // ### could refactor chunks so that I only have one and split when I need. Not sure if it's worth it. Would // ### need chunkData(int from = 0, int size = -1). The current approach makes caching easier since I can now cache an entire chunk. // ### ensureCursorVisible(TextCursor) is not implemented // ### add a command line switch to randomly do stuff. Insert, move around etc n times to see if I can reproduce a crash. Allow input of seed // ### I still have some weird debris when scrolling in large documents // ### use tests from Qt. E.g. for QTextCursor // ### need to protect against undo with huge amounts of text in it. E.g. select all and delete. MsgBox asking? // ### maybe refactor updatePosition so it can handle the margins usecase that textcursor needs. // ### could keep undo/redo history in the textcursor and have an api on the cursor. // ### block state in SyntaxHighlighter doesn't remember between // ### highlights. In regular QText.* it does. Could store this info. // ### Shouldn't be that much. Maybe base it off of position in // ### document rather than line number since I don't know which line // ### we're on // ### TextCursor(const TextEdit *). Is this a good idea? // ### caching stuff is getting a little convoluted // ### what should TextDocument::read(documentSize + 1, 10) do? ASSERT? // ### should I allow to write in a formatted manner? currentTextFormat and all? Why not really. // ### consider using QTextBoundaryFinder for something // ### drag and drop // ### documentation // ### consider having extra textLayouts on each side of viewport for optimized scrolling. Could detect that condition // ### Undo section removal/adding. This is a mess class Highlighter : public SyntaxHighlighter { public: Highlighter(QWidget *parent) : SyntaxHighlighter(parent) { } void helper(int from, int size, bool blackForeground) { QTextCharFormat format; format.setBackground(blackForeground ? Qt::yellow : Qt::black); format.setForeground(blackForeground ? Qt::black : Qt::yellow); setFormat(from, size, format); // qDebug() << "setting format" << from << size << currentBlock().mid(from, size) << blackForeground; } virtual void highlightBlock(const QString &text) { enum { Space, LetterOrNumber, Other } state = Space; int last = 0; for (int i=0; i<text.size(); ++i) { if (text.at(i).isSpace()) { if (state != Space) helper(last, i - last, state == LetterOrNumber); state = Space; last = i; } else if (text.at(i).isLetterOrNumber() != (state == LetterOrNumber) || state == Space) { if (state != Space) { helper(last, i - last, state == LetterOrNumber); } state = (text.at(i).isLetterOrNumber() ? LetterOrNumber : Other); last = i; } } if (state != Space) { helper(last, text.size() - last, state == LetterOrNumber); } } }; bool add = false; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0) : QMainWindow(parent), doLineNumbers(false) { QString fileName = "main.cpp"; bool replay = false; bool readOnly = false; int chunkSize = -1; QTextCodec *codec = 0; const QStringList list = QApplication::arguments().mid(1); for (int i=0; i<list.size(); ++i) { const QString &arg = list.at(i); if (arg == "--replay") { replay = true; fileName.clear(); } else if (arg == "--add") { replay = true; add = true; fileName.clear(); } else if (arg == "--log") { fileName.clear(); appendTimer.start(10, this); readOnly = true; chunkSize = 1000; } else if (arg == "--readonly") { readOnly = true; } else if (arg == "--linenumbers") { doLineNumbers = true; } else if (arg.startsWith("--codec=")) { codec = QTextCodec::codecForName(arg.mid(8).toLatin1()); if (!codec) { qWarning("Can't load codec called '%s'", qPrintable(arg.mid(8))); exit(1); } } else if (arg.startsWith("--chunksize=")) { bool ok; chunkSize = arg.mid(12).toInt(&ok); if (!ok) { qWarning("Can't parse %s", qPrintable(arg)); exit(1); } } else { fileName = arg; } } if (fileName.isEmpty() && !appendTimer.isActive()) { Q_ASSERT(replay); QStringList list = QDir(".").entryList(QStringList() << "*.log"); if (list.isEmpty()) { qWarning("Nothing to replay"); exit(1); } qSort(list); fileName = list.last(); } if (replay) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { qWarning("Can't open '%s' for reading", qPrintable(fileName)); exit(1); } #ifndef QT_NO_DEBUG_STREAM qDebug() << "replaying" << fileName; #endif #ifndef QT_NO_DEBUG if (add) { extern QString logFileName; logFileName = fileName; } extern bool doLog; // from textedit.cpp doLog = false; #endif QDataStream ds(&file); ds >> fileName; // reuse this variable for loading document. First QString in log file while (!file.atEnd()) { int type; ds >> type; if (type == QEvent::KeyPress || type == QEvent::KeyRelease) { int key; int modifiers; QString text; bool isAutoRepeat; int count; ds >> key; ds >> modifiers; ds >> text; ds >> isAutoRepeat; ds >> count; events.append(new QKeyEvent(static_cast<QEvent::Type>(type), key, static_cast<Qt::KeyboardModifiers>(modifiers), text, isAutoRepeat, count)); } else if (type == QEvent::Resize) { QSize size; ds >> size; events.append(new QResizeEvent(size, QSize())); } else { Q_ASSERT(type == QEvent::MouseMove || type == QEvent::MouseButtonPress || type == QEvent::MouseButtonRelease); QPoint pos; int button; int buttons; int modifiers; ds >> pos; ds >> button; ds >> buttons; ds >> modifiers; events.append(new QMouseEvent(static_cast<QEvent::Type>(type), pos, static_cast<Qt::MouseButton>(button), static_cast<Qt::MouseButtons>(buttons), static_cast<Qt::KeyboardModifiers>(modifiers))); } } if (!events.isEmpty()) QTimer::singleShot(0, this, SLOT(sendNextEvent())); } QWidget *w = new QWidget(this); QVBoxLayout *l = new QVBoxLayout(w); setCentralWidget(w); l->addWidget(textEdit = new TextEdit(w)); textEdit->setObjectName("primary"); if (chunkSize != -1) { textEdit->document()->setChunkSize(chunkSize); } l->addWidget(otherEdit = new TextEdit); otherEdit->setReadOnly(true); otherEdit->setObjectName("otherEdit"); textEdit->setReadOnly(readOnly); QFontDatabase fdb; foreach(QString family, fdb.families()) { if (fdb.isFixedPitch(family)) { QFont f(family); textEdit->setFont(f); break; } } // textEdit->setSyntaxHighlighter(new Highlighter(textEdit)); #ifndef QT_NO_DEBUG_STREAM if (codec) { qDebug() << "using codec" << codec->name(); } #endif if (appendTimer.isActive()) textEdit->document()->setOption(TextDocument::SwapChunks, true); if (!fileName.isEmpty() && !textEdit->load(fileName, TextDocument::Sparse, codec)) { #ifndef QT_NO_DEBUG_STREAM qDebug() << "Can't load" << fileName; #endif } otherEdit->setDocument(textEdit->document()); lbl = new QLabel(w); connect(textEdit, SIGNAL(cursorPositionChanged(int)), this, SLOT(onCursorPositionChanged(int))); l->addWidget(lbl); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_E), textEdit, SLOT(ensureCursorVisible())); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_L), this, SLOT(createTextSection())); new QShortcut(QKeySequence(QKeySequence::Close), this, SLOT(close())); new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(changeTextSectionFormat())); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_S), this, SLOT(save())); new QShortcut(QKeySequence(Qt::ALT + Qt::Key_S), this, SLOT(saveAs())); QMenu *menu = menuBar()->addMenu("&File"); menu->addAction("About textedit", this, SLOT(about())); QHBoxLayout *h = new QHBoxLayout; h->addWidget(box = new QSpinBox(centralWidget())); connect(textEdit->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(onScrollBarValueChanged())); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_G), this, SLOT(gotoPos())); box->setReadOnly(true); box->setRange(0, INT_MAX); l->addLayout(h); connect(textEdit, SIGNAL(sectionClicked(TextSection *, QPoint)), this, SLOT(onTextSectionClicked(TextSection *, QPoint))); textEdit->viewport()->setAutoFillBackground(true); connect(textEdit->document(), SIGNAL(modificationChanged(bool)), this, SLOT(onModificationChanged(bool))); } void timerEvent(QTimerEvent *e) { if (e->timerId() == appendTimer.timerId()) { static int line = 0; textEdit->append(QString("This is line number %1\n").arg(++line)); TextCursor curs = textEdit->textCursor(); curs.movePosition(TextCursor::End); curs.movePosition(TextCursor::PreviousBlock); textEdit->setTextCursor(curs); textEdit->ensureCursorVisible(); if (line % 100 == 0) { qDebug() << "memory used" << textEdit->document()->currentMemoryUsage() << "documentSize" << textEdit->document()->documentSize(); } } else { QMainWindow::timerEvent(e); } } void closeEvent(QCloseEvent *e) { QSettings("LazyTextEditor", "LazyTextEditor").setValue("geometry", saveGeometry()); QMainWindow::closeEvent(e); } void showEvent(QShowEvent *e) { activateWindow(); raise(); #ifndef QT_NO_DEBUG extern bool doLog; // from textedit.cpp if (doLog) #endif restoreGeometry(QSettings("LazyTextEditor", "LazyTextEditor").value("geometry").toByteArray()); QMainWindow::showEvent(e); } public slots: void onModificationChanged(bool on) { QPalette pal = textEdit->viewport()->palette(); pal.setColor(textEdit->viewport()->backgroundRole(), on ? Qt::yellow : Qt::white); textEdit->viewport()->setPalette(pal); } void save() { textEdit->document()->save(); } void saveAs() { const QString str = QFileDialog::getSaveFileName(this, "Save as", "."); if (!str.isEmpty()) textEdit->document()->save(str); } void about() { textEdit->textCursor().setPosition(0); QMessageBox::information(this, "Textedit", QString("Current memory usage %1KB"). arg(textEdit->document()->currentMemoryUsage() / 1024), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } void onCursorPositionChanged(int pos) { QString text = QString("Position: %1\n" "Word: %2\n"). arg(pos). arg(textEdit->textCursor().wordUnderCursor()); if (doLineNumbers) text += QString("Line number: %0").arg(textEdit->document()->lineNumber(pos)); lbl->setText(text); } void sendNextEvent() { QEvent *ev = events.takeFirst(); QWidget *target = textEdit->viewport(); switch (ev->type()) { case QEvent::Resize: resize(static_cast<QResizeEvent*>(ev)->size()); break; case QEvent::KeyPress: if (static_cast<QKeyEvent*>(ev)->matches(QKeySequence::Close)) break; // fall through target = textEdit; default: QApplication::postEvent(target, ev); break; } if (!events.isEmpty()) { QTimer::singleShot(0, this, SLOT(sendNextEvent())); #ifndef QT_NO_DEBUG } else if (add) { extern bool doLog; // from textedit.cpp doLog = true; #endif } } void createTextSection() { TextCursor cursor = textEdit->textCursor(); if (cursor.hasSelection()) { static bool first = true; QTextCharFormat format; if (first) { format.setForeground(Qt::blue); format.setFontUnderline(true); } else { format.setBackground(Qt::black); format.setForeground(Qt::white); } const int pos = cursor.selectionStart(); const int size = cursor.selectionEnd() - pos; TextSection *s = 0; if (first) { s = textEdit->insertTextSection(pos, size, format, cursor.selectedText()); Q_ASSERT(!otherEdit->sections().contains(s)); Q_ASSERT(!s || textEdit->sections().contains(s)); } else { s = textEdit->document()->insertTextSection(pos, size, format, cursor.selectedText()); } first = !first; if (s) { s->setCursor(Qt::PointingHandCursor); Q_UNUSED(s); Q_ASSERT(s); } } } void changeTextSectionFormat() { static bool first = true; QTextCharFormat format; format.setFontUnderline(true); if (first) { format.setForeground(Qt::white); format.setBackground(Qt::blue); } else { format.setForeground(Qt::blue); } first = !first; foreach(TextSection *s, textEdit->sections()) { s->setFormat(format); } } void onTextSectionClicked(TextSection *section, const QPoint &pos) { #ifndef QT_NO_DEBUG_STREAM qDebug() << section->text() << section->data() << pos; #endif } void onScrollBarValueChanged() { box->setValue(textEdit->viewportPosition()); } void gotoPos() { TextCursor &cursor = textEdit->textCursor(); bool ok; int pos = QInputDialog::getInteger(this, "Goto pos", "Pos", cursor.position(), 0, textEdit->document()->documentSize(), 1, &ok); if (!ok) return; cursor.setPosition(pos); } private: QSpinBox *box; TextEdit *textEdit, *otherEdit; QLabel *lbl; QLinkedList<QEvent*> events; bool doLineNumbers; QBasicTimer appendTimer; }; #include "main.moc" int main(int argc, char **argv) { QApplication a(argc, argv); MainWindow w; w.resize(500, 100); w.show(); return a.exec(); } <commit_msg>extra debugging things<commit_after>#include <QWidget> #include <QString> #include <QFont> #include <QMainWindow> #include <QVBoxLayout> #include <QApplication> #include <QEvent> #include "textedit.h" // ### TODO ### // ### Should clear selection when something else selects something. // ### Line break. Could vastly simplify textlayout if not breaking lines. // ### saving to same file. Need something there. // ### could refactor chunks so that I only have one and split when I need. Not sure if it's worth it. Would // ### need chunkData(int from = 0, int size = -1). The current approach makes caching easier since I can now cache an entire chunk. // ### ensureCursorVisible(TextCursor) is not implemented // ### add a command line switch to randomly do stuff. Insert, move around etc n times to see if I can reproduce a crash. Allow input of seed // ### I still have some weird debris when scrolling in large documents // ### use tests from Qt. E.g. for QTextCursor // ### need to protect against undo with huge amounts of text in it. E.g. select all and delete. MsgBox asking? // ### maybe refactor updatePosition so it can handle the margins usecase that textcursor needs. // ### could keep undo/redo history in the textcursor and have an api on the cursor. // ### block state in SyntaxHighlighter doesn't remember between // ### highlights. In regular QText.* it does. Could store this info. // ### Shouldn't be that much. Maybe base it off of position in // ### document rather than line number since I don't know which line // ### we're on // ### TextCursor(const TextEdit *). Is this a good idea? // ### caching stuff is getting a little convoluted // ### what should TextDocument::read(documentSize + 1, 10) do? ASSERT? // ### should I allow to write in a formatted manner? currentTextFormat and all? Why not really. // ### consider using QTextBoundaryFinder for something // ### drag and drop // ### documentation // ### consider having extra textLayouts on each side of viewport for optimized scrolling. Could detect that condition // ### Undo section removal/adding. This is a mess class Highlighter : public SyntaxHighlighter { public: Highlighter(QWidget *parent) : SyntaxHighlighter(parent) { } void helper(int from, int size, bool blackForeground) { QTextCharFormat format; format.setBackground(blackForeground ? Qt::yellow : Qt::black); format.setForeground(blackForeground ? Qt::black : Qt::yellow); setFormat(from, size, format); // qDebug() << "setting format" << from << size << currentBlock().mid(from, size) << blackForeground; } virtual void highlightBlock(const QString &text) { enum { Space, LetterOrNumber, Other } state = Space; int last = 0; for (int i=0; i<text.size(); ++i) { if (text.at(i).isSpace()) { if (state != Space) helper(last, i - last, state == LetterOrNumber); state = Space; last = i; } else if (text.at(i).isLetterOrNumber() != (state == LetterOrNumber) || state == Space) { if (state != Space) { helper(last, i - last, state == LetterOrNumber); } state = (text.at(i).isLetterOrNumber() ? LetterOrNumber : Other); last = i; } } if (state != Space) { helper(last, text.size() - last, state == LetterOrNumber); } } }; bool add = false; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0) : QMainWindow(parent), doLineNumbers(false) { QString fileName = "main.cpp"; bool replay = false; bool readOnly = false; int chunkSize = -1; QTextCodec *codec = 0; const QStringList list = QApplication::arguments().mid(1); for (int i=0; i<list.size(); ++i) { const QString &arg = list.at(i); if (arg == "--replay") { replay = true; fileName.clear(); } else if (arg == "--add") { replay = true; add = true; fileName.clear(); } else if (arg == "--log") { fileName.clear(); appendTimer.start(10, this); readOnly = true; chunkSize = 1000; } else if (arg == "--readonly") { readOnly = true; } else if (arg == "--linenumbers") { doLineNumbers = true; } else if (arg.startsWith("--codec=")) { codec = QTextCodec::codecForName(arg.mid(8).toLatin1()); if (!codec) { qWarning("Can't load codec called '%s'", qPrintable(arg.mid(8))); exit(1); } } else if (arg.startsWith("--chunksize=")) { bool ok; chunkSize = arg.mid(12).toInt(&ok); if (!ok) { qWarning("Can't parse %s", qPrintable(arg)); exit(1); } } else { fileName = arg; } } if (fileName.isEmpty() && !appendTimer.isActive()) { Q_ASSERT(replay); QStringList list = QDir(".").entryList(QStringList() << "*.log"); if (list.isEmpty()) { qWarning("Nothing to replay"); exit(1); } qSort(list); fileName = list.last(); } if (replay) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { qWarning("Can't open '%s' for reading", qPrintable(fileName)); exit(1); } #ifndef QT_NO_DEBUG_STREAM qDebug() << "replaying" << fileName; #endif #ifndef QT_NO_DEBUG if (add) { extern QString logFileName; logFileName = fileName; } extern bool doLog; // from textedit.cpp doLog = false; #endif QDataStream ds(&file); ds >> fileName; // reuse this variable for loading document. First QString in log file while (!file.atEnd()) { int type; ds >> type; if (type == QEvent::KeyPress || type == QEvent::KeyRelease) { int key; int modifiers; QString text; bool isAutoRepeat; int count; ds >> key; ds >> modifiers; ds >> text; ds >> isAutoRepeat; ds >> count; events.append(new QKeyEvent(static_cast<QEvent::Type>(type), key, static_cast<Qt::KeyboardModifiers>(modifiers), text, isAutoRepeat, count)); } else if (type == QEvent::Resize) { QSize size; ds >> size; events.append(new QResizeEvent(size, QSize())); } else { Q_ASSERT(type == QEvent::MouseMove || type == QEvent::MouseButtonPress || type == QEvent::MouseButtonRelease); QPoint pos; int button; int buttons; int modifiers; ds >> pos; ds >> button; ds >> buttons; ds >> modifiers; events.append(new QMouseEvent(static_cast<QEvent::Type>(type), pos, static_cast<Qt::MouseButton>(button), static_cast<Qt::MouseButtons>(buttons), static_cast<Qt::KeyboardModifiers>(modifiers))); } } if (!events.isEmpty()) QTimer::singleShot(0, this, SLOT(sendNextEvent())); } QWidget *w = new QWidget(this); QVBoxLayout *l = new QVBoxLayout(w); setCentralWidget(w); l->addWidget(textEdit = new TextEdit(w)); textEdit->setObjectName("primary"); if (chunkSize != -1) { textEdit->document()->setChunkSize(chunkSize); } l->addWidget(otherEdit = new TextEdit); otherEdit->setReadOnly(true); otherEdit->hide(); otherEdit->setObjectName("otherEdit"); textEdit->setReadOnly(readOnly); QFontDatabase fdb; foreach(QString family, fdb.families()) { if (fdb.isFixedPitch(family)) { QFont f(family); textEdit->setFont(f); break; } } // textEdit->setSyntaxHighlighter(new Highlighter(textEdit)); #ifndef QT_NO_DEBUG_STREAM if (codec) { qDebug() << "using codec" << codec->name(); } #endif if (appendTimer.isActive()) textEdit->document()->setOption(TextDocument::SwapChunks, true); if (!fileName.isEmpty() && !textEdit->load(fileName, TextDocument::Sparse, codec)) { #ifndef QT_NO_DEBUG_STREAM qDebug() << "Can't load" << fileName; #endif } #if 0 textEdit->document()->setText("This is a test"); QTextCharFormat format; format.setBackground(Qt::yellow); textEdit->insertTextSection(0, 4, format); format = QTextCharFormat(); format.setFontItalic(true); textEdit->insertTextSection(0, 4, format); #endif otherEdit->setDocument(textEdit->document()); lbl = new QLabel(w); connect(textEdit, SIGNAL(cursorPositionChanged(int)), this, SLOT(onCursorPositionChanged(int))); l->addWidget(lbl); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_E), textEdit, SLOT(ensureCursorVisible())); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_L), this, SLOT(createTextSection())); new QShortcut(QKeySequence(QKeySequence::Close), this, SLOT(close())); new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(changeTextSectionFormat())); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_S), this, SLOT(save())); new QShortcut(QKeySequence(Qt::ALT + Qt::Key_S), this, SLOT(saveAs())); QMenu *menu = menuBar()->addMenu("&File"); menu->addAction("About textedit", this, SLOT(about())); QHBoxLayout *h = new QHBoxLayout; h->addWidget(box = new QSpinBox(centralWidget())); connect(textEdit->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(onScrollBarValueChanged())); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_G), this, SLOT(gotoPos())); box->setReadOnly(true); box->setRange(0, INT_MAX); l->addLayout(h); connect(textEdit, SIGNAL(sectionClicked(TextSection *, QPoint)), this, SLOT(onTextSectionClicked(TextSection *, QPoint))); textEdit->viewport()->setAutoFillBackground(true); connect(textEdit->document(), SIGNAL(modificationChanged(bool)), this, SLOT(onModificationChanged(bool))); } void timerEvent(QTimerEvent *e) { if (e->timerId() == appendTimer.timerId()) { static int line = 0; textEdit->append(QString("This is line number %1\n").arg(++line)); TextCursor curs = textEdit->textCursor(); curs.movePosition(TextCursor::End); curs.movePosition(TextCursor::PreviousBlock); textEdit->setTextCursor(curs); textEdit->ensureCursorVisible(); if (line % 100 == 0) { qDebug() << "memory used" << textEdit->document()->currentMemoryUsage() << "documentSize" << textEdit->document()->documentSize(); } } else { QMainWindow::timerEvent(e); } } void closeEvent(QCloseEvent *e) { QSettings("LazyTextEditor", "LazyTextEditor").setValue("geometry", saveGeometry()); QMainWindow::closeEvent(e); } void showEvent(QShowEvent *e) { activateWindow(); raise(); #ifndef QT_NO_DEBUG extern bool doLog; // from textedit.cpp if (doLog) #endif restoreGeometry(QSettings("LazyTextEditor", "LazyTextEditor").value("geometry").toByteArray()); QMainWindow::showEvent(e); } public slots: void onModificationChanged(bool on) { QPalette pal = textEdit->viewport()->palette(); pal.setColor(textEdit->viewport()->backgroundRole(), on ? Qt::yellow : Qt::white); textEdit->viewport()->setPalette(pal); } void save() { textEdit->document()->save(); } void saveAs() { const QString str = QFileDialog::getSaveFileName(this, "Save as", "."); if (!str.isEmpty()) textEdit->document()->save(str); } void about() { textEdit->textCursor().setPosition(0); QMessageBox::information(this, "Textedit", QString("Current memory usage %1KB"). arg(textEdit->document()->currentMemoryUsage() / 1024), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } void onCursorPositionChanged(int pos) { QString text = QString("Position: %1\n" "Word: %2\n"). arg(pos). arg(textEdit->textCursor().wordUnderCursor()); if (doLineNumbers) text += QString("Line number: %0").arg(textEdit->document()->lineNumber(pos)); lbl->setText(text); } void sendNextEvent() { QEvent *ev = events.takeFirst(); QWidget *target = textEdit->viewport(); switch (ev->type()) { case QEvent::Resize: resize(static_cast<QResizeEvent*>(ev)->size()); break; case QEvent::KeyPress: if (static_cast<QKeyEvent*>(ev)->matches(QKeySequence::Close)) break; // fall through target = textEdit; default: QApplication::postEvent(target, ev); break; } if (!events.isEmpty()) { QTimer::singleShot(0, this, SLOT(sendNextEvent())); #ifndef QT_NO_DEBUG } else if (add) { extern bool doLog; // from textedit.cpp doLog = true; #endif } } void createTextSection() { TextCursor cursor = textEdit->textCursor(); if (cursor.hasSelection()) { static bool first = true; QTextCharFormat format; if (first) { format.setForeground(Qt::blue); format.setFontUnderline(true); } else { format.setBackground(Qt::black); format.setForeground(Qt::white); } const int pos = cursor.selectionStart(); const int size = cursor.selectionEnd() - pos; TextSection *s = 0; if (first) { s = textEdit->insertTextSection(pos, size, format, cursor.selectedText()); if (s) { s->setCursor(Qt::PointingHandCursor); Q_UNUSED(s); Q_ASSERT(s); } Q_ASSERT(!otherEdit->sections().contains(s)); Q_ASSERT(!s || textEdit->sections().contains(s)); } else { s = textEdit->document()->insertTextSection(pos, size, format, cursor.selectedText()); } first = !first; } } void changeTextSectionFormat() { static bool first = true; QTextCharFormat format; format.setFontUnderline(true); if (first) { format.setForeground(Qt::white); format.setBackground(Qt::blue); } else { format.setForeground(Qt::blue); } first = !first; foreach(TextSection *s, textEdit->sections()) { s->setFormat(format); } } void onTextSectionClicked(TextSection *section, const QPoint &pos) { #ifndef QT_NO_DEBUG_STREAM qDebug() << section->text() << section->data() << pos; #endif } void onScrollBarValueChanged() { box->setValue(textEdit->viewportPosition()); } void gotoPos() { TextCursor &cursor = textEdit->textCursor(); bool ok; int pos = QInputDialog::getInteger(this, "Goto pos", "Pos", cursor.position(), 0, textEdit->document()->documentSize(), 1, &ok); if (!ok) return; cursor.setPosition(pos); } private: QSpinBox *box; TextEdit *textEdit, *otherEdit; QLabel *lbl; QLinkedList<QEvent*> events; bool doLineNumbers; QBasicTimer appendTimer; }; #include "main.moc" int main(int argc, char **argv) { QApplication a(argc, argv); MainWindow w; w.resize(500, 100); w.show(); return a.exec(); } <|endoftext|>
<commit_before>5a7c1059-2e4f-11e5-85d7-28cfe91dbc4b<commit_msg>5a82e28f-2e4f-11e5-8598-28cfe91dbc4b<commit_after>5a82e28f-2e4f-11e5-8598-28cfe91dbc4b<|endoftext|>
<commit_before>// rump_equation.cpp: example program to show Rump computation requiring high-precision floats to work // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <ostream> #include <limits> #include <numeric> // nextafter // select the number systems we would like to compare #include <universal/number/integer/integer> #include <universal/number/fixpnt/fixpnt> #include <universal/number/areal/areal> //#include <universal/number/bfloat/bfloat> #include <universal/number/posit/posit> #include <universal/number/lns/lns> #include <universal/number/posit/numeric_limits.hpp> template<typename Scalar> Scalar Rump(const Scalar& a, const Scalar& b) { Scalar b2 = b * b; Scalar b3 = b * b * b; Scalar b4 = b2 * b2; Scalar b6 = b3 * b3; Scalar b8 = b4 * b4; Scalar a2 = a * a; // 333.75 * b ^ 6 + a ^ 2 * (11 * a ^ 2 * b ^ 2 - b ^ 6 - 121 * b ^ 4 - 2) + 5.5 * b ^ 8 + a / (2 * b); return 333.75 * b6 + a2 * (11 * a2 * b2 - b6 - 121 * b4 - 2) + 5.5 * b8 + a / (2 * b); } int main(int argc, char** argv) try { using namespace std; using namespace sw::universal; cout << "Rump's equation\n"; /* * one off constant computation from "Handbook of Floating-Point Arithmetic": f(a,b) = 333.75*b^6 + a^2*(11*a^2*b^2 - b^6 - 121*b^4 - 2) + 5.5*b^8 + a/(2*b) for a=77617.0, b=33096.0 The exact result is -54767 / 66192 which starts with −0.8273960599... Using pow vs repeated mutiplication for the power expressions usually yields the same answer, but not always Running on x86 fp types we get (picking some interesting MPFR results) Type | Rep Mult | Pow Func ------------+-------------+------------- float | -6.3383E+29 | -6.3383E+29 double | -1.1806E+21 | -1.1806E+21 long double | 1.1726 | 5.7646E+17 quad | 1.1726 | 1.1726 mpfr(26) | 1.5846E+29 | -1.5846E+29 mpfr(37) | 1.1726 | -1.5474E+26 mpfr(54) | 1.1806e+21 | 1.1726 mpfr(76) | 1.1726 | 1.1726 mpfr(98) | 3.3554E+07 | 3.3554E+07 mpfr(121) | 1.1726 | 1.1726 mpfr(122) | -0.8274 | -0.8274 It requires 122 bits of mantissa under MPFR to get the correct answer, and is really erratic at "lower" precision. There are a couple fpbench versions of it: https://fpbench.org/benchmarks.html#Rump's%20example */ streamsize precision = cout.precision(); double da = 77617.0; double db = 33096.0; { posit<128, 2> a{ da }, b{ db }; cout << double(Rump(a, b)) << endl; } { posit<156, 2> a{ da }, b{ db }; cout << double(Rump(a, b)) << endl; } { posit<256, 2> a{ da }, b{ db }; cout << double(Rump(a, b)) << endl; } cout << setprecision(precision); cout << endl; return EXIT_SUCCESS; } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (const std::runtime_error& err) { std::cerr << "Uncaught runtime exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; } <commit_msg>experiments with the Rump equation and different number systems<commit_after>// rump_equation.cpp: example program to show Rump computation requiring high-precision floats to work // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <ostream> #include <limits> #include <numeric> // nextafter // select the number systems we would like to compare #include <universal/number/decimal/decimal> #include <universal/number/integer/integer> #include <universal/number/fixpnt/fixpnt> #include <universal/number/areal/areal> #include <universal/number/bfloat/bfloat> #include <universal/number/posit/posit> #include <universal/number/lns/lns> #include <universal/number/posit/numeric_limits.hpp> #include <universal/blas/blas.hpp> /* In 1988, Siegfried Rump published an example in which numerical evaluation of an expression gave a misleading result, even though use of increasing arithmetic precision suggested reliable computation. Rump's example is to compute the expression: f(a,b) = 333.75 * b ^ 6 + a ^ 2 * (11 * a ^ 2 * b ^ 2 - b ^ 6 - 121 * b ^ 4 - 2) + 5.5 * b ^ 8 + a / (2 * b) with a = 77617 and b 33096. On an IBM S/370 main frame the function evaluates to the following values given the labeled precision: single precision f = 1.172603... double precision f = 1.1726039400531... extended precision f = 1.172603949953178... This creates the illusion of a reliable result of approximately 1.172603. But in fact, the correct result is: correct result f = -0.827396059946821368141165095479816... Using IEEE-754, we get the following results: type | Rump1 | Rump2 | Rump3 | float | 2.80149e+29 | 1.1726 | -0.827396 | double | -1.18059e+21 | 1.1726 | -0.827396 | long double | -1.18059e+21 | 1.1726 | -0.827396 | The root cause of this behavior is catastrophic cancellation due to the large scale of the exponentiation terms. The value of a and b satisfy the equation: a ^ 2 = 5.5 * b ^ 2 + 1 Simple algebraic manipulation yields the more transparent form of the computation f(a,b) = 5.5 * b ^ 8 - 1 - 5.5 * b ^ 8 + a / ( 2 * b) In this form it is easy to see where the cancellation occurs. The large term 5.5b^8 cancels out leaving the quation: f(a,b) = -2 + a / (2 * b), which yields the correct value of -0.827396... for most formats. For any arithmetic to evaluate this function in its raw form requires enough precision bits to represent the value 1.0 in the ULP. 5.5*b^8 at b = 33096 is of the order of 8e+36, which requires 122 bits of precision to capture the -2.0 while still representing 8e+36 and thus avoiding catastrophic cancellation of this -2.0 during the computation. */ // original f(a,b) = 333.75 * b ^ 6 + a ^ 2 * (11 * a ^ 2 * b ^ 2 - b ^ 6 - 121 * b ^ 4 - 2) + 5.5 * b ^ 8 + a / (2 * b); template<typename Scalar> Scalar Rump1(double _a, double _b) { Scalar a, b; a = Scalar(_a); b = Scalar(_b); Scalar b2 = b * b; Scalar b3 = b * b * b; Scalar b4 = b2 * b2; Scalar b6 = b3 * b3; Scalar b8 = b4 * b4; Scalar a2 = a * a; // 333.75 * b ^ 6 + a ^ 2 * (11 * a ^ 2 * b ^ 2 - b ^ 6 - 121 * b ^ 4 - 2) + 5.5 * b ^ 8 + a / (2 * b); return 333.75 * b6 + a2 * (11 * a2 * b2 - b6 - 121 * b4 - 2) + 5.5 * b8 + a / (2 * b); } template<typename Scalar> Scalar TraceRump1(double _a, double _b) { std::cout << "+-----------------------------------------------------------------------------\n" << typeid(Scalar).name() << '\n'; Scalar a, b; a = Scalar(_a); b = Scalar(_b); Scalar b2 = b * b; std::cout << "b * b : " << b2 << '\n'; Scalar b3 = b * b * b; std::cout << "b * b * b : " << b3 << '\n'; Scalar b4 = b2 * b2; std::cout << "b * b * b * b : " << b4 << '\n'; Scalar b6 = b3 * b3; std::cout << "b3 * b3 : " << b6 << '\n'; Scalar b8 = b4 * b4; std::cout << "b4 * b4 : " << b8 << '\n'; Scalar a2 = a * a; std::cout << "a * a : " << a2 << '\n'; Scalar term1 = 333.75 * b6; std::cout << "333.75 * b6 term1 : " << term1 << '\n'; Scalar term2 = 11 * a2 * b2; std::cout << "11 * a2 * b2 : " << term2 << '\n'; Scalar term3 = (11 * a2 * b2 - b6 - 121 * b4 - 2); std::cout << "(11 * a2 * b2 - b6 - 121 * b4 - 2) : " << term3 << '\n'; Scalar term4 = a2 * term3; std::cout << "a2 * previous_term term4 : " << term4 << '\n'; Scalar term5 = 5.5 * b8; std::cout << "5.5 * b8 term5 : " << term5 << '\n'; Scalar term6 = a / (2 * b); std::cout << "a / (2 * b) term6 : " << term6 << '\n'; std::cout << "term1 + term4 + term5 + term6 : " << term1 + term4 + term5 + term6 << '\n'; // 333.75 * b ^ 6 + a ^ 2 * (11 * a ^ 2 * b ^ 2 - b ^ 6 - 121 * b ^ 4 - 2) + 5.5 * b ^ 8 + a / (2 * b); return 333.75 * b6 + a2 * (11 * a2 * b2 - b6 - 121 * b4 - 2) + 5.5 * b8 + a / (2 * b); } // rewrite f(a,b) = 5.5 * b ^ 8 - 2 - 5.5 * b ^ 8 + a / (2 * b) template<typename Scalar> Scalar Rump2(double _a, double _b) { Scalar a, b; a = Scalar(_a); b = Scalar(_b); Scalar b2 = b * b; Scalar b4 = b2 * b2; Scalar b8 = b4 * b4; // 5.5 * b ^ 8 - 2 - 5.5 * b ^ 8 + a / (2 * b) return 5.5 * b8 - 2.0 - 5.5 * b8 + (a / (2 * b)); } // f(a,b) = -2 + a / 2b template<typename Scalar> Scalar Rump3(double _a, double _b) { Scalar a, b; a = Scalar(_a); b = Scalar(_b); return -2.0 + a / (2 * b); } template<typename Scalar> void GenerateRow(double a, double b, sw::universal::blas::matrix<double>& table, size_t rowNr) { table(rowNr, 0) = double(Rump1<Scalar>(a, b)); table(rowNr, 1) = double(Rump2<Scalar>(a, b)); table(rowNr, 2) = double(Rump3<Scalar>(a, b)); } int main(int argc, char** argv) try { using namespace std; using namespace sw::universal; cout << "Rump's equation\n"; /* * one off constant computation from "Handbook of Floating-Point Arithmetic": f(a,b) = 333.75*b^6 + a^2*(11*a^2*b^2 - b^6 - 121*b^4 - 2) + 5.5*b^8 + a/(2*b) for a=77617.0, b=33096.0 The exact result is -54767 / 66192 which starts with −0.8273960599... Using pow vs repeated mutiplication for the power expressions usually yields the same answer, but not always Running on x86 fp types we get (picking some interesting MPFR results) Type | Rep Mult | Pow Func ------------+-------------+------------- float | -6.3383E+29 | -6.3383E+29 double | -1.1806E+21 | -1.1806E+21 long double | 1.1726 | 5.7646E+17 quad | 1.1726 | 1.1726 mpfr(26) | 1.5846E+29 | -1.5846E+29 mpfr(37) | 1.1726 | -1.5474E+26 mpfr(54) | 1.1806e+21 | 1.1726 mpfr(76) | 1.1726 | 1.1726 mpfr(98) | 3.3554E+07 | 3.3554E+07 mpfr(121) | 1.1726 | 1.1726 mpfr(122) | -0.8274 | -0.8274 It requires 122 bits of mantissa under MPFR to get the correct answer, and is really erratic at "lower" precision. There are a couple fpbench versions of it: https://fpbench.org/benchmarks.html#Rump's%20example */ streamsize precision = cout.precision(); double a = 77617.0; double b = 33096.0; using Labels = std::vector<std::string>; using Data = blas::matrix<double>; Labels rowLbls = { "float", "double", "long double", "quad", "posit16", "posit32", "posit48", "posit64", "posit80", "posit128", "posit156", "integer96", "integer112", "integer128", "integer256", "bfloat16", "bfloat32", "bfloat64", "bfloat80", "bfloat100", "bfloat120" }; Labels column = { "Rump1", "Rump2", "Rump3" }; // using quad = bfloat<128, 11>; Data table(20, 5); GenerateRow<float>(a, b, table, 0); GenerateRow<double>(a, b, table, 1); GenerateRow<long double>(a, b, table, 2); // GenerateRow<quad>(a, b, table, 3); GenerateRow<posit<16, 2>>(a, b, table, 4); GenerateRow<posit<32, 2>>(a, b, table, 5); GenerateRow<posit<48, 2>>(a, b, table, 6); GenerateRow<posit<64, 2>>(a, b, table, 7); GenerateRow<posit<80, 2>>(a, b, table, 8); GenerateRow<posit<128, 2>>(a, b, table, 9); GenerateRow<posit<156, 2>>(a, b, table, 10); GenerateRow<integer<96,uint32_t>>(a, b, table, 11); GenerateRow<integer<112, uint32_t>>(a, b, table, 12); GenerateRow<integer<128, uint32_t>>(a, b, table, 13); GenerateRow<integer<256, uint32_t>>(a, b, table, 14); // print the table constexpr size_t COLUMN_WIDTH = 20; cout << setw(COLUMN_WIDTH) << "type" << " | "; for (size_t j = 0; j < size(column); ++j) { cout << setw(COLUMN_WIDTH) << column[j] << " | "; } cout << '\n'; for (size_t i; i < size(rowLbls); ++i) { cout << setw(COLUMN_WIDTH) << rowLbls[i] << " | "; for (size_t j = 0; j < 3; ++j) { cout << setw(COLUMN_WIDTH) << table(i, j) << " | "; } cout << '\n'; } cout << setprecision(precision); cout << endl; // trace out the original Rump equation with different number systems TraceRump1<double>(a, b); TraceRump1<posit<156,2>>(a, b); TraceRump1<integer<256, uint32_t>>(a, b); TraceRump1<decimal>(a, b); // TODO: some serious errors here return EXIT_SUCCESS; } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (const std::runtime_error& err) { std::cerr << "Uncaught runtime exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; } <|endoftext|>
<commit_before>92323ad6-2d14-11e5-af21-0401358ea401<commit_msg>92323ad7-2d14-11e5-af21-0401358ea401<commit_after>92323ad7-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <osg/Version> #include <osg/ArgumentParser> #include <osg/ApplicationUsage> #include <set> #include <vector> #include <iostream> #include <fstream> typedef std::pair<std::string, std::string> NamePair; typedef std::set<NamePair> NameSet; NamePair EmptyNamePair; bool validName(const std::string& first) { if (first.empty()) return false; if (first[0]<'A' || first[0]>'Z') return false; if (first.size()>=2 && (first[1]<'a' || first[1]>'z')) return false; if (first=="Added") return false; if (first=="CameraNode") return false; if (first=="CopyOp") return false; if (first=="Fixed") return false; if (first=="Creator") return false; if (first=="CullVisitor") return false; if (first=="Drawable") return false; if (first=="Geode") return false; if (first=="GeoSet") return false; if (first=="Image") return false; if (first=="Images/SolarSystem") return false; if (first=="IntersectVisitor") return false; if (first=="LongIDRecord") return false; if (first=="Makefile") return false; if (first=="Matrix") return false; if (first=="MemoryManager") return false; if (first=="MeshRecord") return false; if (first=="Multigen") return false; if (first=="NewCullVisitor") return false; if (first=="Output") return false; if (first=="PageLOD") return false; if (first=="Improved") return false; if (first=="PagedLOD") return false; if (first=="Referenced") return false; if (first=="StateAttribute") return false; if (first=="Switch") return false; if (first=="TechniqueEventHandler") return false; if (first=="Uniform") return false; if (first=="Vec*") return false; if (first=="Viewer") return false; if (first=="VisualStudio") return false; if (first=="X") return false; if (first=="Y") return false; if (first=="Producer") return false; if (first=="New") return false; if (first=="Removed") return false; if (first=="Ouput") return false; if (first=="ReaderWriters") return false; if (first=="NodeVisitor") return false; if (first=="Fixes") return false; if (first=="FontImplementation") return false; if (first=="DisplaySettings") return false; return true; } std::string typoCorrection(const std::string& name) { #if 0 if (name=="") return ""; if (name=="") return ""; if (name=="") return ""; #endif if (name=="Bistroviae") return "Bistrovic"; if (name=="Christaiansen") return "Christiansen"; if (name=="Daust") return "Daoust"; if (name=="Daved") return "David"; if (name=="Fred") return "Frederic"; if (name=="Fredrick") return "Frederic"; if (name=="Fredric") return "Frederic"; if (name=="Garrat") return "Garret"; if (name=="Geof") return "Geoff"; if (name=="Gronenger") return "Gronager"; if (name=="Gronger") return "Gronager"; if (name=="Heirtlein") return "Heirtlein"; if (name=="Heirtlein") return "Hertlein"; if (name=="Hertlien") return "Hertlein"; if (name=="Hi") return "He"; if (name=="Inverson") return "Iverson"; if (name=="Iversion") return "Iverson"; if (name=="Jeoen") return "Joran"; if (name=="Johhansen") return "Johansen"; if (name=="Johnansen") return "Johansen"; if (name=="Johnasen") return "Johansen"; if (name=="Jolley") return "Jolly"; if (name=="Jose") return "Jos"; if (name=="J") return "Jos"; if (name=="Keuhne") return "Kuehne"; if (name=="Kheune") return "Kuehne"; if (name=="Lashari") return "Lashkari"; if (name=="Laskari") return "Lashkari"; if (name=="Macro") return "Marco"; if (name=="Mammond") return "Marmond"; if (name=="March") return "Marco"; if (name=="Marz") return "Martz"; if (name=="Molishtan") return "Molishtan"; if (name=="Molishtan") return "Moloshtan"; if (name=="Moloshton") return "Moloshtan"; if (name=="Moloshton") return "Moloshtan"; if (name=="Moule") return "Moiule"; if (name=="Nicklov") return "Nikolov"; if (name=="Olad") return "Olaf"; if (name=="Osfied") return "Osfield"; if (name=="Pail") return "Paul"; if (name=="Sewel") return "Sewell"; if (name=="Sjolie") return "Sjlie"; if (name=="Sokolosky") return "Sokolowsky"; if (name=="Sokolsky") return "Sokolowsky"; if (name=="Sonda") return "Sondra"; if (name=="Stansilav") return "Stanislav"; if (name=="Stefan") return "Stephan"; if (name=="Stell") return "Steel"; if (name=="Tarantilils") return "Tarantilis"; if (name=="Wieblen") return "Weiblen"; if (name=="Xennon") return "Hanson"; if (name=="Yfei") return "Yefei"; if (name=="Oritz") return "Ortiz"; return name; } void nameCorrection(NamePair& name) { if (name.first=="Eric" && name.second=="Hammil") { name.first = "Chris"; name.second = "Hanson"; } if (name.first=="Nick" && name.second=="") { name.first = "Trajce"; name.second = "Nikolov"; } if (name.first=="Julia" && name.second=="Ortiz") { name.first = "Julian"; name.second = "Ortiz"; } } void lastValidCharacter(const std::string& name, unsigned int& pos,char c) { for(unsigned int i=0;i<pos;++i) { if (name[i]==c) { pos = i; return; } } } void lastValidCharacter(const std::string& name, unsigned int& last) { lastValidCharacter(name, last, '.'); lastValidCharacter(name, last, ','); lastValidCharacter(name, last, '\''); lastValidCharacter(name, last, '/'); lastValidCharacter(name, last, '\\'); lastValidCharacter(name, last, ':'); lastValidCharacter(name, last, ';'); lastValidCharacter(name, last, ')'); } NamePair createName(const std::string& first, const std::string& second) { if (first.empty()) return EmptyNamePair; unsigned int last = first.size(); lastValidCharacter(first, last); if (last==0) return EmptyNamePair; std::string name; name.append(first.begin(), first.begin()+last); if (!validName(name)) return EmptyNamePair; name = typoCorrection(name); if (second.empty()) return NamePair(name,""); if (!validName(second)) return NamePair(name,""); last = second.size(); lastValidCharacter(second, last); if (last>0) { std::string surname(second.begin(), second.begin()+last); surname = typoCorrection(surname); return NamePair(name, surname); } return NamePair(name,""); } void readContributors(NameSet& names, const std::string& file) { std::cout<<"readContributions(names,"<<file<<")"<<std::endl; std::ifstream fin(file.c_str()); typedef std::vector< std::string > Words; Words words; while(fin) { std::string keyword; fin >> keyword; words.push_back(keyword); } std::string blank_string; for(unsigned int i=0; i< words.size(); ++i) { if (words[i]=="From" || words[i]=="from" || words[i]=="From:" || words[i]=="from:") { if (i+2<words.size() && validName(words[i+1])) { NamePair name = createName(words[i+1], words[i+2]); nameCorrection(name); if (!name.first.empty()) names.insert(name); i+=2; } else if (i+1<words.size() && validName(words[i+1])) { NamePair name = createName(words[i+1], blank_string); nameCorrection(name); if (!name.first.empty()) names.insert(name); i+=1; } } } if (names.size()>1) { for(NameSet::iterator itr = names.begin(); itr != names.end(); ) { if (itr->second.empty()) { NameSet::iterator next_itr = itr; ++next_itr; if (next_itr!=names.end() && itr->first==next_itr->first) { names.erase(itr); itr = next_itr; } else { ++itr; } } else { ++itr; } } } } void buildContributors(NameSet& names) { names.insert(NamePair("Robert","Osfield")); names.insert(NamePair("Don","Burns")); names.insert(NamePair("Marco","Jez")); } int main( int argc, char **argv) { osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); arguments.getApplicationUsage()->addCommandLineOption("-c or --contributors","Print out the contributors list."); arguments.getApplicationUsage()->addCommandLineOption("-r <file> or --read <file>","Read the changelog to generate an estimated contributors list."); printf( "%s\n", osgGetVersion() ); bool printContributors = false; while ( arguments.read("-c") || arguments.read("--contributors")) printContributors = true; std::string changeLog; while ( arguments.read("-r",changeLog) || arguments.read("--read",changeLog)) printContributors = true; // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl; arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions()); return 1; } if (printContributors) { NameSet names; buildContributors(names); if (!changeLog.empty()) { readContributors(names, changeLog); } std::cout<<names.size()<<" Contributors:"<<std::endl; for(NameSet::iterator itr = names.begin(); itr != names.end(); ++itr) { std::cout<<" "<<itr->first<<" "<<itr->second<<std::endl; } } return 0; } <commit_msg>Added more typo catches.<commit_after>#include <osg/Version> #include <osg/ArgumentParser> #include <osg/ApplicationUsage> #include <set> #include <vector> #include <iostream> #include <fstream> typedef std::pair<std::string, std::string> NamePair; typedef std::set<NamePair> NameSet; typedef std::vector< std::string > Words; NamePair EmptyNamePair; bool validName(const std::string& first) { if (first.empty()) return false; if (first[0]<'A' || first[0]>'Z') return false; if (first.size()>=2 && (first[1]<'a' || first[1]>'z')) return false; if (first=="Added") return false; if (first=="CameraNode") return false; if (first=="CopyOp") return false; if (first=="Fixed") return false; if (first=="Creator") return false; if (first=="CullVisitor") return false; if (first=="Drawable") return false; if (first=="Geode") return false; if (first=="GeoSet") return false; if (first=="Image") return false; if (first=="Images/SolarSystem") return false; if (first=="IntersectVisitor") return false; if (first=="LongIDRecord") return false; if (first=="Makefile") return false; if (first=="Matrix") return false; if (first=="MemoryManager") return false; if (first=="MeshRecord") return false; if (first=="Multigen") return false; if (first=="NewCullVisitor") return false; if (first=="Output") return false; if (first=="PageLOD") return false; if (first=="Improved") return false; if (first=="PagedLOD") return false; if (first=="Referenced") return false; if (first=="StateAttribute") return false; if (first=="Switch") return false; if (first=="TechniqueEventHandler") return false; if (first=="Uniform") return false; if (first=="Vec*") return false; if (first=="Viewer") return false; if (first=="VisualStudio") return false; if (first=="X") return false; if (first=="Y") return false; if (first=="Producer") return false; if (first=="New") return false; if (first=="Removed") return false; if (first=="Ouput") return false; if (first=="ReaderWriters") return false; if (first=="NodeVisitor") return false; if (first=="Fixes") return false; if (first=="FontImplementation") return false; if (first=="DisplaySettings") return false; if (first=="AnimationPath") return false; if (first=="AnimationPathCallback") return false; if (first=="AnimationPathManipulator") return false; if (first=="ArgumentParser") return false; if (first=="AttrData") return false; if (first=="Azimuth") return false; if (first=="CluserCullingCallback") return false; if (first=="ClusterCullingCallback") return false; if (first=="CoordinateSystem") return false; if (first=="CoordinateSystemNode") return false; if (first=="CoordinateSystemNode&") return false; if (first=="Copyright") return false; if (first=="Cygwin") return false; if (first=="CullCallbacks") return false; if (first=="CullingSettngs") return false; if (first=="DataVariance") return false; if (first=="DatabasePager") return false; if (first=="DrawElementsUByte") return false; if (first=="Escape") return false; if (first=="FluidProgram") return false; if (first=="FrameStats") return false; if (first=="FreeBSD") return false; if (first=="GraphicsContextImplementation") return false; if (first=="GraphicsThread") return false; if (first=="Images") return false; if (first=="IndexBlock") return false; if (first=="Inventor") return false; if (first=="Make") return false; if (first=="Material") return false; if (first=="MergeGeometryVisitor") return false; if (first=="Mode") return false; if (first=="Prodcuer") return false; if (first=="ProxyNode") return false; if (first=="ReentrantMutex") return false; if (first=="ReferenceFrame") return false; if (first=="RemoveLoadedProxyNodes") return false; if (first=="RenderTargetFallback") return false; if (first=="RenderToTextureStage") return false; if (first=="Sequence") return false; if (first=="Shape") return false; if (first=="TessellationHints") return false; if (first=="Support") return false; if (first=="State") return false; if (first=="SmokeTrailEffect") return false; if (first=="TexEnv") return false; if (first=="Texture3D") return false; if (first=="TextureCubeMap") return false; if (first=="TextureObjectManager") return false; if (first=="TextureRectangle(Image*") return false; if (first=="TextureType") return false; if (first=="Texuture") return false; if (first=="TriStripVisitor") return false; if (first=="UserData") return false; if (first=="Viewport") return false; if (first=="Visual") return false; if (first=="Studio") return false; if (first=="Vec2d") return false; if (first=="Vec3d") return false; if (first=="Windows") return false; if (first=="Version") return false; if (first=="Viewport") return false; if (first=="Core") return false; if (first=="DataSet") return false; if (first=="Endian") return false; if (first=="ImageOptions") return false; if (first=="ImageStream") return false; if (first=="KeyboardMouse") return false; if (first=="KeyboardMouseCallback") return false; if (first=="AutoTransform") return false; if (first=="LightModel") return false; if (first=="MatrixManipulator") return false; if (first=="MatrixTransform") return false; if (first=="OpenDX") return false; if (first=="ParentList") return false; if (first=="TerraPage") return false; if (first=="OveralyNode") return false; if (first=="OpenThreads") return false; if (first=="PolygonStipple") return false; if (first=="SceneView") return false; if (first=="PrimitiveIndexFunctor") return false; if (first=="PolytopeVisitor") return false; if (first=="Performer") return false; if (first=="Paging") return false; return true; } std::string typoCorrection(const std::string& name) { #if 0 if (name=="") return ""; if (name=="") return ""; if (name=="") return ""; #endif if (name=="Micheal") return "Michael"; if (name=="Heirtlein") return "Hertlein"; if (name=="Yefrei") return "Yefei"; if (name=="Randal") return "Randall"; if (name=="Hooper") return "Hopper"; if (name=="Molishtan") return "Moloshtan"; if (name=="Vines") return "Vine"; if (name=="Connel") return "Connell"; if (name=="Bistroviae") return "Bistrovic"; if (name=="Christaiansen") return "Christiansen"; if (name=="Daust") return "Daoust"; if (name=="Daved") return "David"; if (name=="Fred") return "Frederic"; if (name=="Fredrick") return "Frederic"; if (name=="Fredric") return "Frederic"; if (name=="Garrat") return "Garret"; if (name=="Geof") return "Geoff"; if (name=="Gronenger") return "Gronager"; if (name=="Gronger") return "Gronager"; if (name=="Heirtlein") return "Heirtlein"; if (name=="Heirtlein") return "Hertlein"; if (name=="Hertlien") return "Hertlein"; if (name=="Hi") return "He"; if (name=="Inverson") return "Iverson"; if (name=="Iversion") return "Iverson"; if (name=="Jeoen") return "Joran"; if (name=="Johhansen") return "Johansen"; if (name=="Johnansen") return "Johansen"; if (name=="Johnasen") return "Johansen"; if (name=="Jolley") return "Jolly"; if (name=="Jose") return "Jos"; if (name=="J") return "Jos"; if (name=="Keuhne") return "Kuehne"; if (name=="Kheune") return "Kuehne"; if (name=="Lashari") return "Lashkari"; if (name=="Laskari") return "Lashkari"; if (name=="Macro") return "Marco"; if (name=="Mammond") return "Marmond"; if (name=="March") return "Marco"; if (name=="Marz") return "Martz"; if (name=="Molishtan") return "Molishtan"; if (name=="Molishtan") return "Moloshtan"; if (name=="Moloshton") return "Moloshtan"; if (name=="Moloshton") return "Moloshtan"; if (name=="Moule") return "Moiule"; if (name=="Nicklov") return "Nikolov"; if (name=="Olad") return "Olaf"; if (name=="Osfied") return "Osfield"; if (name=="Pail") return "Paul"; if (name=="Sewel") return "Sewell"; if (name=="Sjolie") return "Sjlie"; if (name=="Sokolosky") return "Sokolowsky"; if (name=="Sokolsky") return "Sokolowsky"; if (name=="Sonda") return "Sondra"; if (name=="Stansilav") return "Stanislav"; if (name=="Stefan") return "Stephan"; if (name=="Stell") return "Steel"; if (name=="Tarantilils") return "Tarantilis"; if (name=="Wieblen") return "Weiblen"; if (name=="Xennon") return "Hanson"; if (name=="Yfei") return "Yefei"; if (name=="Oritz") return "Ortiz"; if (name=="Cobin") return "Corbin"; return name; } void nameCorrection(NamePair& name) { if (name.first=="Eric" && name.second=="Hammil") { name.first = "Chris"; name.second = "Hanson"; } if (name.first=="Nick" && name.second=="") { name.first = "Trajce"; name.second = "Nikolov"; } if (name.first=="Julia" && name.second=="Ortiz") { name.first = "Julian"; name.second = "Ortiz"; } if (name.first=="Rune" && name.second=="Schmidt") { name.first = "Rune"; name.second = "Schmidt Jensen"; } if (name.first=="Romano" && name.second=="Jos") { name.first = "Romano"; name.second = "Jos Magacho da Silva"; } if (name.first=="Rommano" && name.second=="Silva") { name.first = "Romano"; name.second = "Jos Magacho da Silva"; } } void lastValidCharacter(const std::string& name, unsigned int& pos,char c) { for(unsigned int i=0;i<pos;++i) { if (name[i]==c) { pos = i; return; } } } void lastValidCharacter(const std::string& name, unsigned int& last) { lastValidCharacter(name, last, '.'); lastValidCharacter(name, last, ','); lastValidCharacter(name, last, '\''); lastValidCharacter(name, last, '/'); lastValidCharacter(name, last, '\\'); lastValidCharacter(name, last, ':'); lastValidCharacter(name, last, ';'); lastValidCharacter(name, last, ')'); } NamePair createName(const std::string& first, const std::string& second) { if (first.empty()) return EmptyNamePair; unsigned int last = first.size(); lastValidCharacter(first, last); if (last==0) return EmptyNamePair; std::string name; name.append(first.begin(), first.begin()+last); if (!validName(name)) return EmptyNamePair; name = typoCorrection(name); if (second.empty()) return NamePair(name,""); if (!validName(second)) return NamePair(name,""); last = second.size(); lastValidCharacter(second, last); if (last>0) { std::string surname(second.begin(), second.begin()+last); surname = typoCorrection(surname); return NamePair(name, surname); } return NamePair(name,""); } bool submissionsSequence(const Words& words, unsigned int& i) { if (i+1>=words.size()) return false; if (words[i]=="From" || words[i]=="from" || words[i]=="From:" || words[i]=="from:" || words[i]=="Added" || words[i]=="Merged" || words[i]=="Integrated") return true; if (i+2>=words.size()) return false; if (words[i]=="submitted" && words[i+1]=="by") { i+=1; return true; } if (words[i]=="Folded" && words[i+1]=="in") { i+=1; return true; } if (words[i]=="Checked" && words[i+1]=="in") { i+=1; return true; } if (i+3>=words.size()) return false; if (words[i]=="sent" && words[i+1]=="in" && words[i+2]=="by") { i+=2; return true; } return false; } void readContributors(NameSet& names, const std::string& file) { std::ifstream fin(file.c_str()); Words words; while(fin) { std::string keyword; fin >> keyword; words.push_back(keyword); } std::string blank_string; for(unsigned int i=0; i< words.size(); ++i) { if (submissionsSequence(words,i)) { if (i+2<words.size() && validName(words[i+1])) { NamePair name = createName(words[i+1], words[i+2]); nameCorrection(name); if (!name.first.empty()) names.insert(name); i+=2; } else if (i+1<words.size() && validName(words[i+1])) { NamePair name = createName(words[i+1], blank_string); nameCorrection(name); if (!name.first.empty()) names.insert(name); i+=1; } } } if (names.size()>1) { for(NameSet::iterator itr = names.begin(); itr != names.end(); ) { if (itr->second.empty()) { NameSet::iterator next_itr = itr; ++next_itr; if (next_itr!=names.end() && itr->first==next_itr->first) { names.erase(itr); itr = next_itr; } else { ++itr; } } else { ++itr; } } } } void buildContributors(NameSet& names) { names.insert(NamePair("Robert","Osfield")); names.insert(NamePair("Don","Burns")); names.insert(NamePair("Marco","Jez")); names.insert(NamePair("Karsten","Weiss")); names.insert(NamePair("Graeme","Harkness")); names.insert(NamePair("Axel","Volley")); names.insert(NamePair("Nikolaus","Hanekamp")); names.insert(NamePair("Kristopher","Bixler")); names.insert(NamePair("Tanguy","Fautr")); names.insert(NamePair("J.E.","Hoffmann")); } int main( int argc, char **argv) { osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); arguments.getApplicationUsage()->addCommandLineOption("-c or --contributors","Print out the contributors list."); arguments.getApplicationUsage()->addCommandLineOption("-r <file> or --read <file>","Read the changelog to generate an estimated contributors list."); std::cout<<osgGetLibraryName()<< " "<< osgGetVersion()<<std::endl<<std::endl; bool printContributors = false; while ( arguments.read("-c") || arguments.read("--contributors")) printContributors = true; std::string changeLog; while ( arguments.read("-r",changeLog) || arguments.read("--read",changeLog)) printContributors = true; // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl; arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions()); return 1; } if (printContributors) { NameSet names; buildContributors(names); if (!changeLog.empty()) { readContributors(names, changeLog); } std::cout<<names.size()<<" Contributors:"<<std::endl<<std::endl; for(NameSet::iterator itr = names.begin(); itr != names.end(); ++itr) { std::cout<<" "<<itr->first<<" "<<itr->second<<std::endl; } } return 0; } <|endoftext|>
<commit_before>80c3e2cf-2e4f-11e5-afcc-28cfe91dbc4b<commit_msg>80ca9019-2e4f-11e5-8c51-28cfe91dbc4b<commit_after>80ca9019-2e4f-11e5-8c51-28cfe91dbc4b<|endoftext|>
<commit_before>5a5c2888-2e3a-11e5-bb9c-c03896053bdd<commit_msg>5a69bf82-2e3a-11e5-a6ba-c03896053bdd<commit_after>5a69bf82-2e3a-11e5-a6ba-c03896053bdd<|endoftext|>
<commit_before>/* * @file MeldBlockCode.cpp * @brief Unique blockCode for any meld program. Target module type is determined from command line by meld.cpp * @autor Pierre Thalamy * @date 20/07/2016 */ #include <iostream> #include <sstream> #include "scheduler.h" #include "network.h" #include "meldBlockCode.h" #include "meldInterpretEvents.h" #include "meldInterpretMessages.h" #include "meldInterpretVM.h" #include "lattice.h" #include "trace.h" using namespace std; using namespace MeldInterpret; ModuleType MeldBlockCode::moduleType; MeldBlockCode::MeldBlockCode(BuildingBlock *host): BlockCode(host) { OUTPUT << "MeldBlockCode constructor" << endl; vm = new MeldInterpretVM(hostBlock); hasWork = true; // mode fastest polling = false; // mode fastest currentLocalDate = 0; // mode fastest } MeldBlockCode::~MeldBlockCode() { delete vm; OUTPUT << "MeldBlockCode destructor" << endl; } void MeldBlockCode::init() { stringstream info; if((vm != NULL)) { for (int i = 0; i < hostBlock->getNbInterfaces(); i++) { vm->neighbors[i] = vm->get_neighbor_ID(i); OUTPUT << "Adding neighbor " << vm->neighbors[i] << " on face " << i << endl; vm->enqueue_face(vm->neighbors[i], i, 1); } BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); if((getScheduler()->getMode() == SCHEDULER_MODE_FASTEST) && !vm->deterministicSet) { vm->deterministicSet = true; /*SetDeterministicModeVMCommand determinismCommand(c, hostBlock->blockId); vm->sendCommand(determinismCommand);*/ info << "deterministic mode set"; getScheduler()->trace(info.str(),hostBlock->blockId); OUTPUT << "deterministic mode enable on the VM " << hostBlock->blockId << endl; } } } void MeldBlockCode::startup() { stringstream info; currentLocalDate = BaseSimulator::getScheduler()->now(); info << " Starting MeldBlockCode in block " << hostBlock->blockId; getScheduler()->trace(info.str(),hostBlock->blockId); init(); } void MeldBlockCode::handleDeterministicMode(/*VMCommand &command*/){ currentLocalDate = max(BaseSimulator::getScheduler()->now(), currentLocalDate); /*if(!hasWork && (command.getType() != VM_COMMAND_STOP)) { hasWork = true; #ifdef TEST_DETER //cout << hostBlock->blockId << " has work again at " << BaseSimulator::getScheduler()->now() << endl; #endif }*/ } void MeldBlockCode::processLocalEvent(EventPtr pev) { stringstream info; assert(vm != NULL); info.str(""); OUTPUT << hostBlock->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now() << " process event " << pev->getEventName() << "(" << pev->eventType << ")" << ", random number : " << pev->randomNumber << endl; #ifdef TEST_DETER cout << hostBlock->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now() << " process event " << pev->getEventName() << "(" << pev->eventType << ")" << ", random number : " << pev->randomNumber << endl; #endif switch (pev->eventType) { case EVENT_COMPUTE_PREDICATE: { //Call the VM function to process one rule vm->processOneRule(); //Add another compute event on condition //if... if(vm->isWaiting()){ // random delay before recomputing a predicate // between 0.1 ms and 1ms int delay = (hostBlock->getNextRandomNumber() % (1000 - 100 +1 )) + 100; BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now()+delay, hostBlock)); } //else info << " Block is no longer waiting"; //info << "Compute predicate event"; } break; case EVENT_STOP: { //getDebugger()->sendTerminateMsg(hostBlock->blockId); delete vm; info << "VM stopped"; } break; case EVENT_ADD_NEIGHBOR: { //Should not be used by itself, presence of another block is tested by P2PNetworkInterface unsigned int face = (std::static_pointer_cast<AddNeighborEvent>(pev))->face; vm->neighbors[face] = (std::static_pointer_cast<AddNeighborEvent>(pev))->target; vm->enqueue_face(vm->neighbors[face], face, 1); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); info << "Add neighbor "<< (std::static_pointer_cast<AddNeighborEvent>(pev))->target << " at face " << lattice->getDirectionString(lattice->getOppositeDirection( (std::static_pointer_cast<AddNeighborEvent>(pev))->face)); } break; case EVENT_REMOVE_NEIGHBOR: { unsigned int face = (std::static_pointer_cast<AddNeighborEvent>(pev))->face; vm->neighbors[face] = VACANT; vm->enqueue_face(vm->neighbors[face], face, -1); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); info << "Remove neighbor at face " << lattice->getDirectionString(lattice->getOppositeDirection(face)); } break; case EVENT_TAP: { vm->enqueue_tap(); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); info << "tapped"; } break; case EVENT_SET_COLOR: { hostBlock->getTime(); //Called by the VM, no need to enqueue things Color color = (std::static_pointer_cast<SetColorEvent>(pev))->color; hostBlock->setColor(color); #ifdef TEST_DETER cout << hostBlock->blockId << " SET_COLOR_EVENT" << endl; #endif info << "set color "<< color; } break; /*The interface being connected is tested in function tuple_send of the MeldInterpVM*/ case EVENT_SEND_MESSAGE: { MessagePtr message = (std::static_pointer_cast<VMSendMessageEvent>(pev))->message; P2PNetworkInterface *interface = (std::static_pointer_cast<VMSendMessageEvent>(pev))->sourceInterface; getScheduler()->schedule( new NetworkInterfaceEnqueueOutgoingEvent(BaseSimulator::getScheduler()->now(), message, interface)); info << "sends a message at face " << lattice->getDirectionString(hostBlock->getDirection(interface)) << " to " << interface->connectedInterface->hostBlock->blockId; } break; case EVENT_RECEIVE_MESSAGE: /*EVENT_NI_RECEIVE: */ { MessagePtr mes = (std::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message; switch(mes->type){ case ADD_TUPLE_MSG_ID: getScheduler()->schedule( new AddTupleEvent(BaseSimulator::getScheduler()->now(), hostBlock, std::static_pointer_cast<AddTupleMessage>(mes)->tuple, hostBlock->getDirection(mes->sourceInterface->connectedInterface))); break; case REMOVE_TUPLE_MSG_ID: getScheduler()->schedule( new RemoveTupleEvent(BaseSimulator::getScheduler()->now(), hostBlock, std::static_pointer_cast<RemoveTupleMessage>(mes)->tuple, hostBlock->getDirection(mes->sourceInterface->connectedInterface))); break; } #ifdef TEST_DETER cout << "message received from " << command->sourceInterface->hostBlock->blockId << endl; #endif //info << "message received at face " << NeighborDirection::getString(hostBlock->getDirection(mes->sourceInterface->connectedInterface)) << " from " << mes->sourceInterface->hostBlock->blockId; } break; case EVENT_ACCEL: { /*Not written yet, have to check how the vm handle accel (tuple, etc)*/ info << "accel"; } break; case EVENT_SHAKE: { /*Not written yet, same as accel*/ info << "shake"; } break; case EVENT_SET_DETERMINISTIC: { /*Not sure how to handle that with MeldInterp*/ OUTPUT << "VM set in deterministic mode " << hostBlock->blockId << endl; info << "VM set in deterministic mode"; } break; case EVENT_END_POLL: { polling = false; /*Not written yet Need to check what this is for*/ info << "Polling time period ended"; } break; case EVENT_ADD_TUPLE: this->vm->receive_tuple(1, std::static_pointer_cast<AddTupleEvent>(pev)->tuple, std::static_pointer_cast<AddTupleEvent>(pev)->face); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); //info << "Adding tuple"; break; case EVENT_REMOVE_TUPLE: this->vm->receive_tuple(-1, std::static_pointer_cast<RemoveTupleEvent>(pev)->tuple, std::static_pointer_cast<RemoveTupleEvent>(pev)->face); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); //info << "Removing tuple"; break; default: ERRPUT << "*** ERROR *** : unknown local event"; break; } if(info.str() != "") { getScheduler()->trace(info.str(),hostBlock->blockId); } } BlockCode* MeldBlockCode::buildNewBlockCode(BuildingBlock *host) { return(new MeldBlockCode(host)); } <commit_msg>Fix issues due to the merge operation with the refactoring branch.<commit_after>/* * @file MeldBlockCode.cpp * @brief Unique blockCode for any meld program. Target module type is determined from command line by meld.cpp * @autor Pierre Thalamy * @date 20/07/2016 */ #include <iostream> #include <sstream> #include "scheduler.h" #include "network.h" #include "meldBlockCode.h" #include "meldInterpretEvents.h" #include "meldInterpretMessages.h" #include "meldInterpretVM.h" #include "lattice.h" #include "trace.h" using namespace std; using namespace MeldInterpret; ModuleType MeldBlockCode::moduleType; MeldBlockCode::MeldBlockCode(BuildingBlock *host): BlockCode(host) { OUTPUT << "MeldBlockCode constructor" << endl; vm = new MeldInterpretVM(hostBlock); hasWork = true; // mode fastest polling = false; // mode fastest currentLocalDate = 0; // mode fastest } MeldBlockCode::~MeldBlockCode() { delete vm; OUTPUT << "MeldBlockCode destructor" << endl; } void MeldBlockCode::init() { stringstream info; if((vm != NULL)) { for (int i = 0; i < hostBlock->getNbInterfaces(); i++) { vm->neighbors[i] = vm->get_neighbor_ID(i); OUTPUT << "Adding neighbor " << vm->neighbors[i] << " on face " << i << endl; vm->enqueue_face(vm->neighbors[i], i, 1); } BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); if((getScheduler()->getMode() == SCHEDULER_MODE_FASTEST) && !vm->deterministicSet) { vm->deterministicSet = true; /*SetDeterministicModeVMCommand determinismCommand(c, hostBlock->blockId); vm->sendCommand(determinismCommand);*/ info << "deterministic mode set"; getScheduler()->trace(info.str(),hostBlock->blockId); OUTPUT << "deterministic mode enable on the VM " << hostBlock->blockId << endl; } } } void MeldBlockCode::startup() { stringstream info; currentLocalDate = BaseSimulator::getScheduler()->now(); info << " Starting MeldBlockCode in block " << hostBlock->blockId; getScheduler()->trace(info.str(),hostBlock->blockId); init(); } void MeldBlockCode::handleDeterministicMode(/*VMCommand &command*/){ currentLocalDate = max(BaseSimulator::getScheduler()->now(), currentLocalDate); /*if(!hasWork && (command.getType() != VM_COMMAND_STOP)) { hasWork = true; #ifdef TEST_DETER //cout << hostBlock->blockId << " has work again at " << BaseSimulator::getScheduler()->now() << endl; #endif }*/ } void MeldBlockCode::processLocalEvent(EventPtr pev) { stringstream info; assert(vm != NULL); info.str(""); OUTPUT << hostBlock->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now() << " process event " << pev->getEventName() << "(" << pev->eventType << ")" << ", random number : " << pev->randomNumber << endl; #ifdef TEST_DETER cout << hostBlock->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now() << " process event " << pev->getEventName() << "(" << pev->eventType << ")" << ", random number : " << pev->randomNumber << endl; #endif switch (pev->eventType) { case EVENT_COMPUTE_PREDICATE: { //Call the VM function to process one rule vm->processOneRule(); //Add another compute event on condition //if... if(vm->isWaiting()){ // random delay before recomputing a predicate // between 0.1 ms and 1ms int delay = (hostBlock->getNextRandomNumber() % (1000 - 100 +1 )) + 100; BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now()+delay, hostBlock)); } //else info << " Block is no longer waiting"; //info << "Compute predicate event"; } break; case EVENT_STOP: { //getDebugger()->sendTerminateMsg(hostBlock->blockId); delete vm; info << "VM stopped"; } break; case EVENT_ADD_NEIGHBOR: { //Should not be used by itself, presence of another block is tested by P2PNetworkInterface unsigned int face = (std::static_pointer_cast<AddNeighborEvent>(pev))->face; vm->neighbors[face] = (std::static_pointer_cast<AddNeighborEvent>(pev))->target; vm->enqueue_face(vm->neighbors[face], face, 1); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); info << "Add neighbor "<< (std::static_pointer_cast<AddNeighborEvent>(pev))->target << " at face " << lattice->getDirectionString(lattice->getOppositeDirection( (std::static_pointer_cast<AddNeighborEvent>(pev))->face)); } break; case EVENT_REMOVE_NEIGHBOR: { unsigned int face = (std::static_pointer_cast<AddNeighborEvent>(pev))->face; vm->neighbors[face] = VACANT; vm->enqueue_face(vm->neighbors[face], face, -1); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); info << "Remove neighbor at face " << lattice->getDirectionString(lattice->getOppositeDirection(face)); } break; case EVENT_TAP: { vm->enqueue_tap(); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); info << "tapped"; } break; case EVENT_SET_COLOR: { hostBlock->getLocalTime(); //Called by the VM, no need to enqueue things Color color = (std::static_pointer_cast<SetColorEvent>(pev))->color; hostBlock->setColor(color); #ifdef TEST_DETER cout << hostBlock->blockId << " SET_COLOR_EVENT" << endl; #endif info << "set color "<< color; } break; /*The interface being connected is tested in function tuple_send of the MeldInterpVM*/ case EVENT_SEND_MESSAGE: { MessagePtr message = (std::static_pointer_cast<VMSendMessageEvent>(pev))->message; P2PNetworkInterface *interface = (std::static_pointer_cast<VMSendMessageEvent>(pev))->sourceInterface; getScheduler()->schedule( new NetworkInterfaceEnqueueOutgoingEvent(BaseSimulator::getScheduler()->now(), message, interface)); info << "sends a message at face " << lattice->getDirectionString(hostBlock->getDirection(interface)) << " to " << interface->connectedInterface->hostBlock->blockId; } break; case EVENT_RECEIVE_MESSAGE: /*EVENT_NI_RECEIVE: */ { MessagePtr mes = (std::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message; switch(mes->type){ case ADD_TUPLE_MSG_ID: getScheduler()->schedule( new AddTupleEvent(BaseSimulator::getScheduler()->now(), hostBlock, std::static_pointer_cast<AddTupleMessage>(mes)->tuple, hostBlock->getDirection(mes->sourceInterface->connectedInterface))); break; case REMOVE_TUPLE_MSG_ID: getScheduler()->schedule( new RemoveTupleEvent(BaseSimulator::getScheduler()->now(), hostBlock, std::static_pointer_cast<RemoveTupleMessage>(mes)->tuple, hostBlock->getDirection(mes->sourceInterface->connectedInterface))); break; } #ifdef TEST_DETER cout << "message received from " << command->sourceInterface->hostBlock->blockId << endl; #endif //info << "message received at face " << NeighborDirection::getString(hostBlock->getDirection(mes->sourceInterface->connectedInterface)) << " from " << mes->sourceInterface->hostBlock->blockId; } break; case EVENT_ACCEL: { /*Not written yet, have to check how the vm handle accel (tuple, etc)*/ info << "accel"; } break; case EVENT_SHAKE: { /*Not written yet, same as accel*/ info << "shake"; } break; case EVENT_SET_DETERMINISTIC: { /*Not sure how to handle that with MeldInterp*/ OUTPUT << "VM set in deterministic mode " << hostBlock->blockId << endl; info << "VM set in deterministic mode"; } break; case EVENT_END_POLL: { polling = false; /*Not written yet Need to check what this is for*/ info << "Polling time period ended"; } break; case EVENT_ADD_TUPLE: this->vm->receive_tuple(1, std::static_pointer_cast<AddTupleEvent>(pev)->tuple, std::static_pointer_cast<AddTupleEvent>(pev)->face); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); //info << "Adding tuple"; break; case EVENT_REMOVE_TUPLE: this->vm->receive_tuple(-1, std::static_pointer_cast<RemoveTupleEvent>(pev)->tuple, std::static_pointer_cast<RemoveTupleEvent>(pev)->face); BaseSimulator::getScheduler()->schedule( new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock)); //info << "Removing tuple"; break; default: ERRPUT << "*** ERROR *** : unknown local event"; break; } if(info.str() != "") { getScheduler()->trace(info.str(),hostBlock->blockId); } } BlockCode* MeldBlockCode::buildNewBlockCode(BuildingBlock *host) { return(new MeldBlockCode(host)); } <|endoftext|>
<commit_before>aa62f0ac-35ca-11e5-9ef9-6c40088e03e4<commit_msg>aa6a53ec-35ca-11e5-ba1a-6c40088e03e4<commit_after>aa6a53ec-35ca-11e5-ba1a-6c40088e03e4<|endoftext|>
<commit_before>ca481866-35ca-11e5-9336-6c40088e03e4<commit_msg>ca4e5280-35ca-11e5-9e5e-6c40088e03e4<commit_after>ca4e5280-35ca-11e5-9e5e-6c40088e03e4<|endoftext|>
<commit_before>75f9180c-2d53-11e5-baeb-247703a38240<commit_msg>75f9985e-2d53-11e5-baeb-247703a38240<commit_after>75f9985e-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>760c4b0c-2d53-11e5-baeb-247703a38240<commit_msg>760cccb2-2d53-11e5-baeb-247703a38240<commit_after>760cccb2-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>856279aa-2d15-11e5-af21-0401358ea401<commit_msg>856279ab-2d15-11e5-af21-0401358ea401<commit_after>856279ab-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>a1df2f2e-35ca-11e5-a62c-6c40088e03e4<commit_msg>a1e629a8-35ca-11e5-a39c-6c40088e03e4<commit_after>a1e629a8-35ca-11e5-a39c-6c40088e03e4<|endoftext|>