text
stringlengths
54
60.6k
<commit_before>#ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS #define DEGREES_TO_RADIANS(x) (x * PI / 180.0f) #endif #include "ascii_grid_loader.hpp" #include "code/ylikuutio/triangulation/quad_triangulation.hpp" #include "code/ylikuutio/string/ylikuutio_string.hpp" #include "code/ylikuutio/common/globals.hpp" #include "code/ylikuutio/common/global_variables.hpp" // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc. #include <iostream> // std::cout, std::cin, std::cerr #include <stdint.h> // uint32_t etc. #include <string> // std::string, std::stoi #include <vector> // std::vector namespace loaders { bool load_ascii_grid( std::string ascii_grid_file_name, std::vector<glm::vec3>& out_vertices, std::vector<glm::vec2>& out_UVs, std::vector<glm::vec3>& out_normals, std::string triangulation_type) { // Beginning of `L4133D.asc`. // // ncols 3000 // nrows 3000 // xllcorner 386000.000000000000 // yllcorner 6672000.000000000000 // cellsize 2.000000000000 // NODATA_value -9999.000 // 34.315 34.467 34.441 34.260 33.972 33.564 33.229 33.130 33.102 33.024 32.902 32.669 32.305 32.013 31.937 31.893 31.831 31.832 std::cout << "Loading ascii grid file " << ascii_grid_file_name << " ...\n"; // Open the file const char* char_ascii_grid_file_name = ascii_grid_file_name.c_str(); std::FILE* file = std::fopen(char_ascii_grid_file_name, "rb"); if (!file) { std::cerr << ascii_grid_file_name << " could not be opened.\n"; return false; } // Find out file size. if (std::fseek(file, 0, SEEK_END) != 0) { std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n"; std::fclose(file); return false; } uint64_t file_size = std::ftell(file); // Move file pointer to the beginning of file. if (fseek(file, 0, SEEK_SET) != 0) { std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n"; std::fclose(file); return false; } // Reserve enough memory. char* point_data = new char[file_size]; if (point_data == nullptr) { std::cerr << "Reserving memory for point data failed.\n"; std::fclose(file); return false; } char* point_data_pointer = point_data; // Read the point data from the file into the buffer. std::fread(point_data, 1, file_size, file); // Everything is in memory now, the file can be closed std::fclose(file); // All possible block identifier strings. std::vector<std::string> number_strings_vector = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } int32_t image_width = string::extract_int32_t_value_from_string(point_data_pointer, (char*) " \n", (const char*) "ncols"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } int32_t image_height = string::extract_int32_t_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nrows"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } float xllcorner = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "xllcorner"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } float yllcorner = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "yllcorner"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } float cellsize = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "cellsize"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } float nodata_value = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nodata_value"); uint32_t image_width_in_use = 3000; // should be 3000. uint32_t image_height_in_use = 2000; float* vertex_data; vertex_data = new float[image_width_in_use * image_height_in_use]; float* vertex_pointer; vertex_pointer = vertex_data; // start processing image_data. for (uint32_t z = 0; z < image_height_in_use; z++) { for (uint32_t x = 0; x < image_width_in_use; x++) { while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } *vertex_pointer++ = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) nullptr); } } delete point_data; std::cout << "Triangulating ascii grid data.\n"; TriangulateQuadsStruct triangulate_quads_struct; // triangulate_quads_struct.image_width = image_width; triangulate_quads_struct.image_width = image_width_in_use; triangulate_quads_struct.image_height = image_height_in_use; triangulate_quads_struct.triangulation_type = triangulation_type; triangulate_quads_struct.sphere_radius = NAN; triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call. bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals); delete vertex_data; return true; } } <commit_msg>Bugfix: `cerr` message, `delete` and `return false` if `new` fails.<commit_after>#ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS #define DEGREES_TO_RADIANS(x) (x * PI / 180.0f) #endif #include "ascii_grid_loader.hpp" #include "code/ylikuutio/triangulation/quad_triangulation.hpp" #include "code/ylikuutio/string/ylikuutio_string.hpp" #include "code/ylikuutio/common/globals.hpp" #include "code/ylikuutio/common/global_variables.hpp" // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc. #include <iostream> // std::cout, std::cin, std::cerr #include <stdint.h> // uint32_t etc. #include <string> // std::string, std::stoi #include <vector> // std::vector namespace loaders { bool load_ascii_grid( std::string ascii_grid_file_name, std::vector<glm::vec3>& out_vertices, std::vector<glm::vec2>& out_UVs, std::vector<glm::vec3>& out_normals, std::string triangulation_type) { // Beginning of `L4133D.asc`. // // ncols 3000 // nrows 3000 // xllcorner 386000.000000000000 // yllcorner 6672000.000000000000 // cellsize 2.000000000000 // NODATA_value -9999.000 // 34.315 34.467 34.441 34.260 33.972 33.564 33.229 33.130 33.102 33.024 32.902 32.669 32.305 32.013 31.937 31.893 31.831 31.832 std::cout << "Loading ascii grid file " << ascii_grid_file_name << " ...\n"; // Open the file const char* char_ascii_grid_file_name = ascii_grid_file_name.c_str(); std::FILE* file = std::fopen(char_ascii_grid_file_name, "rb"); if (!file) { std::cerr << ascii_grid_file_name << " could not be opened.\n"; return false; } // Find out file size. if (std::fseek(file, 0, SEEK_END) != 0) { std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n"; std::fclose(file); return false; } uint64_t file_size = std::ftell(file); // Move file pointer to the beginning of file. if (fseek(file, 0, SEEK_SET) != 0) { std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n"; std::fclose(file); return false; } // Reserve enough memory. char* point_data = new char[file_size]; if (point_data == nullptr) { std::cerr << "Reserving memory for point data failed.\n"; std::fclose(file); return false; } char* point_data_pointer = point_data; // Read the point data from the file into the buffer. std::fread(point_data, 1, file_size, file); // Everything is in memory now, the file can be closed std::fclose(file); // All possible block identifier strings. std::vector<std::string> number_strings_vector = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } int32_t image_width = string::extract_int32_t_value_from_string(point_data_pointer, (char*) " \n", (const char*) "ncols"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } int32_t image_height = string::extract_int32_t_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nrows"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } float xllcorner = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "xllcorner"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } float yllcorner = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "yllcorner"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } float cellsize = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "cellsize"); while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } float nodata_value = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nodata_value"); uint32_t image_width_in_use = 3000; // should be 3000. uint32_t image_height_in_use = 2000; float* vertex_data; vertex_data = new float[image_width_in_use * image_height_in_use]; if (vertex_data == nullptr) { std::cerr << "Reserving memory for vertex data failed.\n"; delete point_data; return false; } float* vertex_pointer; vertex_pointer = vertex_data; // start processing image_data. for (uint32_t z = 0; z < image_height_in_use; z++) { for (uint32_t x = 0; x < image_width_in_use; x++) { while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector)) { point_data_pointer++; } *vertex_pointer++ = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) nullptr); } } delete point_data; std::cout << "Triangulating ascii grid data.\n"; TriangulateQuadsStruct triangulate_quads_struct; // triangulate_quads_struct.image_width = image_width; triangulate_quads_struct.image_width = image_width_in_use; triangulate_quads_struct.image_height = image_height_in_use; triangulate_quads_struct.triangulation_type = triangulation_type; triangulate_quads_struct.sphere_radius = NAN; triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call. bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals); delete vertex_data; return true; } } <|endoftext|>
<commit_before>c12de298-2e4e-11e5-9284-b827eb9e62be<commit_msg>c132e928-2e4e-11e5-9284-b827eb9e62be<commit_after>c132e928-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0e0730ec-2e4f-11e5-9284-b827eb9e62be<commit_msg>0e0c35b0-2e4f-11e5-9284-b827eb9e62be<commit_after>0e0c35b0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0b761962-2e4d-11e5-9284-b827eb9e62be<commit_msg>0b7b2664-2e4d-11e5-9284-b827eb9e62be<commit_after>0b7b2664-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ea22d4d8-2e4e-11e5-9284-b827eb9e62be<commit_msg>ea2808ea-2e4e-11e5-9284-b827eb9e62be<commit_after>ea2808ea-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c9251116-2e4d-11e5-9284-b827eb9e62be<commit_msg>c92a0f5e-2e4d-11e5-9284-b827eb9e62be<commit_after>c92a0f5e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f1d27672-2e4c-11e5-9284-b827eb9e62be<commit_msg>f1d77dd4-2e4c-11e5-9284-b827eb9e62be<commit_after>f1d77dd4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fcf63f92-2e4d-11e5-9284-b827eb9e62be<commit_msg>fcfb3376-2e4d-11e5-9284-b827eb9e62be<commit_after>fcfb3376-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fff5c39e-2e4c-11e5-9284-b827eb9e62be<commit_msg>fffab250-2e4c-11e5-9284-b827eb9e62be<commit_after>fffab250-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>97720e62-2e4d-11e5-9284-b827eb9e62be<commit_msg>97770552-2e4d-11e5-9284-b827eb9e62be<commit_after>97770552-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f97e3a04-2e4d-11e5-9284-b827eb9e62be<commit_msg>f98349a4-2e4d-11e5-9284-b827eb9e62be<commit_after>f98349a4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3d1822fc-2e4e-11e5-9284-b827eb9e62be<commit_msg>3d1d32e2-2e4e-11e5-9284-b827eb9e62be<commit_after>3d1d32e2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e53bb738-2e4d-11e5-9284-b827eb9e62be<commit_msg>e540b83c-2e4d-11e5-9284-b827eb9e62be<commit_after>e540b83c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d7f22e4e-2e4e-11e5-9284-b827eb9e62be<commit_msg>d7f72994-2e4e-11e5-9284-b827eb9e62be<commit_after>d7f72994-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>805cfb78-2e4e-11e5-9284-b827eb9e62be<commit_msg>80620be0-2e4e-11e5-9284-b827eb9e62be<commit_after>80620be0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2f992690-2e4d-11e5-9284-b827eb9e62be<commit_msg>2f9e3fa4-2e4d-11e5-9284-b827eb9e62be<commit_after>2f9e3fa4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9ce55106-2e4d-11e5-9284-b827eb9e62be<commit_msg>9cea4a94-2e4d-11e5-9284-b827eb9e62be<commit_after>9cea4a94-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>56f624da-2e4e-11e5-9284-b827eb9e62be<commit_msg>56fb3c5e-2e4e-11e5-9284-b827eb9e62be<commit_after>56fb3c5e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>14899d84-2e4e-11e5-9284-b827eb9e62be<commit_msg>148e9564-2e4e-11e5-9284-b827eb9e62be<commit_after>148e9564-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cd5e4e90-2e4e-11e5-9284-b827eb9e62be<commit_msg>cd7032c2-2e4e-11e5-9284-b827eb9e62be<commit_after>cd7032c2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>97876ad6-2e4e-11e5-9284-b827eb9e62be<commit_msg>979c96c2-2e4e-11e5-9284-b827eb9e62be<commit_after>979c96c2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bf0f1f92-2e4c-11e5-9284-b827eb9e62be<commit_msg>bf142474-2e4c-11e5-9284-b827eb9e62be<commit_after>bf142474-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fd40d3fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>fd45cc4c-2e4d-11e5-9284-b827eb9e62be<commit_after>fd45cc4c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0626a9e4-2e4e-11e5-9284-b827eb9e62be<commit_msg>062bb754-2e4e-11e5-9284-b827eb9e62be<commit_after>062bb754-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>166a0930-2e4f-11e5-9284-b827eb9e62be<commit_msg>166effda-2e4f-11e5-9284-b827eb9e62be<commit_after>166effda-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bacec0d0-2e4d-11e5-9284-b827eb9e62be<commit_msg>bad3b86a-2e4d-11e5-9284-b827eb9e62be<commit_after>bad3b86a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d70c61b6-2e4e-11e5-9284-b827eb9e62be<commit_msg>d7115e78-2e4e-11e5-9284-b827eb9e62be<commit_after>d7115e78-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2a511858-2e4f-11e5-9284-b827eb9e62be<commit_msg>2a562dca-2e4f-11e5-9284-b827eb9e62be<commit_after>2a562dca-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f704e300-2e4c-11e5-9284-b827eb9e62be<commit_msg>f70a1492-2e4c-11e5-9284-b827eb9e62be<commit_after>f70a1492-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>661b4fb2-2e4e-11e5-9284-b827eb9e62be<commit_msg>66205e6c-2e4e-11e5-9284-b827eb9e62be<commit_after>66205e6c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8146953a-2e4e-11e5-9284-b827eb9e62be<commit_msg>814b9e86-2e4e-11e5-9284-b827eb9e62be<commit_after>814b9e86-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>34757ad8-2e4d-11e5-9284-b827eb9e62be<commit_msg>347a8866-2e4d-11e5-9284-b827eb9e62be<commit_after>347a8866-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>15483298-2e4f-11e5-9284-b827eb9e62be<commit_msg>154d3d92-2e4f-11e5-9284-b827eb9e62be<commit_after>154d3d92-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d4009146-2e4d-11e5-9284-b827eb9e62be<commit_msg>d4058f5c-2e4d-11e5-9284-b827eb9e62be<commit_after>d4058f5c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>edb4e096-2e4e-11e5-9284-b827eb9e62be<commit_msg>edb9da6a-2e4e-11e5-9284-b827eb9e62be<commit_after>edb9da6a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>06d6f2b4-2e4d-11e5-9284-b827eb9e62be<commit_msg>06dc0344-2e4d-11e5-9284-b827eb9e62be<commit_after>06dc0344-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6db756ea-2e4d-11e5-9284-b827eb9e62be<commit_msg>6dbc5fe6-2e4d-11e5-9284-b827eb9e62be<commit_after>6dbc5fe6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>67f6a804-2e4e-11e5-9284-b827eb9e62be<commit_msg>67fbb48e-2e4e-11e5-9284-b827eb9e62be<commit_after>67fbb48e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1e2ce3e0-2e4f-11e5-9284-b827eb9e62be<commit_msg>1e31dcc4-2e4f-11e5-9284-b827eb9e62be<commit_after>1e31dcc4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e1d3f6aa-2e4d-11e5-9284-b827eb9e62be<commit_msg>e1d90032-2e4d-11e5-9284-b827eb9e62be<commit_after>e1d90032-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4c309ab2-2e4e-11e5-9284-b827eb9e62be<commit_msg>4c35b07e-2e4e-11e5-9284-b827eb9e62be<commit_after>4c35b07e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d0e1b43c-2e4c-11e5-9284-b827eb9e62be<commit_msg>d0e6dab6-2e4c-11e5-9284-b827eb9e62be<commit_after>d0e6dab6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a12249da-2e4e-11e5-9284-b827eb9e62be<commit_msg>a12747e6-2e4e-11e5-9284-b827eb9e62be<commit_after>a12747e6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ef59dbfa-2e4d-11e5-9284-b827eb9e62be<commit_msg>ef5f45cc-2e4d-11e5-9284-b827eb9e62be<commit_after>ef5f45cc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7a103268-2e4d-11e5-9284-b827eb9e62be<commit_msg>7a152872-2e4d-11e5-9284-b827eb9e62be<commit_after>7a152872-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5216d34c-2e4e-11e5-9284-b827eb9e62be<commit_msg>521c0060-2e4e-11e5-9284-b827eb9e62be<commit_after>521c0060-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1504179e-2e4e-11e5-9284-b827eb9e62be<commit_msg>15091924-2e4e-11e5-9284-b827eb9e62be<commit_after>15091924-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3904a686-2e4e-11e5-9284-b827eb9e62be<commit_msg>39099c40-2e4e-11e5-9284-b827eb9e62be<commit_after>39099c40-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d53f9858-2e4e-11e5-9284-b827eb9e62be<commit_msg>d5449510-2e4e-11e5-9284-b827eb9e62be<commit_after>d5449510-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6c9ec990-2e4e-11e5-9284-b827eb9e62be<commit_msg>6ca3d480-2e4e-11e5-9284-b827eb9e62be<commit_after>6ca3d480-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aee005f8-2e4e-11e5-9284-b827eb9e62be<commit_msg>aee5792a-2e4e-11e5-9284-b827eb9e62be<commit_after>aee5792a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>da99146a-2e4d-11e5-9284-b827eb9e62be<commit_msg>da9e254a-2e4d-11e5-9284-b827eb9e62be<commit_after>da9e254a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a4a0fec6-2e4e-11e5-9284-b827eb9e62be<commit_msg>a4a60a38-2e4e-11e5-9284-b827eb9e62be<commit_after>a4a60a38-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>18b1e44c-2e4f-11e5-9284-b827eb9e62be<commit_msg>18b705e4-2e4f-11e5-9284-b827eb9e62be<commit_after>18b705e4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fb68d3ca-2e4c-11e5-9284-b827eb9e62be<commit_msg>fb6dca06-2e4c-11e5-9284-b827eb9e62be<commit_after>fb6dca06-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8dfc2e8a-2e4d-11e5-9284-b827eb9e62be<commit_msg>8e012ef8-2e4d-11e5-9284-b827eb9e62be<commit_after>8e012ef8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>250ff2c6-2e4d-11e5-9284-b827eb9e62be<commit_msg>2514e8c6-2e4d-11e5-9284-b827eb9e62be<commit_after>2514e8c6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f828ee98-2e4c-11e5-9284-b827eb9e62be<commit_msg>f82dfe7e-2e4c-11e5-9284-b827eb9e62be<commit_after>f82dfe7e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c2814c0c-2e4e-11e5-9284-b827eb9e62be<commit_msg>c2864400-2e4e-11e5-9284-b827eb9e62be<commit_after>c2864400-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cbe0ef8e-2e4c-11e5-9284-b827eb9e62be<commit_msg>cbe5e4c6-2e4c-11e5-9284-b827eb9e62be<commit_after>cbe5e4c6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c3a260f0-2e4c-11e5-9284-b827eb9e62be<commit_msg>c3a75088-2e4c-11e5-9284-b827eb9e62be<commit_after>c3a75088-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a7788430-2e4d-11e5-9284-b827eb9e62be<commit_msg>a77d760c-2e4d-11e5-9284-b827eb9e62be<commit_after>a77d760c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ea0d0784-2e4e-11e5-9284-b827eb9e62be<commit_msg>ea123092-2e4e-11e5-9284-b827eb9e62be<commit_after>ea123092-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e4abe526-2e4e-11e5-9284-b827eb9e62be<commit_msg>e4b0f598-2e4e-11e5-9284-b827eb9e62be<commit_after>e4b0f598-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5643c4fc-2e4e-11e5-9284-b827eb9e62be<commit_msg>5648da6e-2e4e-11e5-9284-b827eb9e62be<commit_after>5648da6e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a796da42-2e4e-11e5-9284-b827eb9e62be<commit_msg>a79bec58-2e4e-11e5-9284-b827eb9e62be<commit_after>a79bec58-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>56090c64-2e4d-11e5-9284-b827eb9e62be<commit_msg>560e0e80-2e4d-11e5-9284-b827eb9e62be<commit_after>560e0e80-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>06d4ce6a-2e4f-11e5-9284-b827eb9e62be<commit_msg>06d9cdc0-2e4f-11e5-9284-b827eb9e62be<commit_after>06d9cdc0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6aba45c8-2e4e-11e5-9284-b827eb9e62be<commit_msg>6abf9212-2e4e-11e5-9284-b827eb9e62be<commit_after>6abf9212-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fb36ee28-2e4c-11e5-9284-b827eb9e62be<commit_msg>fb3be1e4-2e4c-11e5-9284-b827eb9e62be<commit_after>fb3be1e4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9c6b94c8-2e4e-11e5-9284-b827eb9e62be<commit_msg>9c709914-2e4e-11e5-9284-b827eb9e62be<commit_after>9c709914-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e91b5c88-2e4c-11e5-9284-b827eb9e62be<commit_msg>e9205a76-2e4c-11e5-9284-b827eb9e62be<commit_after>e9205a76-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>388d0040-2e4e-11e5-9284-b827eb9e62be<commit_msg>3891f23a-2e4e-11e5-9284-b827eb9e62be<commit_after>3891f23a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d26d8694-2e4e-11e5-9284-b827eb9e62be<commit_msg>d272872a-2e4e-11e5-9284-b827eb9e62be<commit_after>d272872a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cb4c34b0-2e4d-11e5-9284-b827eb9e62be<commit_msg>cb512d12-2e4d-11e5-9284-b827eb9e62be<commit_after>cb512d12-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3b95c2fa-2e4d-11e5-9284-b827eb9e62be<commit_msg>3b9ad11e-2e4d-11e5-9284-b827eb9e62be<commit_after>3b9ad11e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c38e9de0-2e4c-11e5-9284-b827eb9e62be<commit_msg>c39388f0-2e4c-11e5-9284-b827eb9e62be<commit_after>c39388f0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0c23add2-2e4f-11e5-9284-b827eb9e62be<commit_msg>0c28a09e-2e4f-11e5-9284-b827eb9e62be<commit_after>0c28a09e-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>725710dc-2e4d-11e5-9284-b827eb9e62be<commit_msg>725c0920-2e4d-11e5-9284-b827eb9e62be<commit_after>725c0920-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>36c79292-2e4f-11e5-9284-b827eb9e62be<commit_msg>36cca232-2e4f-11e5-9284-b827eb9e62be<commit_after>36cca232-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a7164ce2-2e4e-11e5-9284-b827eb9e62be<commit_msg>a71bcf3c-2e4e-11e5-9284-b827eb9e62be<commit_after>a71bcf3c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fedb5744-2e4c-11e5-9284-b827eb9e62be<commit_msg>fee04b64-2e4c-11e5-9284-b827eb9e62be<commit_after>fee04b64-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>74d68a12-2e4e-11e5-9284-b827eb9e62be<commit_msg>74db9c82-2e4e-11e5-9284-b827eb9e62be<commit_after>74db9c82-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4d23c7a6-2e4d-11e5-9284-b827eb9e62be<commit_msg>4d28d886-2e4d-11e5-9284-b827eb9e62be<commit_after>4d28d886-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3721c6ea-2e4f-11e5-9284-b827eb9e62be<commit_msg>3726be16-2e4f-11e5-9284-b827eb9e62be<commit_after>3726be16-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b258b392-2e4e-11e5-9284-b827eb9e62be<commit_msg>b25da6ae-2e4e-11e5-9284-b827eb9e62be<commit_after>b25da6ae-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d643dab6-2e4e-11e5-9284-b827eb9e62be<commit_msg>d648d7fa-2e4e-11e5-9284-b827eb9e62be<commit_after>d648d7fa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #include <limits.h> #include <sys/stat.h> #ifndef _WIN32 #include <sys/resource.h> #include <unistd.h> #else //#include <TlHelp32.h> #include <windows.h> #include <io.h> #endif #include <stdexcept> #include <signal.h> #include "Util/util.h" #include "Util/File.h" #include "Util/logger.h" #include "Util/uv_errno.h" #include "Thread/WorkThreadPool.h" #include "Process.h" using namespace toolkit; void Process::run(const string &cmd, const string &log_file_tmp) { kill(2000); #ifdef _WIN32 STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; string log_file; if (log_file_tmp.empty()) { //未指定子进程日志文件时,重定向至/dev/null log_file = "NUL"; } else { log_file = StrPrinter << log_file_tmp << "." << getCurrentMillisecond(); } //重定向shell日志至文件 auto fp = File::create_file(log_file.data(), "ab"); if (!fp) { fprintf(stderr, "open log file %s failed:%d(%s)\r\n", log_file.data(), get_uv_error(), get_uv_errmsg()); } else { auto log_fd = (HANDLE)(_get_osfhandle(fileno(fp))); // dup to stdout and stderr. si.wShowWindow = SW_HIDE; // STARTF_USESHOWWINDOW:The wShowWindow member contains additional information. // STARTF_USESTDHANDLES:The hStdInput, hStdOutput, and hStdError members contain additional information. si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.hStdError = log_fd; si.hStdOutput = log_fd; } LPTSTR lpDir = const_cast<char*>(cmd.data()); if (CreateProcess(NULL, lpDir, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)){ //下面两行关闭句柄,解除本进程和新进程的关系,不然有可能 不小心调用TerminateProcess函数关掉子进程 CloseHandle(pi.hThread); _pid = pi.dwProcessId; _handle = pi.hProcess; fprintf(fp, "\r\n\r\n#### pid=%d,cmd=%s #####\r\n\r\n", _pid, cmd.data()); InfoL << "start child process " << _pid << ", log file:" << log_file; } else { WarnL << "start child process fail: " << get_uv_errmsg(); } fclose(fp); #else string log_file; if (log_file_tmp.empty()) { //未指定子进程日志文件时,重定向至/dev/null log_file = "/dev/null"; } else { log_file = StrPrinter << log_file_tmp << "." << getpid(); } _pid = fork(); if (_pid < 0) { throw std::runtime_error(StrPrinter << "fork child process failed,err:" << get_uv_errmsg()); } if (_pid == 0) { //子进程关闭core文件生成 struct rlimit rlim = {0, 0}; setrlimit(RLIMIT_CORE, &rlim); //在启动子进程时,暂时禁用SIGINT、SIGTERM信号 signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); //重定向shell日志至文件 auto fp = File::create_file(log_file.data(), "ab"); if (!fp) { fprintf(stderr, "open log file %s failed:%d(%s)\r\n", log_file.data(), get_uv_error(), get_uv_errmsg()); } else { auto log_fd = fileno(fp); // dup to stdout and stderr. if (dup2(log_fd, STDOUT_FILENO) < 0) { fprintf(stderr, "dup2 stdout file %s failed:%d(%s)\r\n", log_file.data(), get_uv_error(), get_uv_errmsg()); } if (dup2(log_fd, STDERR_FILENO) < 0) { fprintf(stderr, "dup2 stderr file %s failed:%d(%s)\r\n", log_file.data(), get_uv_error(), get_uv_errmsg()); } // 关闭日志文件 ::fclose(fp); } fprintf(stderr, "\r\n\r\n#### pid=%d,cmd=%s #####\r\n\r\n", getpid(), cmd.data()); //关闭父进程继承的fd for (int i = 3; i < 1024; i++) { ::close(i); } auto params = split(cmd, " "); // memory leak in child process, it's ok. char **charpv_params = new char *[params.size() + 1]; for (int i = 0; i < (int) params.size(); i++) { std::string &p = params[i]; charpv_params[i] = (char *) p.data(); } // EOF: NULL charpv_params[params.size()] = NULL; // TODO: execv or execvp auto ret = execv(params[0].c_str(), charpv_params); if (ret < 0) { fprintf(stderr, "fork process failed:%d(%s)\r\n", get_uv_error(), get_uv_errmsg()); } exit(ret); } InfoL << "start child process " << _pid << ", log file:" << log_file; #endif // _WIN32 } /** * 获取进程是否存活状态 * @param pid 进程号 * @param exit_code_ptr 进程返回代码 * @param block 是否阻塞等待 * @return 进程是否还在运行 */ static bool s_wait(pid_t pid, void *handle, int *exit_code_ptr, bool block) { if (pid <= 0) { return false; } #ifdef _WIN32 DWORD code = 0; if (block) { //一直等待 code = WaitForSingleObject(handle, INFINITE); } else { code = WaitForSingleObject(handle, 0); } if(code == WAIT_FAILED || code == WAIT_OBJECT_0){ //子进程已经退出了,获取子进程退出代码 DWORD exitCode = 0; if(exit_code_ptr && GetExitCodeProcess(handle, &exitCode)){ *exit_code_ptr = exitCode; } return false; } if(code == WAIT_TIMEOUT){ //子进程还在线 return true; } //不太可能运行到此处 WarnL << "WaitForSingleObject ret:" << code; return false; #else int status = 0; pid_t p = waitpid(pid, &status, block ? 0 : WNOHANG); int exit_code = (status & 0xFF00) >> 8; if (exit_code_ptr) { *exit_code_ptr = exit_code; } if (p < 0) { WarnL << "waitpid failed, pid=" << pid << ", err=" << get_uv_errmsg(); return false; } if (p > 0) { InfoL << "process terminated, pid=" << pid << ", exit code=" << exit_code; return false; } return true; #endif // _WIN32 } #ifdef _WIN32 // Inspired from http://stackoverflow.com/a/15281070/1529139 // and http://stackoverflow.com/q/40059902/1529139 bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent){ bool success = false; DWORD thisConsoleId = GetCurrentProcessId(); // Leave current console if it exists // (otherwise AttachConsole will return ERROR_ACCESS_DENIED) bool consoleDetached = (FreeConsole() != FALSE); if (AttachConsole(dwProcessId) != FALSE){ // Add a fake Ctrl-C handler for avoid instant kill is this console // WARNING: do not revert it or current program will be also killed SetConsoleCtrlHandler(nullptr, true); success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE); FreeConsole(); } if (consoleDetached){ // Create a new console if previous was deleted by OS if (AttachConsole(thisConsoleId) == FALSE){ int errorCode = GetLastError(); if (errorCode == 31){ // 31=ERROR_GEN_FAILURE AllocConsole(); } } } return success; } #endif // _WIN32 static void s_kill(pid_t pid, void *handle, int max_delay, bool force) { if (pid <= 0) { //pid无效 return; } #ifdef _WIN32 //windows下目前没有比较好的手段往子进程发送SIGTERM或信号 //所以杀死子进程的方式全部强制为立即关闭 force = true; if(force){ //强制关闭子进程 TerminateProcess(handle, 0); }else{ //非强制关闭,发送Ctr+C信号 signalCtrl(pid, CTRL_C_EVENT); } #else if (::kill(pid, force ? SIGKILL : SIGTERM) == -1) { //进程可能已经退出了 WarnL << "kill process " << pid << " failed:" << get_uv_errmsg(); return; } #endif // _WIN32 if (force) { //发送SIGKILL信号后,阻塞等待退出 s_wait(pid, handle, nullptr, true); DebugL << "force kill " << pid << " success!"; return; } //发送SIGTERM信号后,2秒后检查子进程是否已经退出 WorkThreadPool::Instance().getPoller()->doDelayTask(max_delay, [pid, handle]() { if (!s_wait(pid, handle, nullptr, false)) { //进程已经退出了 return 0; } //进程还在运行 WarnL << "process still working,force kill it:" << pid; s_kill(pid, handle, 0, true); return 0; }); } void Process::kill(int max_delay, bool force) { if (_pid <= 0) { return; } s_kill(_pid, _handle, max_delay, force); _pid = -1; #ifdef _WIN32 if(_handle){ CloseHandle(_handle); _handle = nullptr; } #endif } Process::~Process() { kill(2000); } Process::Process() {} bool Process::wait(bool block) { return s_wait(_pid, _handle, &_exit_code, block); } int Process::exit_code() { return _exit_code; } <commit_msg>修复子进程日志路径固定的问题<commit_after>/* * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #include <limits.h> #include <sys/stat.h> #ifndef _WIN32 #include <sys/resource.h> #include <unistd.h> #else //#include <TlHelp32.h> #include <windows.h> #include <io.h> #endif #include <stdexcept> #include <signal.h> #include "Util/util.h" #include "Util/File.h" #include "Util/logger.h" #include "Util/uv_errno.h" #include "Thread/WorkThreadPool.h" #include "Process.h" using namespace toolkit; void Process::run(const string &cmd, const string &log_file_tmp) { kill(2000); #ifdef _WIN32 STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; string log_file; if (log_file_tmp.empty()) { //未指定子进程日志文件时,重定向至/dev/null log_file = "NUL"; } else { log_file = StrPrinter << log_file_tmp << "." << getCurrentMillisecond(); } //重定向shell日志至文件 auto fp = File::create_file(log_file.data(), "ab"); if (!fp) { fprintf(stderr, "open log file %s failed:%d(%s)\r\n", log_file.data(), get_uv_error(), get_uv_errmsg()); } else { auto log_fd = (HANDLE)(_get_osfhandle(fileno(fp))); // dup to stdout and stderr. si.wShowWindow = SW_HIDE; // STARTF_USESHOWWINDOW:The wShowWindow member contains additional information. // STARTF_USESTDHANDLES:The hStdInput, hStdOutput, and hStdError members contain additional information. si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.hStdError = log_fd; si.hStdOutput = log_fd; } LPTSTR lpDir = const_cast<char*>(cmd.data()); if (CreateProcess(NULL, lpDir, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)){ //下面两行关闭句柄,解除本进程和新进程的关系,不然有可能 不小心调用TerminateProcess函数关掉子进程 CloseHandle(pi.hThread); _pid = pi.dwProcessId; _handle = pi.hProcess; fprintf(fp, "\r\n\r\n#### pid=%d,cmd=%s #####\r\n\r\n", _pid, cmd.data()); InfoL << "start child process " << _pid << ", log file:" << log_file; } else { WarnL << "start child process fail: " << get_uv_errmsg(); } fclose(fp); #else _pid = fork(); if (_pid < 0) { throw std::runtime_error(StrPrinter << "fork child process failed,err:" << get_uv_errmsg()); } if (_pid == 0) { string log_file; if (log_file_tmp.empty()) { //未指定子进程日志文件时,重定向至/dev/null log_file = "/dev/null"; } else { log_file = StrPrinter << log_file_tmp << "." << getpid(); } //子进程关闭core文件生成 struct rlimit rlim = {0, 0}; setrlimit(RLIMIT_CORE, &rlim); //在启动子进程时,暂时禁用SIGINT、SIGTERM信号 signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); //重定向shell日志至文件 auto fp = File::create_file(log_file.data(), "ab"); if (!fp) { fprintf(stderr, "open log file %s failed:%d(%s)\r\n", log_file.data(), get_uv_error(), get_uv_errmsg()); } else { auto log_fd = fileno(fp); // dup to stdout and stderr. if (dup2(log_fd, STDOUT_FILENO) < 0) { fprintf(stderr, "dup2 stdout file %s failed:%d(%s)\r\n", log_file.data(), get_uv_error(), get_uv_errmsg()); } if (dup2(log_fd, STDERR_FILENO) < 0) { fprintf(stderr, "dup2 stderr file %s failed:%d(%s)\r\n", log_file.data(), get_uv_error(), get_uv_errmsg()); } // 关闭日志文件 ::fclose(fp); } fprintf(stderr, "\r\n\r\n#### pid=%d,cmd=%s #####\r\n\r\n", getpid(), cmd.data()); //关闭父进程继承的fd for (int i = 3; i < 1024; i++) { ::close(i); } auto params = split(cmd, " "); // memory leak in child process, it's ok. char **charpv_params = new char *[params.size() + 1]; for (int i = 0; i < (int) params.size(); i++) { std::string &p = params[i]; charpv_params[i] = (char *) p.data(); } // EOF: NULL charpv_params[params.size()] = NULL; // TODO: execv or execvp auto ret = execv(params[0].c_str(), charpv_params); if (ret < 0) { fprintf(stderr, "fork process failed:%d(%s)\r\n", get_uv_error(), get_uv_errmsg()); } exit(ret); } string log_file; if (log_file_tmp.empty()) { //未指定子进程日志文件时,重定向至/dev/null log_file = "/dev/null"; } else { log_file = StrPrinter << log_file_tmp << "." << _pid; } InfoL << "start child process " << _pid << ", log file:" << log_file; #endif // _WIN32 } /** * 获取进程是否存活状态 * @param pid 进程号 * @param exit_code_ptr 进程返回代码 * @param block 是否阻塞等待 * @return 进程是否还在运行 */ static bool s_wait(pid_t pid, void *handle, int *exit_code_ptr, bool block) { if (pid <= 0) { return false; } #ifdef _WIN32 DWORD code = 0; if (block) { //一直等待 code = WaitForSingleObject(handle, INFINITE); } else { code = WaitForSingleObject(handle, 0); } if(code == WAIT_FAILED || code == WAIT_OBJECT_0){ //子进程已经退出了,获取子进程退出代码 DWORD exitCode = 0; if(exit_code_ptr && GetExitCodeProcess(handle, &exitCode)){ *exit_code_ptr = exitCode; } return false; } if(code == WAIT_TIMEOUT){ //子进程还在线 return true; } //不太可能运行到此处 WarnL << "WaitForSingleObject ret:" << code; return false; #else int status = 0; pid_t p = waitpid(pid, &status, block ? 0 : WNOHANG); int exit_code = (status & 0xFF00) >> 8; if (exit_code_ptr) { *exit_code_ptr = exit_code; } if (p < 0) { WarnL << "waitpid failed, pid=" << pid << ", err=" << get_uv_errmsg(); return false; } if (p > 0) { InfoL << "process terminated, pid=" << pid << ", exit code=" << exit_code; return false; } return true; #endif // _WIN32 } #ifdef _WIN32 // Inspired from http://stackoverflow.com/a/15281070/1529139 // and http://stackoverflow.com/q/40059902/1529139 bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent){ bool success = false; DWORD thisConsoleId = GetCurrentProcessId(); // Leave current console if it exists // (otherwise AttachConsole will return ERROR_ACCESS_DENIED) bool consoleDetached = (FreeConsole() != FALSE); if (AttachConsole(dwProcessId) != FALSE){ // Add a fake Ctrl-C handler for avoid instant kill is this console // WARNING: do not revert it or current program will be also killed SetConsoleCtrlHandler(nullptr, true); success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE); FreeConsole(); } if (consoleDetached){ // Create a new console if previous was deleted by OS if (AttachConsole(thisConsoleId) == FALSE){ int errorCode = GetLastError(); if (errorCode == 31){ // 31=ERROR_GEN_FAILURE AllocConsole(); } } } return success; } #endif // _WIN32 static void s_kill(pid_t pid, void *handle, int max_delay, bool force) { if (pid <= 0) { //pid无效 return; } #ifdef _WIN32 //windows下目前没有比较好的手段往子进程发送SIGTERM或信号 //所以杀死子进程的方式全部强制为立即关闭 force = true; if(force){ //强制关闭子进程 TerminateProcess(handle, 0); }else{ //非强制关闭,发送Ctr+C信号 signalCtrl(pid, CTRL_C_EVENT); } #else if (::kill(pid, force ? SIGKILL : SIGTERM) == -1) { //进程可能已经退出了 WarnL << "kill process " << pid << " failed:" << get_uv_errmsg(); return; } #endif // _WIN32 if (force) { //发送SIGKILL信号后,阻塞等待退出 s_wait(pid, handle, nullptr, true); DebugL << "force kill " << pid << " success!"; return; } //发送SIGTERM信号后,2秒后检查子进程是否已经退出 WorkThreadPool::Instance().getPoller()->doDelayTask(max_delay, [pid, handle]() { if (!s_wait(pid, handle, nullptr, false)) { //进程已经退出了 return 0; } //进程还在运行 WarnL << "process still working,force kill it:" << pid; s_kill(pid, handle, 0, true); return 0; }); } void Process::kill(int max_delay, bool force) { if (_pid <= 0) { return; } s_kill(_pid, _handle, max_delay, force); _pid = -1; #ifdef _WIN32 if(_handle){ CloseHandle(_handle); _handle = nullptr; } #endif } Process::~Process() { kill(2000); } Process::Process() {} bool Process::wait(bool block) { return s_wait(_pid, _handle, &_exit_code, block); } int Process::exit_code() { return _exit_code; } <|endoftext|>
<commit_before>#include "TestScene.h" #include <fstream> #include <ShaderManager.h> #include <Mesh.h> #include <LightCulling.h> #include <Director.h> #include <ResourceManager.h> #include <PhysicallyBasedMaterial.h> #include <SkyBox.h> using namespace Rendering; using namespace Core; using namespace Rendering::Camera; using namespace Rendering::Geometry; using namespace Rendering::Light; using namespace Rendering::Geometry; using namespace Rendering::Manager; using namespace Rendering::Sky; using namespace Resource; using namespace Device; using namespace Math; //using namespace Importer; TestScene::TestScene(void) : _testObject2(nullptr) { } TestScene::~TestScene(void) { } void TestScene::OnInitialize() { _camera = new Object("Default"); MeshCamera* cam = _camera->AddComponent<MeshCamera>(); #if 1 //GI Test ActivateGI(true, 256, 15.0f); const ResourceManager* resourceMgr = ResourceManager::SharedInstance(); Importer::MeshImporter* importer = resourceMgr->GetMeshImporter(); _testObject = importer->Load("./Resources/CornellBox/box.obj", false); _testObject->GetTransform()->UpdatePosition(Vector3(0.3f, -4.7f, 17.7f)); _testObject->GetTransform()->UpdateEulerAngles(Vector3(-90.0f, 0.0f, 180.0f)); _testObject->GetTransform()->UpdateScale(Vector3(5.0f, 5.0f, 5.0f)); AddObject(_testObject); _light = new Object("Light"); _light->GetTransform()->UpdatePosition(Vector3(0.0f, 2.0f, 16.0f)); PointLight* light = _light->AddComponent<PointLight>(); light->SetLumen(100); light->SetRadius(30.0f); light->ActiveShadow(true); light->GetShadow()->SetUnderScanSize(0.0f); AddObject(_light); // UpdateBoundBox(); // Vector3 pos = GetBoundBox().GetCenter(); _vxgi->SetStartCenterWorldPos(_testObject->GetTransform()->GetLocalPosition() + Vector3(0, 5.0f, 0.0f)); #else //IBL Test // SkyBox ActiveSkyBox("@Skybox", "Resources/CubeMap/desertcube1024.dds"); _camera->GetTransform()->UpdatePosition(Vector3(0, 0, 0)); cam->SetFieldOfViewDegree(60.0f); BasicGeometryGenerator gen; uint flag = uint(RenderManager::DefaultVertexInputTypeFlag::UV0) | uint(RenderManager::DefaultVertexInputTypeFlag::NORMAL); _testObject = gen.CreateSphere(1.0f, 30, 30, flag); _testObject->GetTransform()->UpdatePosition(Vector3(0, 0.0f, 11.0f)); _testObject->GetTransform()->UpdateEulerAngles(Vector3(0.0f, 0.0f, 0.0f)); _testObject->GetTransform()->UpdateScale(Vector3(5, 5, 5)); AddObject(_testObject); _light = new Object("Light"); _light->GetTransform()->UpdateEulerAngles(Vector3(90.0f, 0.0f, 0)); _light->GetTransform()->UpdatePosition(_camera->GetTransform()->GetLocalPosition()); DirectionalLight* light = _light->AddComponent<DirectionalLight>(); light->SetIntensity(2.0f); light->SetUseAutoProjectionLocation(true); light->ActiveShadow(false); AddObject(_light); #endif } void TestScene::OnRenderPreview() { if(_vxgi) { auto voxelViwer = _vxgi->GetDebugVoxelViewer(); if(voxelViwer) { Object* debugVoxels = voxelViwer->GetVoxelsParent(); if(debugVoxels) { Object* exist = FindObject(debugVoxels->GetName()); if( exist == nullptr ) { _testObject->SetUse(false); AddObject(debugVoxels); _testObject2 = debugVoxels; //#ifndef USE_ANISOTROPIC_VOXELIZATION debugVoxels->GetTransform()->UpdatePosition(Vector3(0.0f, -0.3f, -4.1f)); //#else // debugVoxels->GetTransform()->UpdatePosition(Vector3(0.0f, 1.8f, -3.1f)); //#endif } } } } } void TestScene::OnInput(const Device::Win32::Mouse& mouse, const Device::Win32::Keyboard& keyboard) { const float scale = 1.0f; #if 1 Transform* control = _testObject->GetTransform(); if(keyboard.states['W'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(0, scale, 0)); } if(keyboard.states['S'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(0, -scale, 0)); } if(keyboard.states['A'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(-scale, 0, 0)); } if(keyboard.states['D'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(scale, 0, 0)); } if(keyboard.states['T'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(0, 0, scale)); } if(keyboard.states['G'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(0, 0, -scale)); } if(keyboard.states['U'] == Win32::Keyboard::Type::Up) { //PointLight* pl = _light->GetComponent<PointLight>(); //float us = pl->GetShadow()->GetUnderScanSize(); //pl->GetShadow()->SetUnderScanSize(us + scale); Vector3 euler = control->GetLocalEulerAngle(); control->UpdateEulerAngles(euler + Vector3(5.0f, 0.0f, 0.0f)); } if(keyboard.states['J'] == Win32::Keyboard::Type::Up) { //PointLight* pl = _light->GetComponent<PointLight>(); //float us = pl->GetShadow()->GetUnderScanSize(); //pl->GetShadow()->SetUnderScanSize(us - scale); Vector3 euler = control->GetLocalEulerAngle(); control->UpdateEulerAngles(euler - Vector3(5.0f, 0.0f, 0.0f)); } if(keyboard.states['H'] == Win32::Keyboard::Type::Up) { //PointLight* pl = _light->GetComponent<PointLight>(); //pl->GetShadow()->SetBias(pl->GetShadow()->GetBias() - 0.01f); Vector3 euler = control->GetLocalEulerAngle(); control->UpdateEulerAngles(euler - Vector3(0.0f, 5.0f, 0.0f)); } if(keyboard.states['K'] == Win32::Keyboard::Type::Up) { //PointLight* pl = _light->GetComponent<PointLight>(); //pl->GetShadow()->SetBias(pl->GetShadow()->GetBias() + 0.01f); Vector3 euler = control->GetLocalEulerAngle(); control->UpdateEulerAngles(euler + Vector3(0.0f, 5.0f, 0.0f)); } if(keyboard.states['M'] == Win32::Keyboard::Type::Up) { _testObject->SetUse(!_testObject->GetUse()); } #else Vector3 pos = _vxgi->GetStartCenterWorldPos(); if(keyboard.states['W'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(0, scale, 0)); if(keyboard.states['S'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(0, -scale, 0)); if(keyboard.states['A'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(-scale, 0, 0)); if(keyboard.states['D'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(scale, 0, 0)); if(keyboard.states['T'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(0, 0, scale)); if(keyboard.states['G'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(0, 0, -scale)); #endif } void TestScene::OnUpdate(float dt) { } void TestScene::OnRenderPost() { } void TestScene::OnDestroy() { }<commit_msg>테스트 코드 추가<commit_after>#include "TestScene.h" #include <fstream> #include <ShaderManager.h> #include <Mesh.h> #include <LightCulling.h> #include <Director.h> #include <ResourceManager.h> #include <PhysicallyBasedMaterial.h> #include <SkyBox.h> using namespace Rendering; using namespace Core; using namespace Rendering::Camera; using namespace Rendering::Geometry; using namespace Rendering::Light; using namespace Rendering::Geometry; using namespace Rendering::Manager; using namespace Rendering::Sky; using namespace Resource; using namespace Device; using namespace Math; //using namespace Importer; TestScene::TestScene(void) : _testObject2(nullptr) { } TestScene::~TestScene(void) { } void TestScene::OnInitialize() { _camera = new Object("Default"); MeshCamera* cam = _camera->AddComponent<MeshCamera>(); #if 1 //GI Test ActivateGI(true, 256, 15.0f); const ResourceManager* resourceMgr = ResourceManager::SharedInstance(); Importer::MeshImporter* importer = resourceMgr->GetMeshImporter(); _testObject = importer->Load("./Resources/CornellBox/box.obj", false); _testObject->GetTransform()->UpdatePosition(Vector3(0.3f, -4.7f, 17.7f)); _testObject->GetTransform()->UpdateEulerAngles(Vector3(-90.0f, 0.0f, 180.0f)); _testObject->GetTransform()->UpdateScale(Vector3(5.0f, 5.0f, 5.0f)); AddObject(_testObject); _light = new Object("Light"); _light->GetTransform()->UpdatePosition(Vector3(0.0f, 2.0f, 16.0f)); PointLight* light = _light->AddComponent<PointLight>(); light->SetLumen(100); light->SetRadius(30.0f); light->ActiveShadow(true); light->GetShadow()->SetUnderScanSize(0.0f); AddObject(_light); if(_vxgi) _vxgi->SetStartCenterWorldPos(_testObject->GetTransform()->GetLocalPosition() + Vector3(0, 5.0f, 0.0f)); #elif 0 const ResourceManager* resourceMgr = ResourceManager::SharedInstance(); Importer::MeshImporter* importer = resourceMgr->GetMeshImporter(); _testObject = importer->Load("./Resources/Sponza/sponza.obj", false); _testObject->GetTransform()->UpdatePosition(Vector3(-15, -20, 70)); _testObject->GetTransform()->UpdateEulerAngles(Vector3(270, 90.0f, 0.0f)); _testObject->GetTransform()->UpdateScale(Vector3(0.1f, 0.1f, 0.1f)); AddObject(_testObject); UpdateBoundBox(); _camera->GetTransform()->UpdatePosition(GetBoundBox().GetCenter()); _light = new Object("Light"); _light->GetTransform()->UpdatePosition(Vector3(0.0f, 2.0f, 16.0f)); _light->GetTransform()->UpdateEulerAngles(Vector3(30.0f, 330.0f, 0.0f)); DirectionalLight* dl = _light->AddComponent<DirectionalLight>(); dl->SetIntensity(2.0f); dl->ActiveShadow(false); #elif 0 //IBL Test // SkyBox ActiveSkyBox("@Skybox", "Resources/CubeMap/desertcube1024.dds"); _camera->GetTransform()->UpdatePosition(Vector3(0, 0, 0)); cam->SetFieldOfViewDegree(60.0f); BasicGeometryGenerator gen; uint flag = uint(RenderManager::DefaultVertexInputTypeFlag::UV0) | uint(RenderManager::DefaultVertexInputTypeFlag::NORMAL); _testObject = gen.CreateSphere(1.0f, 30, 30, flag); _testObject->GetTransform()->UpdatePosition(Vector3(0, 0.0f, 11.0f)); _testObject->GetTransform()->UpdateEulerAngles(Vector3(0.0f, 0.0f, 0.0f)); _testObject->GetTransform()->UpdateScale(Vector3(5, 5, 5)); AddObject(_testObject); _light = new Object("Light"); _light->GetTransform()->UpdateEulerAngles(Vector3(90.0f, 0.0f, 0)); _light->GetTransform()->UpdatePosition(_camera->GetTransform()->GetLocalPosition()); DirectionalLight* light = _light->AddComponent<DirectionalLight>(); light->SetIntensity(2.0f); light->SetUseAutoProjectionLocation(true); light->ActiveShadow(false); AddObject(_light); #endif } void TestScene::OnRenderPreview() { if(_vxgi) { auto voxelViwer = _vxgi->GetDebugVoxelViewer(); if(voxelViwer) { Object* debugVoxels = voxelViwer->GetVoxelsParent(); if(debugVoxels) { Object* exist = FindObject(debugVoxels->GetName()); if( exist == nullptr ) { _testObject->SetUse(false); AddObject(debugVoxels); _testObject2 = debugVoxels; //#ifndef USE_ANISOTROPIC_VOXELIZATION debugVoxels->GetTransform()->UpdatePosition(Vector3(0.0f, -0.3f, -4.1f)); //#else // debugVoxels->GetTransform()->UpdatePosition(Vector3(0.0f, 1.8f, -3.1f)); //#endif } } } } } void TestScene::OnInput(const Device::Win32::Mouse& mouse, const Device::Win32::Keyboard& keyboard) { const float scale = 5.0f; #if 1 Transform* control = _light->GetTransform(); if(keyboard.states['W'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(0, scale, 0)); } if(keyboard.states['S'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(0, -scale, 0)); } if(keyboard.states['A'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(-scale, 0, 0)); } if(keyboard.states['D'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(scale, 0, 0)); } if(keyboard.states['T'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(0, 0, scale)); } if(keyboard.states['G'] == Win32::Keyboard::Type::Up) { Vector3 pos = control->GetLocalPosition(); control->UpdatePosition(pos + Vector3(0, 0, -scale)); } if(keyboard.states['U'] == Win32::Keyboard::Type::Up) { //PointLight* pl = _light->GetComponent<PointLight>(); //float us = pl->GetShadow()->GetUnderScanSize(); //pl->GetShadow()->SetUnderScanSize(us + scale); Vector3 euler = control->GetLocalEulerAngle(); control->UpdateEulerAngles(euler + Vector3(5.0f, 0.0f, 0.0f)); } if(keyboard.states['J'] == Win32::Keyboard::Type::Up) { //PointLight* pl = _light->GetComponent<PointLight>(); //float us = pl->GetShadow()->GetUnderScanSize(); //pl->GetShadow()->SetUnderScanSize(us - scale); Vector3 euler = control->GetLocalEulerAngle(); control->UpdateEulerAngles(euler - Vector3(5.0f, 0.0f, 0.0f)); } if(keyboard.states['H'] == Win32::Keyboard::Type::Up) { //PointLight* pl = _light->GetComponent<PointLight>(); //pl->GetShadow()->SetBias(pl->GetShadow()->GetBias() - 0.01f); Vector3 euler = control->GetLocalEulerAngle(); control->UpdateEulerAngles(euler - Vector3(0.0f, 5.0f, 0.0f)); } if(keyboard.states['K'] == Win32::Keyboard::Type::Up) { //PointLight* pl = _light->GetComponent<PointLight>(); //pl->GetShadow()->SetBias(pl->GetShadow()->GetBias() + 0.01f); Vector3 euler = control->GetLocalEulerAngle(); control->UpdateEulerAngles(euler + Vector3(0.0f, 5.0f, 0.0f)); } if(keyboard.states['M'] == Win32::Keyboard::Type::Up) { _testObject->SetUse(!_testObject->GetUse()); } #else Vector3 pos = _vxgi->GetStartCenterWorldPos(); if(keyboard.states['W'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(0, scale, 0)); if(keyboard.states['S'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(0, -scale, 0)); if(keyboard.states['A'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(-scale, 0, 0)); if(keyboard.states['D'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(scale, 0, 0)); if(keyboard.states['T'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(0, 0, scale)); if(keyboard.states['G'] == Win32::Keyboard::Type::Up) _vxgi->SetStartCenterWorldPos(pos + Vector3(0, 0, -scale)); #endif } void TestScene::OnUpdate(float dt) { } void TestScene::OnRenderPost() { } void TestScene::OnDestroy() { }<|endoftext|>
<commit_before>#include "master.hpp" namespace factor { struct object_slot_forwarder { mark_bits<object> *forwarding_map; explicit object_slot_forwarder(mark_bits<object> *forwarding_map_) : forwarding_map(forwarding_map_) {} object *visit_object(object *obj) { return forwarding_map->forward_block(obj); } }; struct code_block_forwarder { mark_bits<code_block> *forwarding_map; explicit code_block_forwarder(mark_bits<code_block> *forwarding_map_) : forwarding_map(forwarding_map_) {} code_block *operator()(code_block *compiled) { return forwarding_map->forward_block(compiled); } }; static inline cell tuple_size_with_forwarding(mark_bits<object> *forwarding_map, object *obj) { /* The tuple layout may or may not have been forwarded already. Tricky. */ object *layout_obj = (object *)UNTAG(((tuple *)obj)->layout); tuple_layout *layout; if(layout_obj < obj) { /* It's already been moved up; dereference through forwarding map to get the size */ layout = (tuple_layout *)forwarding_map->forward_block(layout_obj); } else { /* It hasn't been moved up yet; dereference directly */ layout = (tuple_layout *)layout_obj; } return tuple_size(layout); } struct compaction_sizer { mark_bits<object> *forwarding_map; explicit compaction_sizer(mark_bits<object> *forwarding_map_) : forwarding_map(forwarding_map_) {} cell operator()(object *obj) { if(obj->free_p() || obj->h.hi_tag() != TUPLE_TYPE) return obj->size(); else return align(tuple_size_with_forwarding(forwarding_map,obj),data_alignment); } }; struct object_compaction_updater { factor_vm *parent; slot_visitor<object_slot_forwarder> slot_forwarder; code_block_visitor<code_block_forwarder> code_forwarder; mark_bits<object> *data_forwarding_map; explicit object_compaction_updater(factor_vm *parent_, slot_visitor<object_slot_forwarder> slot_forwarder_, code_block_visitor<code_block_forwarder> code_forwarder_, mark_bits<object> *data_forwarding_map_) : parent(parent_), slot_forwarder(slot_forwarder_), code_forwarder(code_forwarder_), data_forwarding_map(data_forwarding_map_) {} void operator()(object *obj, cell size) { cell payload_start; if(obj->h.hi_tag() == TUPLE_TYPE) payload_start = tuple_size_with_forwarding(data_forwarding_map,obj); else payload_start = obj->binary_payload_start(); slot_forwarder.visit_slots(obj,payload_start); code_forwarder.visit_object_code_block(obj); } }; struct code_block_compaction_updater { factor_vm *parent; slot_visitor<object_slot_forwarder> slot_forwarder; explicit code_block_compaction_updater(factor_vm *parent_, slot_visitor<object_slot_forwarder> slot_forwarder_) : parent(parent_), slot_forwarder(slot_forwarder_) {} void operator()(code_block *compiled, cell size) { slot_forwarder.visit_literal_references(compiled); parent->relocate_code_block(compiled); } }; void factor_vm::compact_full_impl(bool trace_contexts_p) { tenured_space *tenured = data->tenured; mark_bits<object> *data_forwarding_map = &tenured->state; mark_bits<code_block> *code_forwarding_map = &code->allocator->state; /* Figure out where blocks are going to go */ data_forwarding_map->compute_forwarding(); code_forwarding_map->compute_forwarding(); /* Update root pointers */ slot_visitor<object_slot_forwarder> slot_forwarder(this,object_slot_forwarder(data_forwarding_map)); code_block_visitor<code_block_forwarder> code_forwarder(this,code_block_forwarder(code_forwarding_map)); slot_forwarder.visit_roots(); if(trace_contexts_p) { slot_forwarder.visit_contexts(); code_forwarder.visit_context_code_blocks(); code_forwarder.visit_callback_code_blocks(); } /* Slide everything in tenured space up, and update data and code heap pointers inside objects. */ object_compaction_updater object_updater(this,slot_forwarder,code_forwarder,data_forwarding_map); compaction_sizer object_sizer(data_forwarding_map); tenured->compact(object_updater,object_sizer); /* Slide everything in the code heap up, and update data and code heap pointers inside code blocks. */ code_block_compaction_updater code_block_updater(this,slot_forwarder); standard_sizer<code_block> code_block_sizer; code->allocator->compact(code_block_updater,code_block_sizer); } } <commit_msg>vm: fix compaction when callback heap has entries in it<commit_after>#include "master.hpp" namespace factor { struct object_slot_forwarder { mark_bits<object> *forwarding_map; explicit object_slot_forwarder(mark_bits<object> *forwarding_map_) : forwarding_map(forwarding_map_) {} object *visit_object(object *obj) { return forwarding_map->forward_block(obj); } }; struct code_block_forwarder { mark_bits<code_block> *forwarding_map; explicit code_block_forwarder(mark_bits<code_block> *forwarding_map_) : forwarding_map(forwarding_map_) {} code_block *operator()(code_block *compiled) { return forwarding_map->forward_block(compiled); } }; static inline cell tuple_size_with_forwarding(mark_bits<object> *forwarding_map, object *obj) { /* The tuple layout may or may not have been forwarded already. Tricky. */ object *layout_obj = (object *)UNTAG(((tuple *)obj)->layout); tuple_layout *layout; if(layout_obj < obj) { /* It's already been moved up; dereference through forwarding map to get the size */ layout = (tuple_layout *)forwarding_map->forward_block(layout_obj); } else { /* It hasn't been moved up yet; dereference directly */ layout = (tuple_layout *)layout_obj; } return tuple_size(layout); } struct compaction_sizer { mark_bits<object> *forwarding_map; explicit compaction_sizer(mark_bits<object> *forwarding_map_) : forwarding_map(forwarding_map_) {} cell operator()(object *obj) { if(obj->free_p() || obj->h.hi_tag() != TUPLE_TYPE) return obj->size(); else return align(tuple_size_with_forwarding(forwarding_map,obj),data_alignment); } }; struct object_compaction_updater { factor_vm *parent; slot_visitor<object_slot_forwarder> slot_forwarder; code_block_visitor<code_block_forwarder> code_forwarder; mark_bits<object> *data_forwarding_map; explicit object_compaction_updater(factor_vm *parent_, slot_visitor<object_slot_forwarder> slot_forwarder_, code_block_visitor<code_block_forwarder> code_forwarder_, mark_bits<object> *data_forwarding_map_) : parent(parent_), slot_forwarder(slot_forwarder_), code_forwarder(code_forwarder_), data_forwarding_map(data_forwarding_map_) {} void operator()(object *obj, cell size) { cell payload_start; if(obj->h.hi_tag() == TUPLE_TYPE) payload_start = tuple_size_with_forwarding(data_forwarding_map,obj); else payload_start = obj->binary_payload_start(); slot_forwarder.visit_slots(obj,payload_start); code_forwarder.visit_object_code_block(obj); } }; struct code_block_compaction_updater { factor_vm *parent; slot_visitor<object_slot_forwarder> slot_forwarder; explicit code_block_compaction_updater(factor_vm *parent_, slot_visitor<object_slot_forwarder> slot_forwarder_) : parent(parent_), slot_forwarder(slot_forwarder_) {} void operator()(code_block *compiled, cell size) { slot_forwarder.visit_literal_references(compiled); parent->relocate_code_block(compiled); } }; void factor_vm::compact_full_impl(bool trace_contexts_p) { tenured_space *tenured = data->tenured; mark_bits<object> *data_forwarding_map = &tenured->state; mark_bits<code_block> *code_forwarding_map = &code->allocator->state; /* Figure out where blocks are going to go */ data_forwarding_map->compute_forwarding(); code_forwarding_map->compute_forwarding(); /* Update root pointers */ slot_visitor<object_slot_forwarder> slot_forwarder(this,object_slot_forwarder(data_forwarding_map)); code_block_visitor<code_block_forwarder> code_forwarder(this,code_block_forwarder(code_forwarding_map)); /* Slide everything in tenured space up, and update data and code heap pointers inside objects. */ object_compaction_updater object_updater(this,slot_forwarder,code_forwarder,data_forwarding_map); compaction_sizer object_sizer(data_forwarding_map); tenured->compact(object_updater,object_sizer); /* Slide everything in the code heap up, and update data and code heap pointers inside code blocks. */ code_block_compaction_updater code_block_updater(this,slot_forwarder); standard_sizer<code_block> code_block_sizer; code->allocator->compact(code_block_updater,code_block_sizer); slot_forwarder.visit_roots(); if(trace_contexts_p) { slot_forwarder.visit_contexts(); code_forwarder.visit_context_code_blocks(); code_forwarder.visit_callback_code_blocks(); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: valuemembernode.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:48:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_configmgr.hxx" #include <stdio.h> #include "valuemembernode.hxx" #ifndef CONFIGMGR_NODEIMPLOBJECTS_HXX_ #include "nodeimplobj.hxx" #endif #ifndef CONFIGMGR_CONFIGCHANGEIMPL_HXX_ #include "nodechangeimpl.hxx" #endif #ifndef CONFIGMGR_CHANGE_HXX #include "change.hxx" #endif #ifndef _CONFIGMGR_TREE_VALUENODE_HXX #include "valuenode.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif namespace configmgr { namespace configuration { // helpers //----------------------------------------------------------------------------- namespace { //----------------------------------------------------------------------------- // internal accessors for direct updates to data //----------------------------------------------------------------------------- inline void setOriginalValue(data::ValueNodeAddress const& rOriginalAddress, UnoAny const& aNewValue) { data::ValueNodeAccess::setValue(rOriginalAddress,aNewValue); } //----------------------------------------------------------------------------- inline void setOriginalToDefault(data::ValueNodeAddress const& rOriginalAddress) { data::ValueNodeAccess::setToDefault(rOriginalAddress); } } // anonymous namespace //----------------------------------------------------------------------------- // class ValueMemberNode //----------------------------------------------------------------------------- ValueMemberNode::ValueMemberNode(data::ValueNodeAccess const& _aNodeAccess) : m_aNodeRef(_aNodeAccess) , m_xDeferredOperation() {} //----------------------------------------------------------------------------- ValueMemberNode::ValueMemberNode(DeferredImplRef const& _xDeferred) // must be valid : m_aNodeRef( _xDeferred->getOriginalNode() ) , m_xDeferredOperation(_xDeferred) {} //----------------------------------------------------------------------------- ValueMemberNode::ValueMemberNode(ValueMemberNode const& rOriginal) : m_aNodeRef(rOriginal.m_aNodeRef) , m_xDeferredOperation(rOriginal.m_xDeferredOperation) {} //----------------------------------------------------------------------------- ValueMemberNode& ValueMemberNode::operator=(ValueMemberNode const& rOriginal) { m_aNodeRef = rOriginal.m_aNodeRef; m_xDeferredOperation = rOriginal.m_xDeferredOperation; return *this; } //----------------------------------------------------------------------------- ValueMemberNode::~ValueMemberNode() { } //----------------------------------------------------------------------------- bool ValueMemberNode::isValid() const { OSL_ASSERT( !m_xDeferredOperation.is() || m_aNodeRef == m_xDeferredOperation->getOriginalNodeAddress()); return m_aNodeRef.isValid(); } //----------------------------------------------------------------------------- bool ValueMemberNode::hasChange() const { return m_xDeferredOperation.is() && m_xDeferredOperation->isChange(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // external accessors //----------------------------------------------------------------------------- Name ValueMemberNode::getNodeName() const { return m_aNodeRef.getName(); } //----------------------------------------------------------------------------- node::Attributes ValueMemberNode::getAttributes() const { return m_aNodeRef.getAttributes(); } //----------------------------------------------------------------------------- bool ValueMemberNode::isDefault() const { if (hasChange()) return m_xDeferredOperation->isToDefault(); return m_aNodeRef.isDefault(); } //----------------------------------------------------------------------------- bool ValueMemberNode::canGetDefaultValue() const { return m_aNodeRef.hasUsableDefault(); } //----------------------------------------------------------------------------- UnoAny ValueMemberNode::getValue() const { if (hasChange()) return m_xDeferredOperation->getNewValue(); return m_aNodeRef.getValue(); } //----------------------------------------------------------------------------- UnoAny ValueMemberNode::getDefaultValue() const { return m_aNodeRef.getDefaultValue(); } //----------------------------------------------------------------------------- UnoType ValueMemberNode::getValueType() const { return m_aNodeRef.getValueType(); } //----------------------------------------------------------------------------- void ValueMemberUpdate::setValue(UnoAny const& aNewValue) { if (m_aMemberNode.m_xDeferredOperation.is()) m_aMemberNode.m_xDeferredOperation->setValue(aNewValue, m_aMemberNode.m_aNodeRef); else setOriginalValue(m_aMemberNode.m_aNodeRef, aNewValue ); } //----------------------------------------------------------------------------- void ValueMemberUpdate::setDefault() { if (m_aMemberNode.m_xDeferredOperation.is()) m_aMemberNode.m_xDeferredOperation->setValueToDefault(m_aMemberNode.m_aNodeRef); else setOriginalToDefault( m_aMemberNode.m_aNodeRef ); } //----------------------------------------------------------------------------- // class ValueMemberNode::DeferredImpl //----------------------------------------------------------------------------- ValueMemberNode::DeferredImpl::DeferredImpl(data::ValueNodeAccess const& _aValueNode) : m_aValueRef(_aValueNode) , m_aNewValue(_aValueNode.getValue()) , m_bToDefault(false) , m_bChange(false) {} //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::setValue(UnoAny const& aNewValue, data::ValueNodeAccess const& _aOriginalNode) { OSL_ENSURE(_aOriginalNode == m_aValueRef, "Incorrect original node passed"); m_aNewValue = aNewValue; m_bToDefault = false; m_bChange = _aOriginalNode.isDefault() || aNewValue != _aOriginalNode.getValue(); } //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::setValueToDefault(data::ValueNodeAccess const& _aOriginalNode) { OSL_ENSURE(_aOriginalNode == m_aValueRef, "Incorrect original node passed"); m_aNewValue = _aOriginalNode.getDefaultValue(); m_bToDefault = true; m_bChange = !_aOriginalNode.isDefault(); } //----------------------------------------------------------------------------- std::auto_ptr<ValueChange> ValueMemberNode::DeferredImpl::preCommitChange() { OSL_ENSURE(isChange(), "Trying to commit a non-change"); data::ValueNodeAccess aOriginalNode = getOriginalNode(); // first find the mode of the change ValueChange::Mode eMode; if (m_bToDefault) eMode = ValueChange::setToDefault; else if (! aOriginalNode.isDefault()) eMode = ValueChange::changeValue; else eMode = ValueChange::wasDefault; // now make a ValueChange std::auto_ptr<ValueChange>pChange( new ValueChange( aOriginalNode.getName().toString(), aOriginalNode.getAttributes(), eMode, this->getNewValue(), aOriginalNode.getValue() ) ); return pChange; } //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::finishCommit(ValueChange& rChange) { { (void)rChange; } OSL_ENSURE(rChange.getNewValue() == this->getNewValue(),"Committed change does not match the intended value"); data::ValueNodeAccess aOriginalNode = getOriginalNode(); m_aNewValue = aOriginalNode.getValue(); m_bToDefault = false; OSL_ENSURE(rChange.getNewValue() == m_aNewValue,"Committed change does not match the actual value"); m_bChange= false; } //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::revertCommit(ValueChange& rChange) { { (void)rChange; } OSL_ENSURE(rChange.getNewValue() == this->getNewValue(),"Reverted change does not match the intended value"); OSL_ENSURE(isChange(), "ValueMemeberNode::DeferredImpl: No Changes to revert"); } //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::failedCommit(ValueChange&) { data::ValueNodeAccess aOriginalNode = getOriginalNode(); // discard the change m_aNewValue = aOriginalNode.getValue(); m_bToDefault = false; m_bChange= false; } //----------------------------------------------------------------------------- ValueChangeImpl* ValueMemberNode::DeferredImpl::collectChange() { data::ValueNodeAccess aOriginalNode = getOriginalNode(); UnoAny aOldValue = aOriginalNode.getValue(); if (!m_bChange) { return NULL; } else if (m_bToDefault) { OSL_ASSERT( m_aNewValue == aOriginalNode.getDefaultValue() ); return new ValueResetImpl( m_aNewValue, aOldValue ); } else { return new ValueReplaceImpl( m_aNewValue, aOldValue ); } } //----------------------------------------------------------------------------- ValueChangeImpl* ValueMemberNode::DeferredImpl::adjustToChange(ValueChange const& rExternalChange) { if (!m_bChange) { return NULL; } else if (m_bToDefault && rExternalChange.getMode() == ValueChange::changeDefault) { OSL_ASSERT( m_aNewValue == rExternalChange.getOldValue() ); m_aNewValue = rExternalChange.getNewValue(); return new ValueReplaceImpl(m_aNewValue, rExternalChange.getOldValue()); } else // return Surrogate - does not honor m_bToDefault { return new ValueReplaceImpl(m_aNewValue, m_aNewValue); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } } <commit_msg>INTEGRATION: CWS changefileheader (1.10.16); FILE MERGED 2008/04/01 15:06:58 thb 1.10.16.3: #i85898# Stripping all external header guards 2008/04/01 12:27:39 thb 1.10.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:57 rt 1.10.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: valuemembernode.cxx,v $ * $Revision: 1.11 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_configmgr.hxx" #include <stdio.h> #include "valuemembernode.hxx" #include "nodeimplobj.hxx" #include "nodechangeimpl.hxx" #include "change.hxx" #include "valuenode.hxx" #include <osl/diagnose.h> namespace configmgr { namespace configuration { // helpers //----------------------------------------------------------------------------- namespace { //----------------------------------------------------------------------------- // internal accessors for direct updates to data //----------------------------------------------------------------------------- inline void setOriginalValue(data::ValueNodeAddress const& rOriginalAddress, UnoAny const& aNewValue) { data::ValueNodeAccess::setValue(rOriginalAddress,aNewValue); } //----------------------------------------------------------------------------- inline void setOriginalToDefault(data::ValueNodeAddress const& rOriginalAddress) { data::ValueNodeAccess::setToDefault(rOriginalAddress); } } // anonymous namespace //----------------------------------------------------------------------------- // class ValueMemberNode //----------------------------------------------------------------------------- ValueMemberNode::ValueMemberNode(data::ValueNodeAccess const& _aNodeAccess) : m_aNodeRef(_aNodeAccess) , m_xDeferredOperation() {} //----------------------------------------------------------------------------- ValueMemberNode::ValueMemberNode(DeferredImplRef const& _xDeferred) // must be valid : m_aNodeRef( _xDeferred->getOriginalNode() ) , m_xDeferredOperation(_xDeferred) {} //----------------------------------------------------------------------------- ValueMemberNode::ValueMemberNode(ValueMemberNode const& rOriginal) : m_aNodeRef(rOriginal.m_aNodeRef) , m_xDeferredOperation(rOriginal.m_xDeferredOperation) {} //----------------------------------------------------------------------------- ValueMemberNode& ValueMemberNode::operator=(ValueMemberNode const& rOriginal) { m_aNodeRef = rOriginal.m_aNodeRef; m_xDeferredOperation = rOriginal.m_xDeferredOperation; return *this; } //----------------------------------------------------------------------------- ValueMemberNode::~ValueMemberNode() { } //----------------------------------------------------------------------------- bool ValueMemberNode::isValid() const { OSL_ASSERT( !m_xDeferredOperation.is() || m_aNodeRef == m_xDeferredOperation->getOriginalNodeAddress()); return m_aNodeRef.isValid(); } //----------------------------------------------------------------------------- bool ValueMemberNode::hasChange() const { return m_xDeferredOperation.is() && m_xDeferredOperation->isChange(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // external accessors //----------------------------------------------------------------------------- Name ValueMemberNode::getNodeName() const { return m_aNodeRef.getName(); } //----------------------------------------------------------------------------- node::Attributes ValueMemberNode::getAttributes() const { return m_aNodeRef.getAttributes(); } //----------------------------------------------------------------------------- bool ValueMemberNode::isDefault() const { if (hasChange()) return m_xDeferredOperation->isToDefault(); return m_aNodeRef.isDefault(); } //----------------------------------------------------------------------------- bool ValueMemberNode::canGetDefaultValue() const { return m_aNodeRef.hasUsableDefault(); } //----------------------------------------------------------------------------- UnoAny ValueMemberNode::getValue() const { if (hasChange()) return m_xDeferredOperation->getNewValue(); return m_aNodeRef.getValue(); } //----------------------------------------------------------------------------- UnoAny ValueMemberNode::getDefaultValue() const { return m_aNodeRef.getDefaultValue(); } //----------------------------------------------------------------------------- UnoType ValueMemberNode::getValueType() const { return m_aNodeRef.getValueType(); } //----------------------------------------------------------------------------- void ValueMemberUpdate::setValue(UnoAny const& aNewValue) { if (m_aMemberNode.m_xDeferredOperation.is()) m_aMemberNode.m_xDeferredOperation->setValue(aNewValue, m_aMemberNode.m_aNodeRef); else setOriginalValue(m_aMemberNode.m_aNodeRef, aNewValue ); } //----------------------------------------------------------------------------- void ValueMemberUpdate::setDefault() { if (m_aMemberNode.m_xDeferredOperation.is()) m_aMemberNode.m_xDeferredOperation->setValueToDefault(m_aMemberNode.m_aNodeRef); else setOriginalToDefault( m_aMemberNode.m_aNodeRef ); } //----------------------------------------------------------------------------- // class ValueMemberNode::DeferredImpl //----------------------------------------------------------------------------- ValueMemberNode::DeferredImpl::DeferredImpl(data::ValueNodeAccess const& _aValueNode) : m_aValueRef(_aValueNode) , m_aNewValue(_aValueNode.getValue()) , m_bToDefault(false) , m_bChange(false) {} //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::setValue(UnoAny const& aNewValue, data::ValueNodeAccess const& _aOriginalNode) { OSL_ENSURE(_aOriginalNode == m_aValueRef, "Incorrect original node passed"); m_aNewValue = aNewValue; m_bToDefault = false; m_bChange = _aOriginalNode.isDefault() || aNewValue != _aOriginalNode.getValue(); } //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::setValueToDefault(data::ValueNodeAccess const& _aOriginalNode) { OSL_ENSURE(_aOriginalNode == m_aValueRef, "Incorrect original node passed"); m_aNewValue = _aOriginalNode.getDefaultValue(); m_bToDefault = true; m_bChange = !_aOriginalNode.isDefault(); } //----------------------------------------------------------------------------- std::auto_ptr<ValueChange> ValueMemberNode::DeferredImpl::preCommitChange() { OSL_ENSURE(isChange(), "Trying to commit a non-change"); data::ValueNodeAccess aOriginalNode = getOriginalNode(); // first find the mode of the change ValueChange::Mode eMode; if (m_bToDefault) eMode = ValueChange::setToDefault; else if (! aOriginalNode.isDefault()) eMode = ValueChange::changeValue; else eMode = ValueChange::wasDefault; // now make a ValueChange std::auto_ptr<ValueChange>pChange( new ValueChange( aOriginalNode.getName().toString(), aOriginalNode.getAttributes(), eMode, this->getNewValue(), aOriginalNode.getValue() ) ); return pChange; } //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::finishCommit(ValueChange& rChange) { { (void)rChange; } OSL_ENSURE(rChange.getNewValue() == this->getNewValue(),"Committed change does not match the intended value"); data::ValueNodeAccess aOriginalNode = getOriginalNode(); m_aNewValue = aOriginalNode.getValue(); m_bToDefault = false; OSL_ENSURE(rChange.getNewValue() == m_aNewValue,"Committed change does not match the actual value"); m_bChange= false; } //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::revertCommit(ValueChange& rChange) { { (void)rChange; } OSL_ENSURE(rChange.getNewValue() == this->getNewValue(),"Reverted change does not match the intended value"); OSL_ENSURE(isChange(), "ValueMemeberNode::DeferredImpl: No Changes to revert"); } //----------------------------------------------------------------------------- void ValueMemberNode::DeferredImpl::failedCommit(ValueChange&) { data::ValueNodeAccess aOriginalNode = getOriginalNode(); // discard the change m_aNewValue = aOriginalNode.getValue(); m_bToDefault = false; m_bChange= false; } //----------------------------------------------------------------------------- ValueChangeImpl* ValueMemberNode::DeferredImpl::collectChange() { data::ValueNodeAccess aOriginalNode = getOriginalNode(); UnoAny aOldValue = aOriginalNode.getValue(); if (!m_bChange) { return NULL; } else if (m_bToDefault) { OSL_ASSERT( m_aNewValue == aOriginalNode.getDefaultValue() ); return new ValueResetImpl( m_aNewValue, aOldValue ); } else { return new ValueReplaceImpl( m_aNewValue, aOldValue ); } } //----------------------------------------------------------------------------- ValueChangeImpl* ValueMemberNode::DeferredImpl::adjustToChange(ValueChange const& rExternalChange) { if (!m_bChange) { return NULL; } else if (m_bToDefault && rExternalChange.getMode() == ValueChange::changeDefault) { OSL_ASSERT( m_aNewValue == rExternalChange.getOldValue() ); m_aNewValue = rExternalChange.getNewValue(); return new ValueReplaceImpl(m_aNewValue, rExternalChange.getOldValue()); } else // return Surrogate - does not honor m_bToDefault { return new ValueReplaceImpl(m_aNewValue, m_aNewValue); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } } <|endoftext|>
<commit_before>/* * * Copyright (c) 2013 Julio Gutierrez * * Permission is hereby granted, free of charge, to any person obtaining a co$ * this software and associated documentation files (the "Software"), to deal$ * the Software without restriction, including without limitation the rights $ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell cop$ * the Software, and to permit persons to whom the Software is furnished to d$ * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in$ * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, F$ * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR$ * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHE$ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include "raspboop/Raspboop.h" namespace raspboop { namespace sensors { HCSR04::HCSR04() { EchoPin = -1; TriggerPin = -1; EchoStart = 0; EchoEnd = 0; Distance = 0; } HCSR04* HCSR04::Create(int ECHO, int TRIG) { // Using the same pins. Should notify user if(ECHO == TRIG) return NULL; HCSR04* H = (HCSR04*)malloc(sizeof(HCSR04)); // Not enough memory. Should notify user if(H == NULL) return NULL; new(H) HCSR04; H->EchoPin = ECHO; H->TriggerPin = TRIG; H->SetInputPin(ECHO); H->SetOutputPin(TRIG); digitalWrite(TRIG, LOW); return H; } void HCSR04::Sense() { // Pins are not set, should notify user if(EchoPin == -1 || TriggerPin == -1) return; EchoStart = EchoEnd = 0; digitalWrite(TriggerPin, HIGH); // HCSR04 manual states to wait 10 micros when triggered delayMicroseconds(10); digitalWrite(TRIG, LOW); while(digitalRead(EchoPin) == 0) EchoStart = (float)micros(); while(digitalRead(Echo)) EchoEnd = (float)micros(); Distance = (EchoEnd - EchoStart) * .017f; } HCSR04::~HCSR04() { } } /* sensors */ } /* raspboop */ <commit_msg>HCSR04: ReleasePins implementation<commit_after>/* * * Copyright (c) 2013 Julio Gutierrez * * Permission is hereby granted, free of charge, to any person obtaining a co$ * this software and associated documentation files (the "Software"), to deal$ * the Software without restriction, including without limitation the rights $ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell cop$ * the Software, and to permit persons to whom the Software is furnished to d$ * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in$ * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, F$ * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR$ * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHE$ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include "raspboop/Raspboop.h" namespace raspboop { namespace sensors { HCSR04::HCSR04() { EchoPin = -1; TriggerPin = -1; EchoStart = 0; EchoEnd = 0; Distance = 0; } HCSR04* HCSR04::Create(int ECHO, int TRIG) { // Using the same pins. Should notify user if(ECHO == TRIG) return NULL; HCSR04* H = (HCSR04*)malloc(sizeof(HCSR04)); // Not enough memory. Should notify user if(H == NULL) return NULL; new(H) HCSR04; H->EchoPin = ECHO; H->TriggerPin = TRIG; H->SetInputPin(ECHO); H->SetOutputPin(TRIG); digitalWrite(TRIG, LOW); return H; } void HCSR04::Sense() { // Pins are not set, should notify user if(EchoPin == -1 || TriggerPin == -1) return; EchoStart = EchoEnd = 0; digitalWrite(TriggerPin, HIGH); // HCSR04 manual states to wait 10 micros when triggered delayMicroseconds(10); digitalWrite(TRIG, LOW); while(digitalRead(EchoPin) == 0) EchoStart = (float)micros(); while(digitalRead(Echo)) EchoEnd = (float)micros(); Distance = (EchoEnd - EchoStart) * .017f; } void HCSR04::ReleasePins() { digitalWrite(TriggerPin, LOW); } HCSR04::~HCSR04() { } } /* sensors */ } /* raspboop */ <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <sstream> #include <map> #include <stdlib.h> #include <Variant.h> #include <Context.h> #include <Nibbler.h> #include <ISO8601.h> #include <Date.h> #include <text.h> #include <i18n.h> #include <DOM.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// DOM::DOM () { } //////////////////////////////////////////////////////////////////////////////// DOM::~DOM () { } //////////////////////////////////////////////////////////////////////////////// // DOM Supported References: // // Configuration: // rc.<name> // // System: // context.program // context.args // context.width // context.height // system.version // system.os // bool DOM::get (const std::string& name, Variant& value) { int len = name.length (); Nibbler n (name); // rc. --> context.config if (len > 3 && name.substr (0, 3) == "rc.") { std::string key = name.substr (3); auto c = context.config.find (key); if (c != context.config.end ()) { value = Variant (c->second); return true; } return false; } // context.* if (len > 8 && name.substr (0, 8) == "context.") { if (name == "context.program") { value = Variant (context.cli2.getBinary ()); return true; } else if (name == "context.args") { std::string commandLine; join (commandLine, " ", context.cli2._original_args); value = Variant (commandLine); return true; } else if (name == "context.width") { value = Variant (static_cast<int> (context.terminal_width ? context.terminal_width : context.getWidth ())); return true; } else if (name == "context.height") { value = Variant (static_cast<int> (context.terminal_height ? context.terminal_height : context.getHeight ())); return true; } else throw format (STRING_DOM_UNREC, name); } // TODO stats.<name> // system. --> Implement locally. if (len > 7 && name.substr (0, 7) == "system.") { // Taskwarrior version number. if (name == "system.version") { value = Variant (VERSION); return true; } // OS type. else if (name == "system.os") { #if defined (DARWIN) value = Variant ("Darwin"); #elif defined (SOLARIS) value = Variant ("Solaris"); #elif defined (CYGWIN) value = Variant ("Cygwin"); #elif defined (HAIKU) value = Variant ("Haiku"); #elif defined (OPENBSD) value = Variant ("OpenBSD"); #elif defined (FREEBSD) value = Variant ("FreeBSD"); #elif defined (NETBSD) value = Variant ("NetBSD"); #elif defined (LINUX) value = Variant ("Linux"); #elif defined (KFREEBSD) value = Variant ("GNU/kFreeBSD"); #elif defined (GNUHURD) value = Variant ("GNU/Hurd"); #else value = Variant (STRING_DOM_UNKNOWN); #endif return true; } else throw format (STRING_DOM_UNREC, name); } // Empty string if nothing is found. return false; } //////////////////////////////////////////////////////////////////////////////// // DOM Supported References: // // Relative or absolute attribute: // <attribute> // <id>.<attribute> // <uuid>.<attribute> // // Single tag: // tags.<word> // // Date type: // <date>.year // <date>.month // <date>.day // <date>.week // <date>.weekday // <date>.julian // <date>.hour // <date>.minute // <date>.second // // Annotations (entry is a date): // annotations.<N>.entry // annotations.<N>.description // bool DOM::get (const std::string& name, const Task& task, Variant& value) { // <attr> if (task.size () && name == "id") { value = Variant (static_cast<int> (task.id)); return true; } if (task.size () && name == "urgency") { value = Variant (task.urgency_c ()); return true; } // split name on '.' std::vector <std::string> elements; split (elements, name, '.'); if (elements.size () == 1) { std::string canonical; if (task.size () && context.cli2.canonicalize (canonical, "attribute", name)) { Column* column = context.columns[canonical]; if (column) { if (column->is_uda () && ! task.has (canonical)) { value = Variant (""); return true; } if (column->type () == "date") { auto numeric = task.get_date (canonical); if (numeric == 0) value = Variant (""); else value = Variant (numeric, Variant::type_date); } else if (column->type () == "duration" || canonical == "recur") value = Variant ((time_t) ISO8601p (task.get (canonical)), Variant::type_duration); else if (column->type () == "numeric") value = Variant (task.get_float (canonical)); else // string value = Variant (task.get (canonical)); return true; } } } else if (elements.size () > 1) { Task ref; Nibbler n (elements[0]); n.save (); int id; std::string uuid; bool proceed = false; if (n.getPartialUUID (uuid) && n.depleted ()) { if (uuid == task.get ("uuid")) ref = task; else context.tdb2.get (uuid, ref); proceed = true; } else { if (n.getInt (id) && n.depleted ()) { if (id == task.id) ref = task; else context.tdb2.get (id, ref); proceed = true; } } if (proceed) { if (elements[1] == "id") { value = Variant (static_cast<int> (ref.id)); return true; } else if (elements[1] == "urgency") { value = Variant (ref.urgency_c ()); return true; } std::string canonical; if (context.cli2.canonicalize (canonical, "attribute", elements[1])) { if (elements.size () == 2) { Column* column = context.columns[canonical]; if (column) { if (column->is_uda () && ! ref.has (canonical)) { value = Variant (""); return true; } if (column->type () == "date") { auto numeric = ref.get_date (canonical); if (numeric == 0) value = Variant (""); else value = Variant (numeric, Variant::type_date); } else if (column->type () == "duration") { auto period = ref.get (canonical); context.debug ("ref.get(" + canonical + ") --> " + period); ISO8601p iso; std::string::size_type cursor = 0; if (iso.parse (period, cursor)) value = Variant ((time_t) iso._value, Variant::type_duration); else value = Variant ((time_t) ISO8601p (ref.get (canonical)), Variant::type_duration); context.debug ("value --> " + (std::string) value); } else if (column->type () == "numeric") value = Variant (ref.get_float (canonical)); else value = Variant (ref.get (canonical)); return true; } } else if (elements.size () == 3) { // tags.<tag> if (canonical == "tags") { value = Variant (ref.hasTag (elements[2]) ? elements[2] : ""); return true; } Column* column = context.columns[canonical]; if (column && column->type () == "date") { // <date>.year // <date>.month // <date>.day // <date>.week // <date>.weekday // <date>.julian // <date>.hour // <date>.minute // <date>.second Date date (ref.get_date (canonical)); if (elements[2] == "year") { value = Variant (static_cast<int> (date.year ())); return true; } else if (elements[2] == "month") { value = Variant (static_cast<int> (date.month ())); return true; } else if (elements[2] == "day") { value = Variant (static_cast<int> (date.day ())); return true; } else if (elements[2] == "week") { value = Variant (static_cast<int> (date.week ())); return true; } else if (elements[2] == "weekday") { value = Variant (static_cast<int> (date.dayOfWeek ())); return true; } else if (elements[2] == "julian") { value = Variant (static_cast<int> (date.dayOfYear ())); return true; } else if (elements[2] == "hour") { value = Variant (static_cast<int> (date.hour ())); return true; } else if (elements[2] == "minute") { value = Variant (static_cast<int> (date.minute ())); return true; } else if (elements[2] == "second") { value = Variant (static_cast<int> (date.second ())); return true; } } } } else if (elements[1] == "annotations") { if (elements.size () == 4) { std::map <std::string, std::string> annos; ref.getAnnotations (annos); int a = strtol (elements[2].c_str (), NULL, 10); int count = 0; // Count off the 'a'th annotation. for (auto& i : annos) { if (++count == a) { if (elements[3] == "entry") { // annotation_1234567890 // 0 ^11 value = Variant ((time_t) strtol (i.first.substr (11).c_str (), NULL, 10), Variant::type_date); return true; } else if (elements[3] == "description") { value = Variant (i.second); return true; } } } } else if (elements.size () == 5) { std::map <std::string, std::string> annos; ref.getAnnotations (annos); int a = strtol (elements[2].c_str (), NULL, 10); int count = 0; // Count off the 'a'th annotation. for (auto& i : annos) { if (++count == a) { // <annotations>.<N>.entry.year // <annotations>.<N>.entry.month // <annotations>.<N>.entry.day // <annotations>.<N>.entry.week // <annotations>.<N>.entry.weekday // <annotations>.<N>.entry.julian // <annotations>.<N>.entry.hour // <annotations>.<N>.entry.minute // <annotations>.<N>.entry.second Date date (i.first.substr (11)); if (elements[4] == "year") { value = Variant (static_cast<int> (date.year ())); return true; } else if (elements[4] == "month") { value = Variant (static_cast<int> (date.month ())); return true; } else if (elements[4] == "day") { value = Variant (static_cast<int> (date.day ())); return true; } else if (elements[4] == "week") { value = Variant (static_cast<int> (date.week ())); return true; } else if (elements[4] == "weekday") { value = Variant (static_cast<int> (date.dayOfWeek ())); return true; } else if (elements[4] == "julian") { value = Variant (static_cast<int> (date.dayOfYear ())); return true; } else if (elements[4] == "hour") { value = Variant (static_cast<int> (date.hour ())); return true; } else if (elements[4] == "minute") { value = Variant (static_cast<int> (date.minute ())); return true; } else if (elements[4] == "second") { value = Variant (static_cast<int> (date.second ())); return true; } } } } } } } // Delegate to the context-free version of DOM::get. return this->get (name, value); } //////////////////////////////////////////////////////////////////////////////// <commit_msg>DOM: Factored out element size<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <sstream> #include <map> #include <stdlib.h> #include <Variant.h> #include <Context.h> #include <Nibbler.h> #include <ISO8601.h> #include <Date.h> #include <text.h> #include <i18n.h> #include <DOM.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// DOM::DOM () { } //////////////////////////////////////////////////////////////////////////////// DOM::~DOM () { } //////////////////////////////////////////////////////////////////////////////// // DOM Supported References: // // Configuration: // rc.<name> // // System: // context.program // context.args // context.width // context.height // system.version // system.os // bool DOM::get (const std::string& name, Variant& value) { int len = name.length (); Nibbler n (name); // rc. --> context.config if (len > 3 && name.substr (0, 3) == "rc.") { std::string key = name.substr (3); auto c = context.config.find (key); if (c != context.config.end ()) { value = Variant (c->second); return true; } return false; } // context.* if (len > 8 && name.substr (0, 8) == "context.") { if (name == "context.program") { value = Variant (context.cli2.getBinary ()); return true; } else if (name == "context.args") { std::string commandLine; join (commandLine, " ", context.cli2._original_args); value = Variant (commandLine); return true; } else if (name == "context.width") { value = Variant (static_cast<int> (context.terminal_width ? context.terminal_width : context.getWidth ())); return true; } else if (name == "context.height") { value = Variant (static_cast<int> (context.terminal_height ? context.terminal_height : context.getHeight ())); return true; } else throw format (STRING_DOM_UNREC, name); } // TODO stats.<name> // system. --> Implement locally. if (len > 7 && name.substr (0, 7) == "system.") { // Taskwarrior version number. if (name == "system.version") { value = Variant (VERSION); return true; } // OS type. else if (name == "system.os") { #if defined (DARWIN) value = Variant ("Darwin"); #elif defined (SOLARIS) value = Variant ("Solaris"); #elif defined (CYGWIN) value = Variant ("Cygwin"); #elif defined (HAIKU) value = Variant ("Haiku"); #elif defined (OPENBSD) value = Variant ("OpenBSD"); #elif defined (FREEBSD) value = Variant ("FreeBSD"); #elif defined (NETBSD) value = Variant ("NetBSD"); #elif defined (LINUX) value = Variant ("Linux"); #elif defined (KFREEBSD) value = Variant ("GNU/kFreeBSD"); #elif defined (GNUHURD) value = Variant ("GNU/Hurd"); #else value = Variant (STRING_DOM_UNKNOWN); #endif return true; } else throw format (STRING_DOM_UNREC, name); } // Empty string if nothing is found. return false; } //////////////////////////////////////////////////////////////////////////////// // DOM Supported References: // // Relative or absolute attribute: // <attribute> // <id>.<attribute> // <uuid>.<attribute> // // Single tag: // tags.<word> // // Date type: // <date>.year // <date>.month // <date>.day // <date>.week // <date>.weekday // <date>.julian // <date>.hour // <date>.minute // <date>.second // // Annotations (entry is a date): // annotations.<N>.entry // annotations.<N>.description // // This code emphasizes speed, hence 'id' being evaluated first. bool DOM::get (const std::string& name, const Task& task, Variant& value) { // <attr> if (task.size () && name == "id") { value = Variant (static_cast<int> (task.id)); return true; } if (task.size () && name == "urgency") { value = Variant (task.urgency_c ()); return true; } // split name on '.' std::vector <std::string> elements; split (elements, name, '.'); auto size = elements.size (); if (size == 1) { std::string canonical; if (task.size () && context.cli2.canonicalize (canonical, "attribute", name)) { Column* column = context.columns[canonical]; if (column) { if (column->is_uda () && ! task.has (canonical)) { value = Variant (""); return true; } if (column->type () == "date") { auto numeric = task.get_date (canonical); if (numeric == 0) value = Variant (""); else value = Variant (numeric, Variant::type_date); } else if (column->type () == "duration" || canonical == "recur") value = Variant ((time_t) ISO8601p (task.get (canonical)), Variant::type_duration); else if (column->type () == "numeric") value = Variant (task.get_float (canonical)); else // string value = Variant (task.get (canonical)); return true; } } } else if (size > 1) { Task ref; Nibbler n (elements[0]); n.save (); int id; std::string uuid; bool proceed = false; if (n.getPartialUUID (uuid) && n.depleted ()) { if (uuid == task.get ("uuid")) ref = task; else context.tdb2.get (uuid, ref); proceed = true; } else { if (n.getInt (id) && n.depleted ()) { if (id == task.id) ref = task; else context.tdb2.get (id, ref); proceed = true; } } if (proceed) { if (elements[1] == "id") { value = Variant (static_cast<int> (ref.id)); return true; } else if (elements[1] == "urgency") { value = Variant (ref.urgency_c ()); return true; } std::string canonical; if (context.cli2.canonicalize (canonical, "attribute", elements[1])) { if (size == 2) { Column* column = context.columns[canonical]; if (column) { if (column->is_uda () && ! ref.has (canonical)) { value = Variant (""); return true; } if (column->type () == "date") { auto numeric = ref.get_date (canonical); if (numeric == 0) value = Variant (""); else value = Variant (numeric, Variant::type_date); } else if (column->type () == "duration") { auto period = ref.get (canonical); context.debug ("ref.get(" + canonical + ") --> " + period); ISO8601p iso; std::string::size_type cursor = 0; if (iso.parse (period, cursor)) value = Variant ((time_t) iso._value, Variant::type_duration); else value = Variant ((time_t) ISO8601p (ref.get (canonical)), Variant::type_duration); context.debug ("value --> " + (std::string) value); } else if (column->type () == "numeric") value = Variant (ref.get_float (canonical)); else value = Variant (ref.get (canonical)); return true; } } else if (size == 3) { // tags.<tag> if (canonical == "tags") { value = Variant (ref.hasTag (elements[2]) ? elements[2] : ""); return true; } Column* column = context.columns[canonical]; if (column && column->type () == "date") { // <date>.year // <date>.month // <date>.day // <date>.week // <date>.weekday // <date>.julian // <date>.hour // <date>.minute // <date>.second Date date (ref.get_date (canonical)); if (elements[2] == "year") { value = Variant (static_cast<int> (date.year ())); return true; } else if (elements[2] == "month") { value = Variant (static_cast<int> (date.month ())); return true; } else if (elements[2] == "day") { value = Variant (static_cast<int> (date.day ())); return true; } else if (elements[2] == "week") { value = Variant (static_cast<int> (date.week ())); return true; } else if (elements[2] == "weekday") { value = Variant (static_cast<int> (date.dayOfWeek ())); return true; } else if (elements[2] == "julian") { value = Variant (static_cast<int> (date.dayOfYear ())); return true; } else if (elements[2] == "hour") { value = Variant (static_cast<int> (date.hour ())); return true; } else if (elements[2] == "minute") { value = Variant (static_cast<int> (date.minute ())); return true; } else if (elements[2] == "second") { value = Variant (static_cast<int> (date.second ())); return true; } } } } else if (elements[1] == "annotations") { if (size == 4) { std::map <std::string, std::string> annos; ref.getAnnotations (annos); int a = strtol (elements[2].c_str (), NULL, 10); int count = 0; // Count off the 'a'th annotation. for (auto& i : annos) { if (++count == a) { if (elements[3] == "entry") { // annotation_1234567890 // 0 ^11 value = Variant ((time_t) strtol (i.first.substr (11).c_str (), NULL, 10), Variant::type_date); return true; } else if (elements[3] == "description") { value = Variant (i.second); return true; } } } } else if (size == 5) { std::map <std::string, std::string> annos; ref.getAnnotations (annos); int a = strtol (elements[2].c_str (), NULL, 10); int count = 0; // Count off the 'a'th annotation. for (auto& i : annos) { if (++count == a) { // <annotations>.<N>.entry.year // <annotations>.<N>.entry.month // <annotations>.<N>.entry.day // <annotations>.<N>.entry.week // <annotations>.<N>.entry.weekday // <annotations>.<N>.entry.julian // <annotations>.<N>.entry.hour // <annotations>.<N>.entry.minute // <annotations>.<N>.entry.second Date date (i.first.substr (11)); if (elements[4] == "year") { value = Variant (static_cast<int> (date.year ())); return true; } else if (elements[4] == "month") { value = Variant (static_cast<int> (date.month ())); return true; } else if (elements[4] == "day") { value = Variant (static_cast<int> (date.day ())); return true; } else if (elements[4] == "week") { value = Variant (static_cast<int> (date.week ())); return true; } else if (elements[4] == "weekday") { value = Variant (static_cast<int> (date.dayOfWeek ())); return true; } else if (elements[4] == "julian") { value = Variant (static_cast<int> (date.dayOfYear ())); return true; } else if (elements[4] == "hour") { value = Variant (static_cast<int> (date.hour ())); return true; } else if (elements[4] == "minute") { value = Variant (static_cast<int> (date.minute ())); return true; } else if (elements[4] == "second") { value = Variant (static_cast<int> (date.second ())); return true; } } } } } } } // Delegate to the context-free version of DOM::get. return this->get (name, value); } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * Licensed under the MIT License (MIT) * * Copyright (c) 2013 AudioScience Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * avdecc_cmd_line_main.cpp * * AVDECC command line main implementation used for testing command line interface. */ #include <iostream> #include <fstream> #include <iomanip> #include <string> #include <vector> #include <cstdint> #include <cinttypes> #include <stdexcept> #include "cmd_line.h" #if defined(__MACH__) #include <readline/readline.h> #include <readline/history.h> #elif defined(__linux__) #include <readline/readline.h> #include <readline/history.h> #endif #if defined(__MACH__) || defined(__linux__) #include <unistd.h> #include <stdio.h> #include <string.h> // For TAB-completion #include "cli_argument.h" #include <set> #else #include "msvc\getopt.h" #endif using namespace std; extern "C" void notification_callback(void *user_obj, int32_t notification_type, uint64_t entity_id, uint16_t cmd_type, uint16_t desc_type, uint16_t desc_index, uint32_t cmd_status, void *notification_id) { if(notification_type == avdecc_lib::COMMAND_TIMEOUT || notification_type == avdecc_lib::RESPONSE_RECEIVED) { const char *cmd_name; const char *desc_name; const char *cmd_status_name; if(cmd_type < avdecc_lib::CMD_LOOKUP) { cmd_name = cmd_line::utility->aem_cmd_value_to_name(cmd_type); desc_name = cmd_line::utility->aem_desc_value_to_name(desc_type); cmd_status_name = cmd_line::utility->aem_cmd_status_value_to_name(cmd_status); } else { cmd_name = cmd_line::utility->acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP); desc_name = "NULL"; cmd_status_name = cmd_line::utility->acmp_cmd_status_value_to_name(cmd_status); } printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %s, %s, %d, %s, %p)\n", cmd_line::utility->notification_value_to_name(notification_type), entity_id, cmd_name, desc_name, desc_index, cmd_status_name, notification_id); } else { printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %d, %d, %d, %d, %p)\n", cmd_line::utility->notification_value_to_name(notification_type), entity_id, cmd_type, desc_type, desc_index, cmd_status, notification_id); } } extern "C" void log_callback(void *user_obj, int32_t log_level, const char *log_msg, int32_t time_stamp_ms) { printf("\n[LOG] %s (%s)\n", cmd_line::utility->logging_level_value_to_name(log_level), log_msg); } #if defined(__MACH__) || defined(__linux__) const cli_command *top_level_command; const cli_command *current_command; int complettion_arg_index = 0; void split(const std::string &s, char delim, std::queue<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) elems.push(item); } char *command_generator(const char *text, int state) { static std::list<std::string> completion_options; static int len; if (!current_command) return NULL; if (!state) { // New word to complete then set up the options to match // Cache the len for efficiency len = strlen(text); // Try the sub-commands of the current command completion_options = current_command->get_sub_command_names(); if (!completion_options.size()) { // If there are no sub-commands then try the arguments std::vector<cli_argument*> args; std::set<std::string> arg_options; // There can be multiple arguments at a given index as there // can be multiple command formats current_command->get_args(complettion_arg_index, args); for (std::vector<cli_argument*>::iterator iter = args.begin(); iter != args.end(); ++iter) { (*iter)->get_completion_options(arg_options); } completion_options.insert(completion_options.end(), arg_options.begin(), arg_options.end()); } } // Return the next name which matches from the command list while (completion_options.size()) { std::string sub_command = completion_options.front(); completion_options.pop_front(); if (strncmp(sub_command.c_str(), text, len) == 0) return (strdup(sub_command.c_str())); } // There are no matches return NULL; } char **command_completer(const char *text, int start, int end) { if (start == 0) { // Start of a new command current_command = top_level_command; } else { // In the middle of a command line, use the rest of the line // to find the right command to provide completion options std::string cmd_path(rl_line_buffer); cmd_path = cmd_path.substr(0, start); std::queue<std::string, std::deque<std::string>> cmd_path_queue; split(cmd_path, ' ', cmd_path_queue); std::string prefix; current_command = top_level_command->get_sub_command(cmd_path_queue, prefix); // There can be remaining parts of the command which mean that an argument // value is being completed instead complettion_arg_index = cmd_path_queue.size(); } char **matches = rl_completion_matches(text, command_generator); return matches; } char *null_completer(const char *text, int state) { return NULL; } #endif static void usage(char *argv[]) { std::cerr << "Usage: " << argv[0] << " [-d] [-i interface]" << std::endl; std::cerr << " -t : Sets test mode which disables checks" << std::endl; std::cerr << " -i interface : Sets the name of the interface to use" << std::endl; std::cerr << " -l log_level : Sets the log level to use." << std::endl; std::cerr << log_level_help << std::endl; exit(1); } int main(int argc, char *argv[]) { bool test_mode = false; int error = 0; char *interface = NULL; int c = 0; int32_t log_level = 0; while ((c = getopt(argc, argv, "ti:l:")) != -1) { switch (c) { case 't': test_mode = true; break; case 'i': interface = optarg; break; case 'l': log_level = atoi(optarg); break; case ':': fprintf(stderr, "Option -%c requires an operand\n", optopt); error++; break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); error++; break; } } for ( ; optind < argc; optind++) { error++; // Unused arguments } if (error) { usage(argv); } if (test_mode) { // Ensure that stdout is not buffered setvbuf(stdout, NULL, _IOLBF, 0); } cmd_line avdecc_cmd_line_ref(notification_callback, log_callback, test_mode, interface, log_level); std::vector<std::string> input_argv; size_t pos = 0; bool done = false; bool is_input_valid = false; std::string cmd_input_orig; #if defined(__MACH__) || defined(__linux__) char* input; // Set up the state for command-line completion top_level_command = avdecc_cmd_line_ref.get_commands(); rl_attempted_completion_function = command_completer; #endif // Override to prevent filename completion #if defined(__MACH__) rl_completion_entry_function = (Function *)null_completer; #elif defined(__linux__) rl_completion_entry_function = null_completer; #endif std::cout << "\nEnter \"help\" for a list of valid commands." << std::endl; while(!done) { #if defined(__MACH__) || defined(__linux__) input = readline("$ "); if (!input) break; if (strlen(input) == 0) continue; std::string cmd_input(input); cmd_input_orig = cmd_input; add_history(input); #else std::string cmd_input; printf("\n>"); std::getline(std::cin, cmd_input); cmd_input_orig = cmd_input; #endif while((pos = cmd_input.find(" ")) != std::string::npos) { if (pos) input_argv.push_back(cmd_input.substr(0, pos)); cmd_input.erase(0, pos + 1); } if(cmd_input.length() && cmd_input != " ") { input_argv.push_back(cmd_input); } if(avdecc_cmd_line_ref.is_output_redirected()) { std::cout << "\n> " << cmd_input_orig << std::endl; } done = avdecc_cmd_line_ref.handle(input_argv); is_input_valid = false; input_argv.clear(); #if defined(__MACH__) || defined(__linux__) free(input); #endif } return 0; } <commit_msg>cmdlineapp: use enum for log level<commit_after>/* * Licensed under the MIT License (MIT) * * Copyright (c) 2013 AudioScience Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * avdecc_cmd_line_main.cpp * * AVDECC command line main implementation used for testing command line interface. */ #include <iostream> #include <fstream> #include <iomanip> #include <string> #include <vector> #include <cstdint> #include <cinttypes> #include <stdexcept> #include "cmd_line.h" #if defined(__MACH__) #include <readline/readline.h> #include <readline/history.h> #elif defined(__linux__) #include <readline/readline.h> #include <readline/history.h> #endif #if defined(__MACH__) || defined(__linux__) #include <unistd.h> #include <stdio.h> #include <string.h> // For TAB-completion #include "cli_argument.h" #include <set> #else #include "msvc\getopt.h" #endif using namespace std; extern "C" void notification_callback(void *user_obj, int32_t notification_type, uint64_t entity_id, uint16_t cmd_type, uint16_t desc_type, uint16_t desc_index, uint32_t cmd_status, void *notification_id) { if(notification_type == avdecc_lib::COMMAND_TIMEOUT || notification_type == avdecc_lib::RESPONSE_RECEIVED) { const char *cmd_name; const char *desc_name; const char *cmd_status_name; if(cmd_type < avdecc_lib::CMD_LOOKUP) { cmd_name = cmd_line::utility->aem_cmd_value_to_name(cmd_type); desc_name = cmd_line::utility->aem_desc_value_to_name(desc_type); cmd_status_name = cmd_line::utility->aem_cmd_status_value_to_name(cmd_status); } else { cmd_name = cmd_line::utility->acmp_cmd_value_to_name(cmd_type - avdecc_lib::CMD_LOOKUP); desc_name = "NULL"; cmd_status_name = cmd_line::utility->acmp_cmd_status_value_to_name(cmd_status); } printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %s, %s, %d, %s, %p)\n", cmd_line::utility->notification_value_to_name(notification_type), entity_id, cmd_name, desc_name, desc_index, cmd_status_name, notification_id); } else { printf("\n[NOTIFICATION] (%s, 0x%" PRIx64 ", %d, %d, %d, %d, %p)\n", cmd_line::utility->notification_value_to_name(notification_type), entity_id, cmd_type, desc_type, desc_index, cmd_status, notification_id); } } extern "C" void log_callback(void *user_obj, int32_t log_level, const char *log_msg, int32_t time_stamp_ms) { printf("\n[LOG] %s (%s)\n", cmd_line::utility->logging_level_value_to_name(log_level), log_msg); } #if defined(__MACH__) || defined(__linux__) const cli_command *top_level_command; const cli_command *current_command; int complettion_arg_index = 0; void split(const std::string &s, char delim, std::queue<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) elems.push(item); } char *command_generator(const char *text, int state) { static std::list<std::string> completion_options; static int len; if (!current_command) return NULL; if (!state) { // New word to complete then set up the options to match // Cache the len for efficiency len = strlen(text); // Try the sub-commands of the current command completion_options = current_command->get_sub_command_names(); if (!completion_options.size()) { // If there are no sub-commands then try the arguments std::vector<cli_argument*> args; std::set<std::string> arg_options; // There can be multiple arguments at a given index as there // can be multiple command formats current_command->get_args(complettion_arg_index, args); for (std::vector<cli_argument*>::iterator iter = args.begin(); iter != args.end(); ++iter) { (*iter)->get_completion_options(arg_options); } completion_options.insert(completion_options.end(), arg_options.begin(), arg_options.end()); } } // Return the next name which matches from the command list while (completion_options.size()) { std::string sub_command = completion_options.front(); completion_options.pop_front(); if (strncmp(sub_command.c_str(), text, len) == 0) return (strdup(sub_command.c_str())); } // There are no matches return NULL; } char **command_completer(const char *text, int start, int end) { if (start == 0) { // Start of a new command current_command = top_level_command; } else { // In the middle of a command line, use the rest of the line // to find the right command to provide completion options std::string cmd_path(rl_line_buffer); cmd_path = cmd_path.substr(0, start); std::queue<std::string, std::deque<std::string>> cmd_path_queue; split(cmd_path, ' ', cmd_path_queue); std::string prefix; current_command = top_level_command->get_sub_command(cmd_path_queue, prefix); // There can be remaining parts of the command which mean that an argument // value is being completed instead complettion_arg_index = cmd_path_queue.size(); } char **matches = rl_completion_matches(text, command_generator); return matches; } char *null_completer(const char *text, int state) { return NULL; } #endif static void usage(char *argv[]) { std::cerr << "Usage: " << argv[0] << " [-d] [-i interface]" << std::endl; std::cerr << " -t : Sets test mode which disables checks" << std::endl; std::cerr << " -i interface : Sets the name of the interface to use" << std::endl; std::cerr << " -l log_level : Sets the log level to use." << std::endl; std::cerr << log_level_help << std::endl; exit(1); } int main(int argc, char *argv[]) { bool test_mode = false; int error = 0; char *interface = NULL; int c = 0; int32_t log_level = avdecc_lib::LOGGING_LEVEL_ERROR; while ((c = getopt(argc, argv, "ti:l:")) != -1) { switch (c) { case 't': test_mode = true; break; case 'i': interface = optarg; break; case 'l': log_level = atoi(optarg); break; case ':': fprintf(stderr, "Option -%c requires an operand\n", optopt); error++; break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); error++; break; } } for ( ; optind < argc; optind++) { error++; // Unused arguments } if (error) { usage(argv); } if (test_mode) { // Ensure that stdout is not buffered setvbuf(stdout, NULL, _IOLBF, 0); } cmd_line avdecc_cmd_line_ref(notification_callback, log_callback, test_mode, interface, log_level); std::vector<std::string> input_argv; size_t pos = 0; bool done = false; bool is_input_valid = false; std::string cmd_input_orig; #if defined(__MACH__) || defined(__linux__) char* input; // Set up the state for command-line completion top_level_command = avdecc_cmd_line_ref.get_commands(); rl_attempted_completion_function = command_completer; #endif // Override to prevent filename completion #if defined(__MACH__) rl_completion_entry_function = (Function *)null_completer; #elif defined(__linux__) rl_completion_entry_function = null_completer; #endif std::cout << "\nEnter \"help\" for a list of valid commands." << std::endl; while(!done) { #if defined(__MACH__) || defined(__linux__) input = readline("$ "); if (!input) break; if (strlen(input) == 0) continue; std::string cmd_input(input); cmd_input_orig = cmd_input; add_history(input); #else std::string cmd_input; printf("\n>"); std::getline(std::cin, cmd_input); cmd_input_orig = cmd_input; #endif while((pos = cmd_input.find(" ")) != std::string::npos) { if (pos) input_argv.push_back(cmd_input.substr(0, pos)); cmd_input.erase(0, pos + 1); } if(cmd_input.length() && cmd_input != " ") { input_argv.push_back(cmd_input); } if(avdecc_cmd_line_ref.is_output_redirected()) { std::cout << "\n> " << cmd_input_orig << std::endl; } done = avdecc_cmd_line_ref.handle(input_argv); is_input_valid = false; input_argv.clear(); #if defined(__MACH__) || defined(__linux__) free(input); #endif } return 0; } <|endoftext|>
<commit_before>// Font.cc // Copyright (c) 2002 Henrik Kinnunen (fluxgen@linuxmail.org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //$Id: Font.cc,v 1.6 2002/05/02 07:19:02 fluxgen Exp $ #include "Font.hh" #include "StringUtil.hh" //use gnu extensions #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif //_GNU_SOURCE #include <cstdarg> #include <iostream> #include <cassert> #include <string> #include <cstdio> #ifdef HAVE_CONFIG_H # include "../config.h" #endif // HAVE_CONFIG_H #ifdef HAVE_SETLOCALE #include <locale.h> #endif //HAVE_SETLOCALE #include "i18n.hh" namespace FbTk { bool Font::m_multibyte = false; //TODO: fix multibyte Font::Font(Display *display, const char *name):m_loaded(false), m_display(display) { m_font.fontstruct = 0; m_font.set_extents = 0; m_font.set = 0; //TODO: should only be done once m_multibyte = I18n::instance()->multibyte(); if (name!=0) { load(name); } } Font::~Font() { freeFont(); } bool Font::load(const char *name) { if (m_multibyte) { XFontSet set = createFontSet(m_display, name); if (!set) return false; freeFont(); m_font.set = set; m_font.set_extents = XExtentsOfFontSet(m_font.set); } else { XFontStruct *font = XLoadQueryFont(m_display, name); if (font==0) return false; freeFont(); //free old font m_font.fontstruct = font; //set new font } m_loaded = true; //mark the font loaded return true; } bool Font::loadFromDatabase(XrmDatabase &database, const char *rname, const char *rclass) { assert(rname); assert(rclass); XrmValue value; char *value_type; //this should probably be moved to a Database class so we can keep //track of database init if (XrmGetResource(database, rname, rclass, &value_type, &value)) { #ifdef DEBUG std::cerr<<__FILE__<<"("<<__LINE__<<"): Load font:"<<value.addr<<std::endl; #endif return load(value.addr); } return false; } unsigned int Font::getTextWidth(const char *text, unsigned int size) const { if (text==0) return 0; if (multibyte()) { XRectangle ink, logical; XmbTextExtents(m_font.set, text, size, &ink, &logical); return logical.width; } else { assert(m_font.fontstruct); return XTextWidth(m_font.fontstruct, text, size); } return 0; } unsigned int Font::getHeight() const { if (multibyte() && getFontSetExtents()) return getFontSetExtents()->max_ink_extent.height; if (getFontStruct()) return getFontStruct()->ascent + getFontStruct()->descent; return 0; } XFontSet Font::createFontSet(Display *display, const char *fontname) { XFontSet fs; const int FONT_ELEMENT_SIZE=50; char **missing, *def = "-"; int nmissing, pixel_size = 0, buf_size = 0; char weight[FONT_ELEMENT_SIZE], slant[FONT_ELEMENT_SIZE]; fs = XCreateFontSet(display, fontname, &missing, &nmissing, &def); if (fs && (! nmissing)) return fs; #ifdef HAVE_SETLOCALE if (! fs) { if (nmissing) XFreeStringList(missing); setlocale(LC_CTYPE, "C"); fs = XCreateFontSet(display, fontname, &missing, &nmissing, &def); setlocale(LC_CTYPE, ""); } #endif // HAVE_SETLOCALE if (fs) { XFontStruct **fontstructs; char **fontnames; XFontsOfFontSet(fs, &fontstructs, &fontnames); fontname = fontnames[0]; } getFontElement(fontname, weight, FONT_ELEMENT_SIZE, "-medium-", "-bold-", "-demibold-", "-regular-", 0); getFontElement(fontname, slant, FONT_ELEMENT_SIZE, "-r-", "-i-", "-o-", "-ri-", "-ro-", 0); getFontSize(fontname, &pixel_size); if (! strcmp(weight, "*")) std::strncpy(weight, "medium", FONT_ELEMENT_SIZE); if (! strcmp(slant, "*")) std::strncpy(slant, "r", FONT_ELEMENT_SIZE); if (pixel_size < 3) pixel_size = 3; else if (pixel_size > 97) pixel_size = 97; buf_size = strlen(fontname) + (FONT_ELEMENT_SIZE * 2) + 64; char *pattern2 = new char[buf_size]; snprintf(pattern2, buf_size - 1, "%s," "-*-*-%s-%s-*-*-%d-*-*-*-*-*-*-*," "-*-*-*-*-*-*-%d-*-*-*-*-*-*-*,*", fontname, weight, slant, pixel_size, pixel_size); fontname = pattern2; if (nmissing) XFreeStringList(missing); if (fs) XFreeFontSet(display, fs); fs = XCreateFontSet(display, fontname, &missing, &nmissing, &def); delete [] pattern2; return fs; } const char *Font::getFontElement(const char *pattern, char *buf, int bufsiz, ...) { const char *p, *v; char *p2; va_list va; va_start(va, bufsiz); buf[bufsiz-1] = 0; buf[bufsiz-2] = '*'; while((v = va_arg(va, char *)) != 0) { p = StringUtil::strcasestr(pattern, v); if (p) { std::strncpy(buf, p+1, bufsiz-2); p2 = strchr(buf, '-'); if (p2) *p2=0; va_end(va); return p; } } va_end(va); std::strncpy(buf, "*", bufsiz); return 0; } const char *Font::getFontSize(const char *pattern, int *size) { const char *p; const char *p2=0; int n=0; for (p=pattern; 1; p++) { if (!*p) { if (p2!=0 && n>1 && n<72) { *size = n; return p2+1; } else { *size = 16; return 0; } } else if (*p=='-') { if (n>1 && n<72 && p2!=0) { *size = n; return p2+1; } p2=p; n=0; } else if (*p>='0' && *p<='9' && p2!=0) { n *= 10; n += *p-'0'; } else { p2=0; n=0; } } } void Font::freeFont() { //free memory if (m_font.fontstruct!=0) XFreeFont(m_display, m_font.fontstruct); if (m_font.set) XFreeFontSet(m_display, m_font.set); //clear struct m_font.fontstruct = 0; m_font.set = 0; m_font.set_extents = 0; m_loaded = false; //mark the font not loaded } }; <commit_msg>removed dep on i18n and used MB_CUR_MAX direct<commit_after>// Font.cc // Copyright (c) 2002 Henrik Kinnunen (fluxgen@linuxmail.org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //$Id: Font.cc,v 1.7 2002/08/04 15:36:19 fluxgen Exp $ #include "Font.hh" #include "StringUtil.hh" #ifdef HAVE_CONFIG_H #include "../config.h" #endif // HAVE_CONFIG_H //use gnu extensions #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif //_GNU_SOURCE #include <cstdarg> #include <iostream> #include <cassert> #include <string> #include <cstdio> #ifdef HAVE_SETLOCALE #include <locale.h> #endif //HAVE_SETLOCALE namespace FbTk { bool Font::m_multibyte = false; //TODO: fix multibyte Font::Font(Display *display, const char *name):m_loaded(false), m_display(display) { m_font.fontstruct = 0; m_font.set_extents = 0; m_font.set = 0; // MB_CUR_MAX returns the size of a char in the current locale if (MB_CUR_MAX > 1) m_multibyte = true; if (name!=0) { load(name); } } Font::~Font() { freeFont(); } bool Font::load(const char *name) { if (m_multibyte) { XFontSet set = createFontSet(m_display, name); if (!set) return false; freeFont(); m_font.set = set; m_font.set_extents = XExtentsOfFontSet(m_font.set); } else { XFontStruct *font = XLoadQueryFont(m_display, name); if (font==0) return false; freeFont(); //free old font m_font.fontstruct = font; //set new font } m_loaded = true; //mark the font loaded return true; } bool Font::loadFromDatabase(XrmDatabase &database, const char *rname, const char *rclass) { assert(rname); assert(rclass); XrmValue value; char *value_type; //This should probably be moved to a Database class so we can keep //track of database init if (XrmGetResource(database, rname, rclass, &value_type, &value)) { #ifdef DEBUG std::cerr<<__FILE__<<"("<<__LINE__<<"): Load font:"<<value.addr<<std::endl; #endif return load(value.addr); } return false; } unsigned int Font::textWidth(const char *text, unsigned int size) const { if (text==0) return 0; if (multibyte()) { XRectangle ink, logical; XmbTextExtents(m_font.set, text, size, &ink, &logical); return logical.width; } else { assert(m_font.fontstruct); return XTextWidth(m_font.fontstruct, text, size); } return 0; } unsigned int Font::height() const { if (!isLoaded()) return 0; if (multibyte() && fontSetExtents()) return fontSetExtents()->max_ink_extent.height; if (fontStruct()) return fontStruct()->ascent + fontStruct()->descent; return 0; } XFontSet Font::createFontSet(Display *display, const char *fontname) { XFontSet fs; const int FONT_ELEMENT_SIZE=50; char **missing, *def = "-"; int nmissing, pixel_size = 0, buf_size = 0; char weight[FONT_ELEMENT_SIZE], slant[FONT_ELEMENT_SIZE]; fs = XCreateFontSet(display, fontname, &missing, &nmissing, &def); if (fs && (! nmissing)) return fs; #ifdef HAVE_SETLOCALE if (! fs) { if (nmissing) XFreeStringList(missing); setlocale(LC_CTYPE, "C"); fs = XCreateFontSet(display, fontname, &missing, &nmissing, &def); setlocale(LC_CTYPE, ""); } #endif // HAVE_SETLOCALE if (fs) { XFontStruct **fontstructs; char **fontnames; XFontsOfFontSet(fs, &fontstructs, &fontnames); fontname = fontnames[0]; } getFontElement(fontname, weight, FONT_ELEMENT_SIZE, "-medium-", "-bold-", "-demibold-", "-regular-", 0); getFontElement(fontname, slant, FONT_ELEMENT_SIZE, "-r-", "-i-", "-o-", "-ri-", "-ro-", 0); getFontSize(fontname, &pixel_size); if (! strcmp(weight, "*")) std::strncpy(weight, "medium", FONT_ELEMENT_SIZE); if (! strcmp(slant, "*")) std::strncpy(slant, "r", FONT_ELEMENT_SIZE); if (pixel_size < 3) pixel_size = 3; else if (pixel_size > 97) pixel_size = 97; buf_size = strlen(fontname) + (FONT_ELEMENT_SIZE * 2) + 64; char *pattern2 = new char[buf_size]; snprintf(pattern2, buf_size - 1, "%s," "-*-*-%s-%s-*-*-%d-*-*-*-*-*-*-*," "-*-*-*-*-*-*-%d-*-*-*-*-*-*-*,*", fontname, weight, slant, pixel_size, pixel_size); fontname = pattern2; if (nmissing) XFreeStringList(missing); if (fs) XFreeFontSet(display, fs); fs = XCreateFontSet(display, fontname, &missing, &nmissing, &def); delete [] pattern2; return fs; } const char *Font::getFontElement(const char *pattern, char *buf, int bufsiz, ...) { const char *p, *v; char *p2; va_list va; va_start(va, bufsiz); buf[bufsiz-1] = 0; buf[bufsiz-2] = '*'; while((v = va_arg(va, char *)) != 0) { p = StringUtil::strcasestr(pattern, v); if (p) { std::strncpy(buf, p+1, bufsiz-2); p2 = strchr(buf, '-'); if (p2) *p2=0; va_end(va); return p; } } va_end(va); std::strncpy(buf, "*", bufsiz); return 0; } const char *Font::getFontSize(const char *pattern, int *size) { const char *p; const char *p2=0; int n=0; for (p=pattern; 1; p++) { if (!*p) { if (p2!=0 && n>1 && n<72) { *size = n; return p2+1; } else { *size = 16; return 0; } } else if (*p=='-') { if (n>1 && n<72 && p2!=0) { *size = n; return p2+1; } p2=p; n=0; } else if (*p>='0' && *p<='9' && p2!=0) { n *= 10; n += *p-'0'; } else { p2=0; n=0; } } } void Font::freeFont() { //free memory if (m_font.fontstruct!=0) XFreeFont(m_display, m_font.fontstruct); if (m_font.set) XFreeFontSet(m_display, m_font.set); //clear struct m_font.fontstruct = 0; m_font.set = 0; m_font.set_extents = 0; m_loaded = false; //mark the font not loaded } }; <|endoftext|>
<commit_before> void check(int mxn, int x) { bool kill = true; int n = randint(1,mxn); polygon p; rep(i,0,n) { p.push_back(point(randint(0,x), randint(0,x))); } int cnt = convex_hull(p); polygon q; rep(i,0,cnt) q.push_back(hull[i]); rep(i,0,size(q)) { rep(j,0,i) { assert_not_equal(q[i], q[j], kill); } } if (size(q) >= 3) { rep(i,0,size(q)) { int j = (i+1) % size(q), k = (i+2) % size(q); assert_true(ccw(q[i], q[j], q[k]) < 0, kill); } rep(i,0,size(p)) { assert_true(point_in_polygon(q, p[i]) <= 0, kill); } } } void test() { /* Field testing: UVa 681 */ polygon p; p.push_back(point(1,1)); p.push_back(point(2,2)); p.push_back(point(3,3)); p.push_back(point(4,4)); p.push_back(point(1,-1)); p.push_back(point(2,-2)); p.push_back(point(3,-3)); p.push_back(point(4,-4)); int cnt = convex_hull(p); rep(i,0,cnt) { cout << hull[i] << endl; } return; rep(n,1,20) { rep(k,1,100) { rep(it,0,1000) check(n,k); } } } <commit_msg>comment out debug code<commit_after> void check(int mxn, int x) { bool kill = true; int n = randint(1,mxn); polygon p; rep(i,0,n) { p.push_back(point(randint(0,x), randint(0,x))); } int cnt = convex_hull(p); polygon q; rep(i,0,cnt) q.push_back(hull[i]); rep(i,0,size(q)) { rep(j,0,i) { assert_not_equal(q[i], q[j], kill); } } if (size(q) >= 3) { rep(i,0,size(q)) { int j = (i+1) % size(q), k = (i+2) % size(q); assert_true(ccw(q[i], q[j], q[k]) < 0, kill); } rep(i,0,size(p)) { assert_true(point_in_polygon(q, p[i]) <= 0, kill); } } } void test() { /* Field testing: UVa 681 */ // polygon p; // p.push_back(point(1,1)); // p.push_back(point(2,2)); // p.push_back(point(3,3)); // p.push_back(point(4,4)); // p.push_back(point(1,-1)); // p.push_back(point(2,-2)); // p.push_back(point(3,-3)); // p.push_back(point(4,-4)); // // int cnt = convex_hull(p); // rep(i,0,cnt) { // cout << hull[i] << endl; // } // // return; rep(n,1,20) { rep(k,1,100) { rep(it,0,1000) check(n,k); } } } <|endoftext|>
<commit_before>#include <vector> #include <string> #include <sstream> #include <iostream> #include "../include/munchar.hpp" #include "../include/munchar_lexemes.hpp" using namespace std; using namespace Munchar; using namespace Munchar::Lexemes; constexpr auto import_kwd = "@import"_lit ^ !id_body; constexpr auto optional_kwd = "@optional"_lit ^ !id_body; constexpr auto func_kwd = "@func"_lit ^ !id_body; constexpr auto namespace_kwd = "@namespace"_lit ^ !id_body; constexpr auto open_kwd = "@open"_lit ^ !id_body; constexpr auto read_kwd = "read"_lit ^ !(id_body | colon); constexpr auto position_kwd = ("top"_lit | "bottom"_lit | "before"_lit | "after"_lit) ^ !(id_body | colon); constexpr auto ts_identifier = +'$'_lit | (id_start ^ *(id_body | '$'_lit)); constexpr auto gvar = '$'_lit ^ +id_body; constexpr auto lvar = '%'_lit ^ +id_body; using Positions = vector<size_t>; Positions lparens; Positions rparens; Positions lbraces; Positions rbraces; Positions commas; Positions dots; Positions gvars; Positions lvars; Positions identifiers; Positions attributes; Positions imports; Positions optionals; Positions funcs; Positions namespaces; Positions opens; int main() { stringstream ss; for (char c = 0; (c = getchar()) != EOF; ss << c) ; auto src = ss.str().c_str(); auto start = src; while (*src) { switch (*src) { case ' ': case '\t': case '\n': case '\r': { src = whitespace(src); } break; case '/': { if (src = c_comment(src)) blah; else if (src = cpp_comment(src)) blah; else if (src = slash_regexp(src)) blah; else error; } break; case '#': { src = sh_comment(src); } break; case '@': { if (src = import_kwd(src)) blah; else if (src = optional_kwd(src)) blah; else if (src = func_kwd(src)) blah; else if (src = namespace_kwd(src)) blah; else if (src = open_kwd(src)) blah; else error; } break; case '+': { ++src; } break; case '"': case '\'': { if (src = Lexemes::string(src)) blah; else error; } break; case '`': { if (src = backquote_regexp(src)) blah; else error; } break; case '(': { ++src; } break; case ')': { ++src; } break; case '{': { ++src; } break; case '}': { ++src; } break; case '.': { ++src; } break; case ',': { ++src; } break; case '=': { ++src; } break; case '$': { if (src = gvar(src)) blah; else src = ts_identifier(src); } break; case '%': { if (src = lvar(src)) blah; else error; } break; default: { if (src = position_kwd(src)) check_for_attr; else if (src = read_kwd(src)) check_for_attr; else if (src = ts_identifier(src)) check_for_attr; else if (src = attr_name(src)) blah; else if (src = number(src)) blah; else error; } break; } } return 0; }<commit_msg>fleshing out the sample tokenizer<commit_after>#include <vector> #include <string> #include <sstream> #include <iostream> #include <utility> #include "../include/munchar.hpp" #include "../include/munchar_lexemes.hpp" using namespace std; using namespace Munchar; using namespace Munchar::Lexemes; constexpr auto import_kwd = "@import"_lit ^ !id_body; constexpr auto optional_kwd = "@optional"_lit ^ !id_body; constexpr auto func_kwd = "@func"_lit ^ !id_body; constexpr auto namespace_kwd = "@namespace"_lit ^ !id_body; constexpr auto open_kwd = "@open"_lit ^ !id_body; constexpr auto read_kwd = "read"_lit ^ !(id_body | colon); constexpr auto position_kwd = ("top"_lit | "bottom"_lit | "before"_lit | "after"_lit) ^ !(id_body | colon); constexpr auto ts_identifier = +'$'_lit | (id_start ^ *(id_body | '$'_lit)); constexpr auto attr_name = (id_start | colon) ^ *(id_body | "-:."_cls); constexpr auto type_name = P(::isupper) ^ *id_body; constexpr auto gvar = '$'_lit ^ +id_body; constexpr auto lvar = '%'_lit ^ +id_body; constexpr auto ts_path = +(id_body | "-+.*?:\\/"_cls); constexpr auto slash_regexp = slash ^ (escape_seq | (!"/\\"_cls ^ _)) ^ slash ^ *"imxouesn"_cls; constexpr auto bq_regexp = backquote ^ (escape_seq | (!"`\\"_cls ^ _)) ^ backquote ^ *"imxouesn"_cls; enum class Tritium_Token { lparen, rparen, lbrace, rbrace, comma, dot, equal, plus, string, regexp, pos, gvar, lvar, kwd, id, type, path, ns, open, func, import, optional, read, comment }; struct Lexeme { Tritium_Token t; const char* b; const char* e; constexpr Lexeme(Tritium_Token tok, const char* beg, const char* end) : t(tok), b(beg), e(end) { } }; vector<Lexeme> lexemes; int main() { stringstream ss; for (char c = 0; (c = getchar()) != EOF; ss << c) ; auto src = ss.str().c_str(); auto start = src, pos = src; while (*src) { switch (*src) { case ' ': case '\t': case '\n': case '\r': { pos = whitespace(src); } break; case '/': { if ((pos = c_comment(src)) || (pos = cpp_comment(src))) { lexemes.push_back(Lexeme(Tritium_Token::comment, src, pos)); } else if (pos = slash_regexp(src)) { lexemes.push_back(Lexeme(Tritium_Token::regexp, src, pos)); } else { throw "malformed comment or regular expression"; } } break; case '#': { pos = sh_comment(src); lexemes.push_back(Lexeme(Tritium_Token::comment, src, pos)); } break; case '@': { if (pos = import_kwd(src)) { lexemes.push_back(Lexeme(Tritium_Token::import, src, pos)); } else if (pos = optional_kwd(src)) { lexemes.push_back(Lexeme(Tritium_Token::optional, src, pos)); } else if (pos = func_kwd(src)) { lexemes.push_back(Lexeme(Tritium_Token::func, src, pos)); } else if (pos = namespace_kwd(src)) { lexemes.push_back(Lexeme(Tritium_Token::ns, src, pos)); } else if (pos = open_kwd(src)) { lexemes.push_back(Lexeme(Tritium_Token::open, src, pos)); } else { throw "unrecognized directive"; } } break; case '+': { lexemes.push_back(Lexeme(Tritium_Token::plus, src, pos)); } break; case '"': case '\'': { if (pos = Lexemes::string(src)) { lexemes.push_back(Lexeme(Tritium_Token::string, src, pos)); } else { throw "unterminated string"; } } break; case '`': { if (pos = bq_regexp(src)) { lexemes.push_back(Lexeme(Tritium_Token::regexp, src, pos)); } else { throw "malformed regular expression"; } } break; case '(': { lexemes.push_back(Lexeme(Tritium_Token::lparen, src, pos)); } break; case ')': { lexemes.push_back(Lexeme(Tritium_Token::rparen, src, pos)); } break; case '{': { lexemes.push_back(Lexeme(Tritium_Token::lbrace, src, pos)); } break; case '}': { lexemes.push_back(Lexeme(Tritium_Token::rbrace, src, pos)); } break; case '.': { lexemes.push_back(Lexeme(Tritium_Token::dot, src, pos)); } break; case ',': { lexemes.push_back(Lexeme(Tritium_Token::comma, src, pos)); } break; case '=': { lexemes.push_back(Lexeme(Tritium_Token::equal, src, pos)); } break; case '$': { if (pos = gvar(src)) { lexemes.push_back(Lexeme(Tritium_Token::gvar, src, pos)); } else { pos = ts_identifier(src); lexemes.push_back(Lexeme(Tritium_Token::id, src, pos)); } } break; case '%': { if (pos = lvar(src)) { lexemes.push_back(Lexeme(Tritium_Token::lvar, src, pos)); } else { throw "malformed local variable name"; } } break; default: { if (pos = position_kwd(src)) { lexemes.push_back(Lexeme(Tritium_Token::pos, src, pos)); } else if (pos = type_name(src)) { lexemes.push_back(Lexeme(Tritium_Token::type, src, pos)); } else if (pos = read_kwd(src)) { lexemes.push_back(Lexeme(Tritium_Token::read, src, pos)); } else if (pos = attr_name(src)) { if (*(pos-1) != ':') throw "attribute name must be followed by `:`"; lexemes.push_back(Lexeme(Tritium_Token::kwd, src, pos)); } else if (pos = ts_identifier(src)) { lexemes.push_back(Lexeme(Tritium_Token::id, src, pos)); } else if (pos = number(src)) { lexemes.push_back(Lexeme(Tritium_Token::string, src, pos)); } else { throw "unrecognized lexeme"; } } break; src = pos; } } return 0; }<|endoftext|>
<commit_before>/* standard_adserver_connector.cc Wolfgang Sourdeau, March 2013 Copyright (c) 2013 Datacratic. All rights reserved. */ #include "rtbkit/common/account_key.h" #include "rtbkit/common/currency.h" #include "rtbkit/common/json_holder.h" #include "standard_adserver_connector.h" using namespace std; using namespace boost::program_options; using namespace RTBKIT; /* STANDARDADSERVERARGUMENTS */ boost::program_options::options_description StandardAdServerArguments:: makeProgramOptions() { boost::program_options::options_description stdOptions = ServiceProxyArguments::makeProgramOptions(); boost::program_options::options_description options("Standard Ad Server Connector"); options.add_options() ("win-port,w", value(&winPort), "listening port for wins") ("events-port,e", value(&eventsPort), "listening port for events") ("external-win-port,x", value(&externalWinPort), "listening port for external wins"); stdOptions.add(options); return stdOptions; } void StandardAdServerArguments:: validate() { ExcCheck(winPort > 0, "winPort is not set"); ExcCheck(eventsPort > 0, "eventsPort is not set"); ExcCheck(externalWinPort > 0, "externalWinPort is not set"); } /* STANDARDADSERVERCONNECTOR */ StandardAdServerConnector:: StandardAdServerConnector(std::shared_ptr<ServiceProxies> & proxy, const string & serviceName) : HttpAdServerConnector(serviceName, proxy), publisher_(proxy->zmqContext) { } StandardAdServerConnector:: StandardAdServerConnector(std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) : HttpAdServerConnector(json.get("name", "standard-adserver").asString(), proxies), publisher_(getServices()->zmqContext) { int winPort = json.get("winPort", "18143").asInt(); int eventsPort = json.get("eventsPort", "18144").asInt(); int externalWinPort = json.get("externalWinPort", "18145").asInt(); init(winPort, eventsPort, externalWinPort); } void StandardAdServerConnector:: init(StandardAdServerArguments & ssConfig) { ssConfig.validate(); init(ssConfig.winPort, ssConfig.eventsPort, ssConfig.externalWinPort); } void StandardAdServerConnector:: init(int winsPort, int eventsPort, int externalPort) { shared_ptr<ServiceProxies> services = getServices(); auto onWinRq = [=] (const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { this->handleWinRq(header, json, jsonStr); }; registerEndpoint(winsPort, onWinRq); auto onDeliveryRq = [=] (const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { this->handleDeliveryRq(header, json, jsonStr); }; registerEndpoint(eventsPort, onDeliveryRq); auto onExternalWinRq = [=] (const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { this->handleExternalWinRq(header, json, jsonStr); }; registerEndpoint(externalPort, onExternalWinRq); HttpAdServerConnector::init(services->config); publisher_.init(services->config, serviceName_ + "/logger"); } void StandardAdServerConnector:: start() { bindTcp(); publisher_.bindTcp(getServices()->ports->getRange("adServer.logger")); publisher_.start(); HttpAdServerConnector::start(); } void StandardAdServerConnector:: shutdown() { publisher_.shutdown(); HttpAdServerConnector::shutdown(); } void StandardAdServerConnector:: handleWinRq(const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { Date timestamp = Date::fromSecondsSinceEpoch(json["timestamp"].asDouble()); Date bidTimestamp; if (json.isMember("bidTimestamp")) { bidTimestamp = Date::fromSecondsSinceEpoch(json["bidTimestamp"].asDouble()); } string auctionIdStr(json["auctionId"].asString()); string adSpotIdStr(json["adSpotId"].asString()); string accountKeyStr(json["accountId"].asString()); double winPriceDbl(json["winPrice"].asDouble()); double dataCostDbl(json["dataCost"].asDouble()); Id auctionId(auctionIdStr); Id adSpotId(adSpotIdStr); AccountKey accountKey(accountKeyStr); USD_CPM winPrice(winPriceDbl); USD_CPM dataCost(dataCostDbl); UserIds userIds; const Json::Value & meta = json["winMeta"]; publishWin(auctionId, adSpotId, winPrice, timestamp, meta, userIds, accountKey, bidTimestamp); publisher_.publish("WIN", timestamp.print(3), auctionIdStr, adSpotIdStr, accountKeyStr, winPrice.toString(), dataCost.toString(), meta); } void StandardAdServerConnector:: handleDeliveryRq(const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { Date timestamp = Date::fromSecondsSinceEpoch(json["timestamp"].asDouble()); Date bidTimestamp; if (json.isMember("bidTimestamp")) { bidTimestamp = Date::fromSecondsSinceEpoch(json["bidTimestamp"].asDouble()); } int matchType(0); /* 1: campaign, 2: user, 0: none */ string auctionIdStr, adSpotIdStr, userIdStr; Id auctionId, adSpotId, userId; UserIds userIds; if (json.isMember("auctionId")) { auctionIdStr = json["auctionId"].asString(); adSpotIdStr = json["adSpotId"].asString(); auctionId = Id(auctionIdStr); adSpotId = Id(adSpotIdStr); matchType = 1; } if (json.isMember("userId")) { userIdStr = json["userId"].asString(); userId = Id(userIdStr); if (!matchType) matchType = 2; } string event(json["event"].asString()); if (event == "click") { if (matchType != 1) { throw ML::Exception("click events must have auction/spot ids"); } publishCampaignEvent("CLICK", auctionId, adSpotId, timestamp, Json::Value(), userIds); publisher_.publish("CLICK", timestamp.print(3), auctionIdStr, adSpotIdStr, userIds.toString()); } else if (event == "conversion") { Json::Value meta; meta["payout"] = json["payout"]; USD_CPM payout(json["payout"].asDouble()); if (matchType == 1) { publishCampaignEvent("CONVERSION", auctionId, adSpotId, timestamp, meta, userIds); publisher_.publish("CONVERSION", timestamp.print(3), "campaign", auctionIdStr, adSpotIdStr, payout.toString()); } else if (matchType == 2) { publishUserEvent("CONVERSION", userId, timestamp, meta, userIds); publisher_.publish("CONVERSION", timestamp.print(3), "user", auctionId.toString(), payout.toString()); } else { publisher_.publish("CONVERSION", timestamp.print(3), "unmatched", auctionId.toString(), payout.toString()); } } else { throw ML::Exception("invalid event type: '" + event + "'"); } } void StandardAdServerConnector:: handleExternalWinRq(const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { Date now = Date::now(); string auctionIdStr(json["auctionId"].asString()); Id auctionId(auctionIdStr); double price(json["winPrice"].asDouble()); double dataCostDbl(0.0); if (json.isMember("dataCost")) { dataCostDbl = json["dataCost"].asDouble(); } USD_CPM dataCost(dataCostDbl); Json::Value bidRequest = json["bidRequest"]; publisher_.publish("EXTERNALWIN", now.print(3), auctionIdStr, std::to_string(price), dataCost.toString(), boost::trim_copy(bidRequest.toString())); } namespace { struct AtInit { AtInit() { AdServerConnector::registerFactory("standard", [](std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) { return new StandardAdServerConnector(proxies, json); }); } } atInit; } <commit_msg>fixed issue with standard ad server<commit_after>/* standard_adserver_connector.cc Wolfgang Sourdeau, March 2013 Copyright (c) 2013 Datacratic. All rights reserved. */ #include "rtbkit/common/account_key.h" #include "rtbkit/common/currency.h" #include "rtbkit/common/json_holder.h" #include "standard_adserver_connector.h" using namespace std; using namespace boost::program_options; using namespace RTBKIT; /* STANDARDADSERVERARGUMENTS */ boost::program_options::options_description StandardAdServerArguments:: makeProgramOptions() { boost::program_options::options_description stdOptions = ServiceProxyArguments::makeProgramOptions(); boost::program_options::options_description options("Standard Ad Server Connector"); options.add_options() ("win-port,w", value(&winPort), "listening port for wins") ("events-port,e", value(&eventsPort), "listening port for events") ("external-win-port,x", value(&externalWinPort), "listening port for external wins"); stdOptions.add(options); return stdOptions; } void StandardAdServerArguments:: validate() { ExcCheck(winPort > 0, "winPort is not set"); ExcCheck(eventsPort > 0, "eventsPort is not set"); ExcCheck(externalWinPort > 0, "externalWinPort is not set"); } /* STANDARDADSERVERCONNECTOR */ StandardAdServerConnector:: StandardAdServerConnector(std::shared_ptr<ServiceProxies> & proxy, const string & serviceName) : HttpAdServerConnector(serviceName, proxy), publisher_(proxy->zmqContext) { } StandardAdServerConnector:: StandardAdServerConnector(std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) : HttpAdServerConnector(json.get("name", "standard-adserver").asString(), proxies), publisher_(getServices()->zmqContext) { int winPort = json.get("winPort", 18143).asInt(); int eventsPort = json.get("eventsPort", 18144).asInt(); int externalWinPort = json.get("externalWinPort", 18145).asInt(); init(winPort, eventsPort, externalWinPort); } void StandardAdServerConnector:: init(StandardAdServerArguments & ssConfig) { ssConfig.validate(); init(ssConfig.winPort, ssConfig.eventsPort, ssConfig.externalWinPort); } void StandardAdServerConnector:: init(int winsPort, int eventsPort, int externalPort) { shared_ptr<ServiceProxies> services = getServices(); auto onWinRq = [=] (const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { this->handleWinRq(header, json, jsonStr); }; registerEndpoint(winsPort, onWinRq); auto onDeliveryRq = [=] (const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { this->handleDeliveryRq(header, json, jsonStr); }; registerEndpoint(eventsPort, onDeliveryRq); auto onExternalWinRq = [=] (const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { this->handleExternalWinRq(header, json, jsonStr); }; registerEndpoint(externalPort, onExternalWinRq); HttpAdServerConnector::init(services->config); publisher_.init(services->config, serviceName_ + "/logger"); } void StandardAdServerConnector:: start() { bindTcp(); publisher_.bindTcp(getServices()->ports->getRange("adServer.logger")); publisher_.start(); HttpAdServerConnector::start(); } void StandardAdServerConnector:: shutdown() { publisher_.shutdown(); HttpAdServerConnector::shutdown(); } void StandardAdServerConnector:: handleWinRq(const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { Date timestamp = Date::fromSecondsSinceEpoch(json["timestamp"].asDouble()); Date bidTimestamp; if (json.isMember("bidTimestamp")) { bidTimestamp = Date::fromSecondsSinceEpoch(json["bidTimestamp"].asDouble()); } string auctionIdStr(json["auctionId"].asString()); string adSpotIdStr(json["adSpotId"].asString()); string accountKeyStr(json["accountId"].asString()); double winPriceDbl(json["winPrice"].asDouble()); double dataCostDbl(json["dataCost"].asDouble()); Id auctionId(auctionIdStr); Id adSpotId(adSpotIdStr); AccountKey accountKey(accountKeyStr); USD_CPM winPrice(winPriceDbl); USD_CPM dataCost(dataCostDbl); UserIds userIds; const Json::Value & meta = json["winMeta"]; publishWin(auctionId, adSpotId, winPrice, timestamp, meta, userIds, accountKey, bidTimestamp); publisher_.publish("WIN", timestamp.print(3), auctionIdStr, adSpotIdStr, accountKeyStr, winPrice.toString(), dataCost.toString(), meta); } void StandardAdServerConnector:: handleDeliveryRq(const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { Date timestamp = Date::fromSecondsSinceEpoch(json["timestamp"].asDouble()); Date bidTimestamp; if (json.isMember("bidTimestamp")) { bidTimestamp = Date::fromSecondsSinceEpoch(json["bidTimestamp"].asDouble()); } int matchType(0); /* 1: campaign, 2: user, 0: none */ string auctionIdStr, adSpotIdStr, userIdStr; Id auctionId, adSpotId, userId; UserIds userIds; if (json.isMember("auctionId")) { auctionIdStr = json["auctionId"].asString(); adSpotIdStr = json["adSpotId"].asString(); auctionId = Id(auctionIdStr); adSpotId = Id(adSpotIdStr); matchType = 1; } if (json.isMember("userId")) { userIdStr = json["userId"].asString(); userId = Id(userIdStr); if (!matchType) matchType = 2; } string event(json["event"].asString()); if (event == "click") { if (matchType != 1) { throw ML::Exception("click events must have auction/spot ids"); } publishCampaignEvent("CLICK", auctionId, adSpotId, timestamp, Json::Value(), userIds); publisher_.publish("CLICK", timestamp.print(3), auctionIdStr, adSpotIdStr, userIds.toString()); } else if (event == "conversion") { Json::Value meta; meta["payout"] = json["payout"]; USD_CPM payout(json["payout"].asDouble()); if (matchType == 1) { publishCampaignEvent("CONVERSION", auctionId, adSpotId, timestamp, meta, userIds); publisher_.publish("CONVERSION", timestamp.print(3), "campaign", auctionIdStr, adSpotIdStr, payout.toString()); } else if (matchType == 2) { publishUserEvent("CONVERSION", userId, timestamp, meta, userIds); publisher_.publish("CONVERSION", timestamp.print(3), "user", auctionId.toString(), payout.toString()); } else { publisher_.publish("CONVERSION", timestamp.print(3), "unmatched", auctionId.toString(), payout.toString()); } } else { throw ML::Exception("invalid event type: '" + event + "'"); } } void StandardAdServerConnector:: handleExternalWinRq(const HttpHeader & header, const Json::Value & json, const std::string & jsonStr) { Date now = Date::now(); string auctionIdStr(json["auctionId"].asString()); Id auctionId(auctionIdStr); double price(json["winPrice"].asDouble()); double dataCostDbl(0.0); if (json.isMember("dataCost")) { dataCostDbl = json["dataCost"].asDouble(); } USD_CPM dataCost(dataCostDbl); Json::Value bidRequest = json["bidRequest"]; publisher_.publish("EXTERNALWIN", now.print(3), auctionIdStr, std::to_string(price), dataCost.toString(), boost::trim_copy(bidRequest.toString())); } namespace { struct AtInit { AtInit() { AdServerConnector::registerFactory("standard", [](std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) { return new StandardAdServerConnector(proxies, json); }); } } atInit; } <|endoftext|>
<commit_before>/* Copyright (c) 1999 Gary Haussmann This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include "sysdef.h" #include "cssys/sysdriv.h" #include "cs2d/common/graph2d.h" #include "csutil/util.h" #include "cs2d/openglcommon/gl2d_font.h" /// we need a definition of GLFontInfo, declared in the header file class csGraphics2DOpenGLFontServer::GLFontInfo { public: /** * Constructor. Pass in a CS font, which will be analyzed and * used to build a texture holding all the characters. */ GLFontInfo (FontDef &newfont); /** * destructor. * Destroys the texture that holds the font characters. */ ~GLFontInfo () { glDeleteTextures (1, &mTexture_Handle); } /** * Call this to draw a character. The character is drawn on the * screen using the current color, and a transform is applied * to the modelview matrix to shift to the right. This is such * that the next call to DrawCharacter will draw a character in the * next cell over; that way you can make repeated calls without having * to manually position each character */ void DrawCharacter (unsigned char characterindex); private: // handle referring to the texture used for this font GLuint mTexture_Handle; // size of characters in the texture, in texture coordinates float mTexture_CharacterWidth; float mTexture_CharacterHeight; // size of characters in screen pixels unsigned int mCharacterWidth; unsigned int mCharacterHeight; // describes layout of the characters in the texture unsigned int mTexture_Characters_Per_Row; }; csGraphics2DOpenGLFontServer::GLFontInfo::GLFontInfo (FontDef &newfont) { // allocate handle for a new texture to hold this font glGenTextures (1,&mTexture_Handle); // set up the texture info glBindTexture (GL_TEXTURE_2D, mTexture_Handle); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); // Construct a buffer of data for OpenGL. We must do some transformation // of the Crystal Space data: // -use unsigned bytes instead of bits (GL_BITMAP not supported? GJH) // -width and height must be a power of 2 // -characters are laid out in a grid format, going across and // then down // first figure out how many characters to cram into a row, and // thus how many rows. There are 256 pixels in a row, and // 256 characters in the font as well. const int basetexturewidth = 256; const int fontcharactercount = 128; mCharacterHeight = newfont.Height; mCharacterWidth = FindNearestPowerOf2 (newfont.Width); mTexture_Characters_Per_Row = basetexturewidth / mCharacterWidth; int fontcharacterrows = fontcharactercount / mTexture_Characters_Per_Row; int basetextureheight = FindNearestPowerOf2 (newfont.Height * fontcharacterrows); // now figure out the size of a single character in the texture, // in texture coordinate space mTexture_CharacterWidth = mCharacterWidth / (float)basetexturewidth; mTexture_CharacterHeight = mCharacterHeight / (float)basetextureheight; // build bitmap data in a format proper for OpenGL // each pixel transforms into 1 byte alpha unsigned int basepixelsize = 1; unsigned char *fontbitmapdata; CHK (fontbitmapdata = new unsigned char [basetexturewidth * basetextureheight * basepixelsize]); // transform each CS character onto a small rectangular section // of the fontbitmap we have allocated for this font for (int curcharacter = 0; curcharacter<128; curcharacter++) { // locations in fontbitmap at which the current character will // be stored unsigned int curcharx = mCharacterWidth * (curcharacter % mTexture_Characters_Per_Row); unsigned int curchary = mCharacterHeight * (curcharacter / mTexture_Characters_Per_Row); unsigned char *characterbitmapbase = fontbitmapdata + (curcharx + curchary * basetexturewidth * basepixelsize); // points to location of the font source data unsigned char *fontsourcebits = newfont.FontBitmap + curcharacter * newfont.BytesPerChar; // grab bits from the source, and stuff them into the font bitmap // one at a time for (unsigned int pixely = 0; pixely < mCharacterHeight; pixely++) { // grab a whole byte from the source; we will strip off the // bits one at a time unsigned char currentsourcebyte = *fontsourcebits++; unsigned char destbytesetting; for (unsigned int pixelx = 0; pixelx < mCharacterWidth; pixelx++) { // strip a bit off and dump it into the base bitmap destbytesetting = (currentsourcebyte & 128) ? 255 : 0; *characterbitmapbase++ = destbytesetting; currentsourcebyte = currentsourcebyte << 1; } // advance base bitmap pointer to the next row characterbitmapbase += (basetexturewidth - mCharacterWidth) *basepixelsize; } } // shove all the data at OpenGL... glPixelStorei (GL_UNPACK_ALIGNMENT, 1); glTexImage2D (GL_TEXTURE_2D, 0 /*mipmap level */, 1 /* bytes-per-pixel */, basetexturewidth, basetextureheight, 0 /*border*/, GL_ALPHA, GL_UNSIGNED_BYTE, fontbitmapdata); CHK (delete [] fontbitmapdata); } void csGraphics2DOpenGLFontServer::GLFontInfo::DrawCharacter ( unsigned char characterindex) { // bind the texture containing this font glBindTexture(GL_TEXTURE_2D,mTexture_Handle); // other required settings glEnable(GL_TEXTURE_2D); glShadeModel(GL_FLAT); glEnable(GL_ALPHA_TEST); glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // figure out location of the character in the texture float chartexturex = mTexture_CharacterWidth * (characterindex % mTexture_Characters_Per_Row); float chartexturey = mTexture_CharacterHeight * (characterindex / mTexture_Characters_Per_Row); // the texture coordinates must point to the correct character // the texture is a strip a wide as a single character and // as tall as 256 characters. We must select a single // character from it float tx1 = chartexturex, tx2 = chartexturex + mTexture_CharacterWidth; float ty1 = chartexturey, ty2 = chartexturey + mTexture_CharacterHeight; float x1 = 0.0, x2 = mCharacterWidth; float y1 = 0.0, y2 = mCharacterHeight; glAlphaFunc (GL_EQUAL,1.0); glBegin (GL_QUADS); glTexCoord2f (tx1,ty1); glVertex2f (x1,y2); glTexCoord2f (tx2,ty1); glVertex2f (x2,y2); glTexCoord2f (tx2,ty2); glVertex2f (x2,y1); glTexCoord2f (tx1,ty2); glVertex2f (x1,y1); glEnd (); glTranslatef (8.0,0.0,0.0); glDisable(GL_ALPHA_TEST); } /* The constructor initializes it member variables and constructs the * first font, if one was passed into the constructor */ csGraphics2DOpenGLFontServer::csGraphics2DOpenGLFontServer (int MaxFonts) : mFont_Count (0), mMax_Font_Count (MaxFonts), mFont_Information_Array (NULL) { CHK (mFont_Information_Array = new GLFontInfo * [MaxFonts]); } csGraphics2DOpenGLFontServer::~csGraphics2DOpenGLFontServer () { // kill all the font data we have accumulated if (mFont_Information_Array) { // cycle through all loaded fonts for (int index = 0; index < mFont_Count; index++) CHKB (delete mFont_Information_Array [index]); CHK (delete [] mFont_Information_Array); } } void csGraphics2DOpenGLFontServer::AddFont (FontDef &addme) { if (mFont_Count >= mMax_Font_Count) return; // we assume the FontDef is legal... mFont_Information_Array [mFont_Count++] = new GLFontInfo (addme); } /* Print some characters (finally!) This is basically a wrapper * around repeated calls to WriteCharacter */ void csGraphics2DOpenGLFontServer::WriteCharacters(char *writeme, int fontnumber) { // do some error checking if (mFont_Count < 1) return; if (fontnumber >= mFont_Count) fontnumber = 0; // write the string for (char *curcharacter = writeme; *curcharacter != 0; curcharacter++) WriteCharacter (*curcharacter, fontnumber); } /* Print a character. This is basically a wrapper * around calls to the GLFontInfo method WriteCharacter() */ void csGraphics2DOpenGLFontServer::WriteCharacter(char writeme, int fontnumber) { // do some error checking if (mFont_Count < 1) return; if (fontnumber >= mFont_Count) fontnumber = 0; mFont_Information_Array [fontnumber]->DrawCharacter (writeme); } <commit_msg>Fixed text rendering. The problem was that the third parameter--which tells OpenGL the components of data you are passing in--was '1' when it should have been 'GL_ALPHA'.<commit_after>/* Copyright (c) 1999 Gary Haussmann This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include "sysdef.h" #include "cssys/sysdriv.h" #include "cs2d/common/graph2d.h" #include "csutil/util.h" #include "cs2d/openglcommon/gl2d_font.h" /// we need a definition of GLFontInfo, declared in the header file class csGraphics2DOpenGLFontServer::GLFontInfo { public: /** * Constructor. Pass in a CS font, which will be analyzed and * used to build a texture holding all the characters. */ GLFontInfo (FontDef &newfont); /** * destructor. * Destroys the texture that holds the font characters. */ ~GLFontInfo () { glDeleteTextures (1, &mTexture_Handle); } /** * Call this to draw a character. The character is drawn on the * screen using the current color, and a transform is applied * to the modelview matrix to shift to the right. This is such * that the next call to DrawCharacter will draw a character in the * next cell over; that way you can make repeated calls without having * to manually position each character */ void DrawCharacter (unsigned char characterindex); private: // handle referring to the texture used for this font GLuint mTexture_Handle; // size of characters in the texture, in texture coordinates float mTexture_CharacterWidth; float mTexture_CharacterHeight; // size of characters in screen pixels unsigned int mCharacterWidth; unsigned int mCharacterHeight; // describes layout of the characters in the texture unsigned int mTexture_Characters_Per_Row; }; csGraphics2DOpenGLFontServer::GLFontInfo::GLFontInfo (FontDef &newfont) { // allocate handle for a new texture to hold this font glGenTextures (1,&mTexture_Handle); // set up the texture info glBindTexture (GL_TEXTURE_2D, mTexture_Handle); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); // Construct a buffer of data for OpenGL. We must do some transformation // of the Crystal Space data: // -use unsigned bytes instead of bits (GL_BITMAP not supported? GJH) // -width and height must be a power of 2 // -characters are laid out in a grid format, going across and // then down // first figure out how many characters to cram into a row, and // thus how many rows. There are 256 pixels in a row, and // 256 characters in the font as well. const int basetexturewidth = 256; const int fontcharactercount = 128; mCharacterHeight = newfont.Height; mCharacterWidth = FindNearestPowerOf2 (newfont.Width); mTexture_Characters_Per_Row = basetexturewidth / mCharacterWidth; int fontcharacterrows = fontcharactercount / mTexture_Characters_Per_Row; int basetextureheight = FindNearestPowerOf2 (newfont.Height * fontcharacterrows); // now figure out the size of a single character in the texture, // in texture coordinate space mTexture_CharacterWidth = mCharacterWidth / (float)basetexturewidth; mTexture_CharacterHeight = mCharacterHeight / (float)basetextureheight; // build bitmap data in a format proper for OpenGL // each pixel transforms into 1 byte alpha unsigned int basepixelsize = 1; unsigned char *fontbitmapdata; CHK (fontbitmapdata = new unsigned char [basetexturewidth * basetextureheight * basepixelsize]); // transform each CS character onto a small rectangular section // of the fontbitmap we have allocated for this font for (int curcharacter = 0; curcharacter<128; curcharacter++) { // locations in fontbitmap at which the current character will // be stored unsigned int curcharx = mCharacterWidth * (curcharacter % mTexture_Characters_Per_Row); unsigned int curchary = mCharacterHeight * (curcharacter / mTexture_Characters_Per_Row); unsigned char *characterbitmapbase = fontbitmapdata + (curcharx + curchary * basetexturewidth * basepixelsize); // points to location of the font source data unsigned char *fontsourcebits = newfont.FontBitmap + curcharacter * newfont.BytesPerChar; // grab bits from the source, and stuff them into the font bitmap // one at a time for (unsigned int pixely = 0; pixely < mCharacterHeight; pixely++) { // grab a whole byte from the source; we will strip off the // bits one at a time unsigned char currentsourcebyte = *fontsourcebits++; unsigned char destbytesetting; for (unsigned int pixelx = 0; pixelx < mCharacterWidth; pixelx++) { // strip a bit off and dump it into the base bitmap destbytesetting = (currentsourcebyte & 128) ? 255 : 0; *characterbitmapbase++ = destbytesetting; currentsourcebyte = currentsourcebyte << 1; } // advance base bitmap pointer to the next row characterbitmapbase += (basetexturewidth - mCharacterWidth) *basepixelsize; } } // shove all the data at OpenGL... glPixelStorei (GL_UNPACK_ALIGNMENT, 1); glTexImage2D (GL_TEXTURE_2D, 0 /*mipmap level */, GL_ALPHA /* bytes-per-pixel */, basetexturewidth, basetextureheight, 0 /*border*/, GL_ALPHA, GL_UNSIGNED_BYTE, fontbitmapdata); CHK (delete [] fontbitmapdata); } void csGraphics2DOpenGLFontServer::GLFontInfo::DrawCharacter ( unsigned char characterindex) { // bind the texture containing this font glBindTexture(GL_TEXTURE_2D,mTexture_Handle); // other required settings glEnable(GL_TEXTURE_2D); glShadeModel(GL_FLAT); glEnable(GL_ALPHA_TEST); glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // figure out location of the character in the texture float chartexturex = mTexture_CharacterWidth * (characterindex % mTexture_Characters_Per_Row); float chartexturey = mTexture_CharacterHeight * (characterindex / mTexture_Characters_Per_Row); // the texture coordinates must point to the correct character // the texture is a strip a wide as a single character and // as tall as 256 characters. We must select a single // character from it float tx1 = chartexturex, tx2 = chartexturex + mTexture_CharacterWidth; float ty1 = chartexturey, ty2 = chartexturey + mTexture_CharacterHeight; float x1 = 0.0, x2 = mCharacterWidth; float y1 = 0.0, y2 = mCharacterHeight; glAlphaFunc (GL_EQUAL,1.0); glBegin (GL_QUADS); glTexCoord2f (tx1,ty1); glVertex2f (x1,y2); glTexCoord2f (tx2,ty1); glVertex2f (x2,y2); glTexCoord2f (tx2,ty2); glVertex2f (x2,y1); glTexCoord2f (tx1,ty2); glVertex2f (x1,y1); glEnd (); glTranslatef (8.0,0.0,0.0); glDisable(GL_ALPHA_TEST); } /* The constructor initializes it member variables and constructs the * first font, if one was passed into the constructor */ csGraphics2DOpenGLFontServer::csGraphics2DOpenGLFontServer (int MaxFonts) : mFont_Count (0), mMax_Font_Count (MaxFonts), mFont_Information_Array (NULL) { CHK (mFont_Information_Array = new GLFontInfo * [MaxFonts]); } csGraphics2DOpenGLFontServer::~csGraphics2DOpenGLFontServer () { // kill all the font data we have accumulated if (mFont_Information_Array) { // cycle through all loaded fonts for (int index = 0; index < mFont_Count; index++) CHKB (delete mFont_Information_Array [index]); CHK (delete [] mFont_Information_Array); } } void csGraphics2DOpenGLFontServer::AddFont (FontDef &addme) { if (mFont_Count >= mMax_Font_Count) return; // we assume the FontDef is legal... mFont_Information_Array [mFont_Count++] = new GLFontInfo (addme); } /* Print some characters (finally!) This is basically a wrapper * around repeated calls to WriteCharacter */ void csGraphics2DOpenGLFontServer::WriteCharacters(char *writeme, int fontnumber) { // do some error checking if (mFont_Count < 1) return; if (fontnumber >= mFont_Count) fontnumber = 0; // write the string for (char *curcharacter = writeme; *curcharacter != 0; curcharacter++) WriteCharacter (*curcharacter, fontnumber); } /* Print a character. This is basically a wrapper * around calls to the GLFontInfo method WriteCharacter() */ void csGraphics2DOpenGLFontServer::WriteCharacter(char writeme, int fontnumber) { // do some error checking if (mFont_Count < 1) return; if (fontnumber >= mFont_Count) fontnumber = 0; mFont_Information_Array [fontnumber]->DrawCharacter (writeme); } <|endoftext|>
<commit_before>// RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s < %t.out // RUN: %clangxx_msan -fsanitize-memory-track-origins -O3 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s < %t.out // Test origin propagation through insertvalue IR instruction. // REQUIRES: stable-runtime #include <stdio.h> #include <stdint.h> struct mypair { int64_t x; int y; }; mypair my_make_pair(int64_t x, int y) { mypair p; p.x = x; p.y = y; return p; } int main() { int64_t * volatile p = new int64_t; mypair z = my_make_pair(*p, 0); if (z.x) printf("zzz\n"); // CHECK: MemorySanitizer: use-of-uninitialized-value // CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-3]] // CHECK: Uninitialized value was created by a heap allocation // CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-8]] delete p; return 0; } <commit_msg>[compiler-rt] [msan] Remove stable-runtime requirement for insertvalue_origin.cc<commit_after>// RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s < %t.out // RUN: %clangxx_msan -fsanitize-memory-track-origins -O3 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s < %t.out // Test origin propagation through insertvalue IR instruction. #include <stdio.h> #include <stdint.h> struct mypair { int64_t x; int y; }; mypair my_make_pair(int64_t x, int y) { mypair p; p.x = x; p.y = y; return p; } int main() { int64_t * volatile p = new int64_t; mypair z = my_make_pair(*p, 0); if (z.x) printf("zzz\n"); // CHECK: MemorySanitizer: use-of-uninitialized-value // CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-3]] // CHECK: Uninitialized value was created by a heap allocation // CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-8]] delete p; return 0; } <|endoftext|>