text
stringlengths
54
60.6k
<commit_before>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES #include "vendor/better-enums/enum_strict.hpp" #include "vendor/range/v3/view/drop.hpp" #include "vendor/range/v3/view/transform.hpp" #include "vendor/fmt/format.hpp" #include "vendor/range/v3/view/chunk.hpp" #include "vendor/range/v3/to_container.hpp" #include "vendor/range/v3/numeric/accumulate.hpp" #include "vendor/docopt/docopt.hpp" #include "vendor/range/v3/algorithm/find_if.hpp" #include <thewizardplusplus/wizard_parser/exceptions/unexpected_entity_exception.hpp> #include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp> #include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp> #include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/match_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/ast_node.hpp> #include <thewizardplusplus/wizard_parser/exceptions/positional_exception.hpp> #include <thewizardplusplus/wizard_parser/parser/parse.hpp> #include <thewizardplusplus/wizard_parser/utilities/utilities.hpp> #include <cstddef> #include <functional> #include <vector> #include <cstdint> #include <regex> #include <unordered_map> #include <string> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string_view> #include <iterator> #include <sstream> #include <limits> #include <iomanip> #include <exception> using namespace thewizardplusplus::wizard_parser; using namespace thewizardplusplus::wizard_parser::parser::operators; using namespace std::literals::string_literals; struct function final { const std::size_t arity; const std::function<double(const std::vector<double>&)> handler; }; BETTER_ENUM(entity_type, std::uint8_t, node = exceptions::entity_type::_size(), constant, function ) template<entity_type::_integral type> using unexpected_entity_exception = exceptions::base_unexpected_entity_exception<entity_type, type>; const auto usage = R"(Usage: ./example [options] [--] [<expression>] Options: -h, --help - show this message; -t TARGET, --target TARGET - preliminary target of processing (allowed: tokens, cst); -p PRECISION, --precision PRECISION - precision of a result; -s, --stdin - read an expression from stdin; -V, --verbose - mark an error.)"; const auto lexemes = lexer::lexeme_group{ {std::regex{R"(\+)"}, "plus"}, {std::regex{R"(-)"}, "minus"}, {std::regex{R"(\*)"}, "star"}, {std::regex{R"(/)"}, "slash"}, {std::regex{R"(%)"}, "percent"}, {std::regex{R"(\()"}, "opening_parenthesis"}, {std::regex{R"(\))"}, "closing_parenthesis"}, {std::regex{R"(,)"}, "comma"}, {std::regex{R"(\d+(\.\d+)?(e-?\d+)?)"}, "number"}, {std::regex{R"([A-Za-z_]\w*)"}, "identifier"}, {std::regex{R"(\s+)"}, "whitespace"} }; const auto lexemes_exceptions = lexer::exception_group{"whitespace"}; // precision is taken from Boost 1.70.0, Math Toolkit 2.9.0 const auto constants = std::unordered_map<std::string, double>{ {"pi", 3.141592653589793238462643383279502884}, {"e", 2.718281828459045235360287471352662497} }; const auto functions = std::unordered_map<std::string, function>{ {"+", {2, [] (const auto& args) { return args[0] + args[1]; }}}, {"-", {2, [] (const auto& args) { return args[0] - args[1]; }}}, {"*", {2, [] (const auto& args) { return args[0] * args[1]; }}}, {"/", {2, [] (const auto& args) { return args[0] / args[1]; }}}, {"%", {2, [] (const auto& args) { return std::fmod(args[0], args[1]); }}}, {"floor", {1, [] (const auto& args) { return std::floor(args[0]); }}}, {"ceil", {1, [] (const auto& args) { return std::ceil(args[0]); }}}, {"trunc", {1, [] (const auto& args) { return std::trunc(args[0]); }}}, {"round", {1, [] (const auto& args) { return std::round(args[0]); }}}, {"sin", {1, [] (const auto& args) { return std::sin(args[0]); }}}, {"cos", {1, [] (const auto& args) { return std::cos(args[0]); }}}, {"tn", {1, [] (const auto& args) { return std::tan(args[0]); }}}, {"arcsin", {1, [] (const auto& args) { return std::asin(args[0]); }}}, {"arccos", {1, [] (const auto& args) { return std::acos(args[0]); }}}, {"arctn", {1, [] (const auto& args) { return std::atan(args[0]); }}}, {"angle", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}}, {"pow", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}}, {"sqrt", {1, [] (const auto& args) { return std::sqrt(args[0]); }}}, {"exp", {1, [] (const auto& args) { return std::exp(args[0]); }}}, {"ln", {1, [] (const auto& args) { return std::log(args[0]); }}}, {"lg", {1, [] (const auto& args) { return std::log10(args[0]); }}}, {"abs", {1, [] (const auto& args) { return std::abs(args[0]); }}}, }; template<typename streamable> void exit(const int& code, const streamable& message) { (code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\n'; std::exit(code); } parser::rule_parser::pointer make_parser() { const auto expression_dummy = parser::dummy(); RULE(function_call) = "identifier"_t >> &"("_v >> -(expression_dummy >> *(&","_v >> expression_dummy)) >> &")"_v; RULE(atom) = "number"_t | function_call | "identifier"_t | (&"("_v >> expression_dummy >> &")"_v); RULE(unary) = *("-"_v) >> atom; RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary); RULE(sum) = product >> *(("+"_v | "-"_v) >> product); expression_dummy->set_parser(sum); return sum; } double evaluate_ast_node( const parser::ast_node& ast, const std::unordered_map<std::string, double>& constants, const std::unordered_map<std::string, function>& functions ) { const auto inspect_sequence = [] (const auto& ast) -> const auto& { return ast.children[0].children; }; const auto evaluate_with_context = [&] (const auto& ast) { return evaluate_ast_node(ast, constants, functions); }; if (ast.type == "number") { return std::stod(ast.value, nullptr); } else if (ast.type == "identifier") { try { return constants.at(ast.value); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::constant>{offset}; } } else if (ast.type == "atom") { const auto type = (+parser::ast_node_type::sequence)._to_string(); const auto first_child = ast.children[0].type == type ? inspect_sequence(ast)[0] : ast.children[0]; return evaluate_with_context(first_child); } else if (ast.type == "unary") { const auto result = evaluate_with_context(inspect_sequence(ast).back()); const auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1; return sign * result; } else if (ast.type == "function_call") { try { const auto name = inspect_sequence(ast)[0].value; const auto arguments = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::transform([&] (const auto& ast) { return evaluate_with_context(ast); }); const auto function = functions.at(name); if (arguments.size() != function.arity) { const auto unit = function.arity == 1 ? "argument" : "arguments"; const auto description = fmt::format("function requires {:d} {:s}", function.arity, unit); const auto offset = parser::get_offset(ast); throw exceptions::positional_exception{description, offset}; } return function.handler(arguments); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::function>{offset}; } } else if (ast.type == "product" || ast.type == "sum") { const auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]); const auto children_chunks = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::chunk(2) | ranges::view::transform([] (const auto& chunk) { return chunk | ranges::to_<parser::ast_node_group>(); }); return ranges::accumulate( children_chunks, first_operand, [&] (const auto& result, const auto& chunk) { const auto name = chunk[0].value; const auto second_operand = evaluate_with_context(chunk[1]); return functions.at(name).handler({result, second_operand}); } ); } else { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::node>{offset}; } } std::runtime_error enrich_exception( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { const auto mark_offset = std::string(exception.offset, ' '); const auto mark = std::string(mark_length, '^'); return std::runtime_error{fmt::format( "{:s}\n| \"{:s}\"\n| {:s}{:s}", exception.what(), code, mark_offset, mark )}; } int main(int argc, char* argv[]) try { const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true); const auto expression = options.at("<expression>") ? options.at("<expression>").asString() : ""; const auto code = options.at("--stdin").asBool() ? std::string{std::istreambuf_iterator<char>{std::cin}, {}} : expression; const auto enrich = options.at("--verbose").asBool() ? std::function{enrich_exception} : [] ( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { return exception; }; try { auto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code); if (options.at("--target") == "tokens"s) { exit(EXIT_SUCCESS, tokens); } const auto eoi = exceptions::entity_type::eoi; try { const auto ast = parser::parse_all(make_parser(), tokens); if (options.at("--target") == "cst"s) { exit(EXIT_SUCCESS, ast); } auto buffer = std::ostringstream{}; const auto precision = options.at("--precision") ? options.at("--precision").asLong() : std::numeric_limits<double>::max_digits10; const auto result = evaluate_ast_node(ast, constants, functions); buffer << std::setprecision(precision) << result; exit(EXIT_SUCCESS, buffer.str()); } catch (const exceptions::unexpected_entity_exception<eoi>& exception) { const auto offset = exception.offset == utilities::integral_infinity ? code.size() : exception.offset; throw exceptions::unexpected_entity_exception<eoi>{offset}; } catch (const exceptions::positional_exception& exception) { const auto token = ranges::find_if(tokens, [&] (const auto& token) { return token.offset == exception.offset; }); throw enrich(exception, code, token->value.size()); } } catch (const exceptions::positional_exception& exception) { throw enrich(exception, code, 1); } } catch (const std::exception& exception) { exit(EXIT_FAILURE, fmt::format("error: {:s}", exception.what())); } <commit_msg>Add the list parser: use it in the example<commit_after>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES #include "vendor/better-enums/enum_strict.hpp" #include "vendor/range/v3/view/drop.hpp" #include "vendor/range/v3/view/transform.hpp" #include "vendor/fmt/format.hpp" #include "vendor/range/v3/view/chunk.hpp" #include "vendor/range/v3/to_container.hpp" #include "vendor/range/v3/numeric/accumulate.hpp" #include "vendor/docopt/docopt.hpp" #include "vendor/range/v3/algorithm/find_if.hpp" #include <thewizardplusplus/wizard_parser/exceptions/unexpected_entity_exception.hpp> #include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp> #include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp> #include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/match_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/list_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/ast_node.hpp> #include <thewizardplusplus/wizard_parser/exceptions/positional_exception.hpp> #include <thewizardplusplus/wizard_parser/parser/parse.hpp> #include <thewizardplusplus/wizard_parser/utilities/utilities.hpp> #include <cstddef> #include <functional> #include <vector> #include <cstdint> #include <regex> #include <unordered_map> #include <string> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string_view> #include <iterator> #include <sstream> #include <limits> #include <iomanip> #include <exception> using namespace thewizardplusplus::wizard_parser; using namespace thewizardplusplus::wizard_parser::parser::operators; using namespace std::literals::string_literals; struct function final { const std::size_t arity; const std::function<double(const std::vector<double>&)> handler; }; BETTER_ENUM(entity_type, std::uint8_t, node = exceptions::entity_type::_size(), constant, function ) template<entity_type::_integral type> using unexpected_entity_exception = exceptions::base_unexpected_entity_exception<entity_type, type>; const auto usage = R"(Usage: ./example [options] [--] [<expression>] Options: -h, --help - show this message; -t TARGET, --target TARGET - preliminary target of processing (allowed: tokens, cst); -p PRECISION, --precision PRECISION - precision of a result; -s, --stdin - read an expression from stdin; -V, --verbose - mark an error.)"; const auto lexemes = lexer::lexeme_group{ {std::regex{R"(\+)"}, "plus"}, {std::regex{R"(-)"}, "minus"}, {std::regex{R"(\*)"}, "star"}, {std::regex{R"(/)"}, "slash"}, {std::regex{R"(%)"}, "percent"}, {std::regex{R"(\()"}, "opening_parenthesis"}, {std::regex{R"(\))"}, "closing_parenthesis"}, {std::regex{R"(,)"}, "comma"}, {std::regex{R"(\d+(\.\d+)?(e-?\d+)?)"}, "number"}, {std::regex{R"([A-Za-z_]\w*)"}, "identifier"}, {std::regex{R"(\s+)"}, "whitespace"} }; const auto lexemes_exceptions = lexer::exception_group{"whitespace"}; // precision is taken from Boost 1.70.0, Math Toolkit 2.9.0 const auto constants = std::unordered_map<std::string, double>{ {"pi", 3.141592653589793238462643383279502884}, {"e", 2.718281828459045235360287471352662497} }; const auto functions = std::unordered_map<std::string, function>{ {"+", {2, [] (const auto& args) { return args[0] + args[1]; }}}, {"-", {2, [] (const auto& args) { return args[0] - args[1]; }}}, {"*", {2, [] (const auto& args) { return args[0] * args[1]; }}}, {"/", {2, [] (const auto& args) { return args[0] / args[1]; }}}, {"%", {2, [] (const auto& args) { return std::fmod(args[0], args[1]); }}}, {"floor", {1, [] (const auto& args) { return std::floor(args[0]); }}}, {"ceil", {1, [] (const auto& args) { return std::ceil(args[0]); }}}, {"trunc", {1, [] (const auto& args) { return std::trunc(args[0]); }}}, {"round", {1, [] (const auto& args) { return std::round(args[0]); }}}, {"sin", {1, [] (const auto& args) { return std::sin(args[0]); }}}, {"cos", {1, [] (const auto& args) { return std::cos(args[0]); }}}, {"tn", {1, [] (const auto& args) { return std::tan(args[0]); }}}, {"arcsin", {1, [] (const auto& args) { return std::asin(args[0]); }}}, {"arccos", {1, [] (const auto& args) { return std::acos(args[0]); }}}, {"arctn", {1, [] (const auto& args) { return std::atan(args[0]); }}}, {"angle", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}}, {"pow", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}}, {"sqrt", {1, [] (const auto& args) { return std::sqrt(args[0]); }}}, {"exp", {1, [] (const auto& args) { return std::exp(args[0]); }}}, {"ln", {1, [] (const auto& args) { return std::log(args[0]); }}}, {"lg", {1, [] (const auto& args) { return std::log10(args[0]); }}}, {"abs", {1, [] (const auto& args) { return std::abs(args[0]); }}}, }; template<typename streamable> void exit(const int& code, const streamable& message) { (code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\n'; std::exit(code); } parser::rule_parser::pointer make_parser() { const auto expression_dummy = parser::dummy(); RULE(function_call) = "identifier"_t >> &"("_v >> -(expression_dummy % &","_v) >> &")"_v; RULE(atom) = "number"_t | function_call | "identifier"_t | (&"("_v >> expression_dummy >> &")"_v); RULE(unary) = *("-"_v) >> atom; RULE(product) = unary % ("*"_v | "/"_v | "%"_v); RULE(sum) = product % ("+"_v | "-"_v); expression_dummy->set_parser(sum); return sum; } double evaluate_ast_node( const parser::ast_node& ast, const std::unordered_map<std::string, double>& constants, const std::unordered_map<std::string, function>& functions ) { const auto inspect_sequence = [] (const auto& ast) -> const auto& { return ast.children[0].children; }; const auto evaluate_with_context = [&] (const auto& ast) { return evaluate_ast_node(ast, constants, functions); }; if (ast.type == "number") { return std::stod(ast.value, nullptr); } else if (ast.type == "identifier") { try { return constants.at(ast.value); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::constant>{offset}; } } else if (ast.type == "atom") { const auto type = (+parser::ast_node_type::sequence)._to_string(); const auto first_child = ast.children[0].type == type ? inspect_sequence(ast)[0] : ast.children[0]; return evaluate_with_context(first_child); } else if (ast.type == "unary") { const auto result = evaluate_with_context(inspect_sequence(ast).back()); const auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1; return sign * result; } else if (ast.type == "function_call") { try { const auto name = inspect_sequence(ast)[0].value; const auto arguments = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::transform([&] (const auto& ast) { return evaluate_with_context(ast); }); const auto function = functions.at(name); if (arguments.size() != function.arity) { const auto unit = function.arity == 1 ? "argument" : "arguments"; const auto description = fmt::format("function requires {:d} {:s}", function.arity, unit); const auto offset = parser::get_offset(ast); throw exceptions::positional_exception{description, offset}; } return function.handler(arguments); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::function>{offset}; } } else if (ast.type == "product" || ast.type == "sum") { const auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]); const auto children_chunks = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::chunk(2) | ranges::view::transform([] (const auto& chunk) { return chunk | ranges::to_<parser::ast_node_group>(); }); return ranges::accumulate( children_chunks, first_operand, [&] (const auto& result, const auto& chunk) { const auto name = chunk[0].value; const auto second_operand = evaluate_with_context(chunk[1]); return functions.at(name).handler({result, second_operand}); } ); } else { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::node>{offset}; } } std::runtime_error enrich_exception( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { const auto mark_offset = std::string(exception.offset, ' '); const auto mark = std::string(mark_length, '^'); return std::runtime_error{fmt::format( "{:s}\n| \"{:s}\"\n| {:s}{:s}", exception.what(), code, mark_offset, mark )}; } int main(int argc, char* argv[]) try { const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true); const auto expression = options.at("<expression>") ? options.at("<expression>").asString() : ""; const auto code = options.at("--stdin").asBool() ? std::string{std::istreambuf_iterator<char>{std::cin}, {}} : expression; const auto enrich = options.at("--verbose").asBool() ? std::function{enrich_exception} : [] ( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { return exception; }; try { auto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code); if (options.at("--target") == "tokens"s) { exit(EXIT_SUCCESS, tokens); } const auto eoi = exceptions::entity_type::eoi; try { const auto ast = parser::parse_all(make_parser(), tokens); if (options.at("--target") == "cst"s) { exit(EXIT_SUCCESS, ast); } auto buffer = std::ostringstream{}; const auto precision = options.at("--precision") ? options.at("--precision").asLong() : std::numeric_limits<double>::max_digits10; const auto result = evaluate_ast_node(ast, constants, functions); buffer << std::setprecision(precision) << result; exit(EXIT_SUCCESS, buffer.str()); } catch (const exceptions::unexpected_entity_exception<eoi>& exception) { const auto offset = exception.offset == utilities::integral_infinity ? code.size() : exception.offset; throw exceptions::unexpected_entity_exception<eoi>{offset}; } catch (const exceptions::positional_exception& exception) { const auto token = ranges::find_if(tokens, [&] (const auto& token) { return token.offset == exception.offset; }); throw enrich(exception, code, token->value.size()); } } catch (const exceptions::positional_exception& exception) { throw enrich(exception, code, 1); } } catch (const std::exception& exception) { exit(EXIT_FAILURE, fmt::format("error: {:s}", exception.what())); } <|endoftext|>
<commit_before>// Petter Strandmark 2012. #include <algorithm> #include <iostream> #include <limits> #include <stdexcept> #include <vector> #include <Eigen/Dense> #include <spii/spii.h> #include <spii/solver.h> namespace spii { // Holds a point in the Nelder-Mead simplex. // Equipped with a comparison operator for sorting. struct SimplexPoint { Eigen::VectorXd x; double value; bool operator<(const SimplexPoint& rhs) const { return this->value < rhs.value; } }; // If required for debugging. std::ostream& operator<<(std::ostream& out, const SimplexPoint& point) { out << point.x.transpose() << " : " << point.value; return out; } } // namespace spii namespace std { template<> void swap<spii::SimplexPoint>(spii::SimplexPoint& lhs, spii::SimplexPoint& rhs) { lhs.x.swap(rhs.x); swap(lhs.value, rhs.value); } } namespace spii { void Solver::solve_nelder_mead(const Function& function, SolverResults* results) const { double global_start_time = wall_time(); // Dimension of problem. size_t n = function.get_number_of_scalars(); // The Nelder-Mead simplex. std::vector<SimplexPoint> simplex(n + 1); // Copy the user state to the current point. Eigen::VectorXd x; function.copy_user_to_global(&x); // TODO: Find a better initialization. for (size_t i = 0; i < n + 1; ++i) { simplex[i].x = x; if (i < n) { if (std::abs(x[i]) < 0.025) { simplex[i].x[i] += 0.05; } else { simplex[i].x[i] += 0.05 * x[i]; } } simplex[i].value = function.evaluate(simplex[i].x); } std::sort(simplex.begin(), simplex.end()); SimplexPoint mean_point; SimplexPoint reflection_point; SimplexPoint expansion_point; mean_point.x.resize(n); reflection_point.x.resize(n); expansion_point.x.resize(n); double fmin = std::numeric_limits<double>::quiet_NaN(); double fmax = std::numeric_limits<double>::quiet_NaN(); double fval = std::numeric_limits<double>::quiet_NaN(); double fprev = std::numeric_limits<double>::quiet_NaN(); double area0 = std::numeric_limits<double>::quiet_NaN(); Eigen::MatrixXd area_mat(n, n); // // START MAIN ITERATION // results->startup_time = wall_time() - global_start_time; results->exit_condition = SolverResults::ERROR; int iter = 0; while (true) { // // In each iteration, the worst point in the simplex // is replaced with a new one. // double start_time = wall_time(); mean_point.x.setZero(); fval = 0; // Compute the mean of the best n points. for (size_t i = 0; i < n; ++i) { mean_point.x += simplex[i].x; fval += simplex[i].value; } fval /= double(n); mean_point.x /= double(n); fmin = simplex[0].value; fmax = simplex[n].value; // Compute the area of the simplex. for (size_t i = 0; i < n; ++i) { area_mat.col(i) = simplex[i].x - simplex[n].x; } double area = std::abs(area_mat.determinant()); if (iter == 0) { area0 = area; } const char* iteration_type = "n/a"; // Compute the reflexion point and evaluate it. reflection_point.x = 2.0 * mean_point.x - simplex[n].x; reflection_point.value = function.evaluate(reflection_point.x); if (simplex[0].value <= reflection_point.value && reflection_point.value < simplex[n - 1].value) { // Reflected point is neither better nor worst in the // new simplex. std::swap(reflection_point, simplex[n]); iteration_type = "Reflect 1"; } else if (reflection_point.value < simplex[0].value) { // Reflected point is better than the current best; try // to go farther along this direction. // Compute expansion point. expansion_point.x = 3.0 * mean_point.x - 2.0 * simplex[n].x; expansion_point.value = function.evaluate(expansion_point.x); if (expansion_point.value < reflection_point.value) { std::swap(expansion_point, simplex[n]); iteration_type = "Expansion"; } else { std::swap(reflection_point, simplex[n]); iteration_type = "Reflect 2"; } } else { // Reflected point is still worse than x[n]; contract. bool success = false; if (simplex[n - 1].value <= reflection_point.value && reflection_point.value < simplex[n].value) { // Try to perform "outside" contraction. expansion_point.x = 1.5 * mean_point.x - 0.5 * simplex[n].x; expansion_point.value = function.evaluate(expansion_point.x); if (expansion_point.value <= reflection_point.value) { std::swap(expansion_point, simplex[n]); success = true; iteration_type = "Outside contraction"; } } else { // Try to perform "inside" contraction. expansion_point.x = 0.5 * mean_point.x + 0.5 * simplex[n].x; expansion_point.value = function.evaluate(expansion_point.x); if (expansion_point.value < simplex[n].value) { std::swap(expansion_point, simplex[n]); success = true; iteration_type = "Inside contraction"; } } if (! success) { // Neither outside nor inside contraction was acceptable; // shrink the simplex toward the best point. for (size_t i = 1; i < n + 1; ++i) { simplex[i].x = 0.5 * (simplex[0].x + simplex[i].x); simplex[i].value = function.evaluate(simplex[i].x); iteration_type = "Shrink"; } } } std::sort(simplex.begin(), simplex.end()); results->function_evaluation_time += wall_time() - start_time; // // Test stopping criteriea // start_time = wall_time(); if (area / area0 < this->gradient_tolerance) { results->exit_condition = SolverResults::GRADIENT_TOLERANCE; break; } if (iter >= this->maximum_iterations) { results->exit_condition = SolverResults::NO_CONVERGENCE; break; } results->stopping_criteria_time += wall_time() - start_time; // // Log the results of this iteration. // start_time = wall_time(); int log_interval = 1; if (iter > 30) { log_interval = 10; } if (iter > 200) { log_interval = 100; } if (iter > 2000) { log_interval = 1000; } if (this->log_function && iter % log_interval == 0) { char str[1024]; if (iter == 0) { this->log_function("Itr min(f) avg(f) max(f) area type"); } std::sprintf(str, "%4d %+.3e %+.3e %+.3e %.3e %s", iter, fmin, fval, fmax, area, iteration_type); this->log_function(str); } results->log_time += wall_time() - start_time; fprev = fmax; iter++; } // Return the best point as solution. function.copy_global_to_user(simplex[0].x); results->total_time = wall_time() - global_start_time; if (this->log_function) { char str[1024]; std::sprintf(str, " end %+.3e", fval); this->log_function(str); } } } // namespace spii <commit_msg>Nelder-Mead update. initialization method from nmsmax.m<commit_after>// Petter Strandmark 2012. #include <algorithm> #include <iostream> #include <limits> #include <stdexcept> #include <vector> #include <Eigen/Dense> #include <spii/spii.h> #include <spii/solver.h> namespace spii { // Holds a point in the Nelder-Mead simplex. // Equipped with a comparison operator for sorting. struct SimplexPoint { Eigen::VectorXd x; double value; bool operator<(const SimplexPoint& rhs) const { return this->value < rhs.value; } }; // If required for debugging. std::ostream& operator<<(std::ostream& out, const SimplexPoint& point) { out << point.x.transpose() << " : " << point.value; return out; } } // namespace spii namespace std { template<> void swap<spii::SimplexPoint>(spii::SimplexPoint& lhs, spii::SimplexPoint& rhs) { lhs.x.swap(rhs.x); swap(lhs.value, rhs.value); } } namespace spii { void initialize_simplex(const Function& function, const Eigen::VectorXd& x0, std::vector<SimplexPoint>* simplex) { size_t n = function.get_number_of_scalars(); Eigen::VectorXd absx0 = x0; for (size_t i = 0; i < n; ++i) { absx0[i] = std::abs(x0[i]); } double scale = std::max(absx0.maxCoeff(), 1.0); const double nd = n; double alpha1 = scale / (nd * std::sqrt(2.0)) * (std::sqrt(nd+1)- 1 + nd); double alpha2 = scale / (nd * std::sqrt(2.0)) * (std::sqrt(nd+1) - 1); Eigen::VectorXd alpha2_vec(x0.size()); alpha2_vec.setConstant(alpha2); simplex->at(0).x = x0; for (size_t i = 1; i < n + 1; ++i) { simplex->at(i).x = x0 + alpha2_vec; simplex->at(i).x[i-1] = x0[i-1] + alpha1; } for (size_t i = 0; i < n + 1; ++i) { simplex->at(i).value = function.evaluate(simplex->at(i).x); } std::sort(simplex->begin(), simplex->end()); } void Solver::solve_nelder_mead(const Function& function, SolverResults* results) const { double global_start_time = wall_time(); // Dimension of problem. size_t n = function.get_number_of_scalars(); // The Nelder-Mead simplex. std::vector<SimplexPoint> simplex(n + 1); // Copy the user state to the current point. Eigen::VectorXd x; function.copy_user_to_global(&x); initialize_simplex(function, x, &simplex); SimplexPoint mean_point; SimplexPoint reflection_point; SimplexPoint expansion_point; mean_point.x.resize(n); reflection_point.x.resize(n); expansion_point.x.resize(n); double fmin = std::numeric_limits<double>::quiet_NaN(); double fmax = std::numeric_limits<double>::quiet_NaN(); double fval = std::numeric_limits<double>::quiet_NaN(); double fprev = std::numeric_limits<double>::quiet_NaN(); double area = std::numeric_limits<double>::quiet_NaN(); double area0 = std::numeric_limits<double>::quiet_NaN(); double area1 = std::numeric_limits<double>::quiet_NaN(); Eigen::MatrixXd area_mat(n, n); // // START MAIN ITERATION // results->startup_time = wall_time() - global_start_time; results->exit_condition = SolverResults::ERROR; int iter = 0; int n_shrink_in_a_row = 0; while (true) { // // In each iteration, the worst point in the simplex // is replaced with a new one. // double start_time = wall_time(); mean_point.x.setZero(); fval = 0; // Compute the mean of the best n points. for (size_t i = 0; i < n; ++i) { mean_point.x += simplex[i].x; fval += simplex[i].value; } fval /= double(n); mean_point.x /= double(n); fmin = simplex[0].value; fmax = simplex[n].value; const char* iteration_type = "n/a"; // Compute the reflexion point and evaluate it. reflection_point.x = 2.0 * mean_point.x - simplex[n].x; reflection_point.value = function.evaluate(reflection_point.x); bool is_shrink = false; if (simplex[0].value <= reflection_point.value && reflection_point.value < simplex[n - 1].value) { // Reflected point is neither better nor worst in the // new simplex. std::swap(reflection_point, simplex[n]); iteration_type = "Reflect 1"; } else if (reflection_point.value < simplex[0].value) { // Reflected point is better than the current best; try // to go farther along this direction. // Compute expansion point. expansion_point.x = 3.0 * mean_point.x - 2.0 * simplex[n].x; expansion_point.value = function.evaluate(expansion_point.x); if (expansion_point.value < reflection_point.value) { std::swap(expansion_point, simplex[n]); iteration_type = "Expansion"; } else { std::swap(reflection_point, simplex[n]); iteration_type = "Reflect 2"; } } else { // Reflected point is still worse than x[n]; contract. bool success = false; if (simplex[n - 1].value <= reflection_point.value && reflection_point.value < simplex[n].value) { // Try to perform "outside" contraction. expansion_point.x = 1.5 * mean_point.x - 0.5 * simplex[n].x; expansion_point.value = function.evaluate(expansion_point.x); if (expansion_point.value <= reflection_point.value) { std::swap(expansion_point, simplex[n]); success = true; iteration_type = "Outside contraction"; } } else { // Try to perform "inside" contraction. expansion_point.x = 0.5 * mean_point.x + 0.5 * simplex[n].x; expansion_point.value = function.evaluate(expansion_point.x); if (expansion_point.value < simplex[n].value) { std::swap(expansion_point, simplex[n]); success = true; iteration_type = "Inside contraction"; } } if (! success) { // Neither outside nor inside contraction was acceptable; // shrink the simplex toward the best point. for (size_t i = 1; i < n + 1; ++i) { simplex[i].x = 0.5 * (simplex[0].x + simplex[i].x); simplex[i].value = function.evaluate(simplex[i].x); iteration_type = "Shrink"; is_shrink = true; } } } std::sort(simplex.begin(), simplex.end()); results->function_evaluation_time += wall_time() - start_time; // // Test stopping criteriea // start_time = wall_time(); // Compute the area of the simplex. for (size_t i = 0; i < n; ++i) { area_mat.col(i) = simplex[i].x - simplex[n].x; } area = std::abs(area_mat.determinant()); if (iter == 0) { area0 = area; area1 = area; } if (area / area0 < this->gradient_tolerance) { results->exit_condition = SolverResults::GRADIENT_TOLERANCE; break; } if (is_shrink) { n_shrink_in_a_row++; } else { n_shrink_in_a_row = 0; } if (n_shrink_in_a_row > 50) { results->exit_condition = SolverResults::GRADIENT_TOLERANCE; break; } if (iter >= this->maximum_iterations) { results->exit_condition = SolverResults::NO_CONVERGENCE; break; } results->stopping_criteria_time += wall_time() - start_time; // // Restarting // //if (area / area1 < 1e-10) { // x = simplex[0].x; // initialize_simplex(function, x, &simplex); // area1 = area; // if (this->log_function) { // this->log_function("Restarted."); // } //} // // Log the results of this iteration. // start_time = wall_time(); int log_interval = 1; if (iter > 30) { log_interval = 10; } if (iter > 200) { log_interval = 100; } if (iter > 2000) { log_interval = 1000; } if (this->log_function && iter % log_interval == 0) { char str[1024]; if (iter == 0) { this->log_function("Itr min(f) avg(f) max(f) area type"); } std::sprintf(str, "%4d %+.3e %+.3e %+.3e %.3e %s", iter, fmin, fval, fmax, area, iteration_type); this->log_function(str); } results->log_time += wall_time() - start_time; fprev = fmax; iter++; } // Return the best point as solution. function.copy_global_to_user(simplex[0].x); results->total_time = wall_time() - global_start_time; if (this->log_function) { char str[1024]; std::sprintf(str, " end %+.3e %.3e", fval, area); this->log_function(str); } } } // namespace spii <|endoftext|>
<commit_before>#include "./labelling_coordinator.h" #include <Eigen/Core> #include <map> #include <vector> #include "./labelling/labels_container.h" #include "./labelling/clustering.h" #include "./labelling/labels.h" #include "./placement/constraint_updater.h" #include "./placement/persistent_constraint_updater.h" #include "./placement/cuda_texture_mapper.h" #include "./graphics/buffer_drawer.h" #include "./nodes.h" #include "./label_node.h" #include "./texture_mapper_manager.h" LabellingCoordinator::LabellingCoordinator( int layerCount, std::shared_ptr<Forces::Labeller> forcesLabeller, std::shared_ptr<Labels> labels, std::shared_ptr<Nodes> nodes) : layerCount(layerCount), forcesLabeller(forcesLabeller), labels(labels), nodes(nodes), clustering(labels, layerCount - 1) { } void LabellingCoordinator::initialize( int bufferSize, std::shared_ptr<Graphics::BufferDrawer> drawer, std::shared_ptr<TextureMapperManager> textureMapperManager, int width, int height) { auto constraintUpdater = std::make_shared<ConstraintUpdater>(drawer, bufferSize, bufferSize); persistentConstraintUpdater = std::make_shared<PersistentConstraintUpdater>(constraintUpdater); for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex) { auto labelsContainer = std::make_shared<LabelsContainer>(); labelsInLayer.push_back(labelsContainer); auto labeller = std::make_shared<Placement::Labeller>(labelsContainer); labeller->resize(width, height); labeller->initialize( textureMapperManager->getOccupancyTextureMapper(layerIndex), textureMapperManager->getDistanceTransformTextureMapper(layerIndex), textureMapperManager->getApolloniusTextureMapper(layerIndex), textureMapperManager->getConstraintTextureMapper(), persistentConstraintUpdater); placementLabellers.push_back(labeller); } } void LabellingCoordinator::cleanup() { for (auto placementLabeller : placementLabellers) placementLabeller->cleanup(); } void LabellingCoordinator::update(double frameTime, Eigen::Matrix4f projection, Eigen::Matrix4f view, int activeLayerNumber) { labellerFrameData = LabellerFrameData(frameTime, projection, view); auto positions = getPlacementPositions(activeLayerNumber); if (forcesEnabled) positions = getForcesPositions(positions); distributeLabelsToLayers(); updateLabelPositionsInLabelNodes(positions); } void LabellingCoordinator::updatePlacement() { persistentConstraintUpdater->clear(); for (auto placementLabeller : placementLabellers) placementLabeller->update(labellerFrameData); } std::vector<float> LabellingCoordinator::updateClusters() { clustering.update(labellerFrameData.viewProjection); auto clusters = clustering.getFarthestClusterMembersWithLabelIds(); std::vector<float> zValues; std::cout << "zValuesEye: "; for (auto pair : clusters) { zValues.push_back(pair.first); std::cout << pair.first << ":"; for (auto z : pair.second) std::cout << z << ", "; std::cout << std::endl; } std::cout << std::endl; return zValues; } void LabellingCoordinator::resize(int width, int height) { for (auto placementLabeller : placementLabellers) placementLabeller->resize(width, height); forcesLabeller->resize(width, height); } std::map<int, Eigen::Vector3f> LabellingCoordinator::getPlacementPositions(int activeLayerNumber) { std::map<int, Eigen::Vector3f> placementPositions; int layerIndex = 0; for (auto placementLabeller : placementLabellers) { if (activeLayerNumber == 0 || activeLayerNumber - 1 == layerIndex) { auto newPositionsForLayer = placementLabeller->getLastPlacementResult(); placementPositions.insert(newPositionsForLayer.begin(), newPositionsForLayer.end()); } layerIndex++; } return placementPositions; } std::map<int, Eigen::Vector3f> LabellingCoordinator::getForcesPositions( std::map<int, Eigen::Vector3f> placementPositions) { if (firstFramesWithoutPlacement && placementPositions.size()) { firstFramesWithoutPlacement = false; forcesLabeller->setPositions(labellerFrameData, placementPositions); } return forcesLabeller->update(labellerFrameData, placementPositions); } void LabellingCoordinator::distributeLabelsToLayers() { auto centerWithLabelIds = clustering.getCentersWithLabelIds(); int layerIndex = 0; for (auto &pair : centerWithLabelIds) { auto &container = labelsInLayer[layerIndex]; container->clear(); for (int labelId : pair.second) { container->add(labels->getById(labelId)); labelIdToLayerIndex[labelId] = layerIndex; } layerIndex++; } } void LabellingCoordinator::updateLabelPositionsInLabelNodes( std::map<int, Eigen::Vector3f> newPositions) { for (auto &labelNode : nodes->getLabelNodes()) { if (newPositions.count(labelNode->label.id)) { labelNode->setIsVisible(true); labelNode->labelPosition = newPositions[labelNode->label.id]; labelNode->layerIndex = labelIdToLayerIndex[labelNode->label.id]; } else { labelNode->setIsVisible(false); } } } <commit_msg>Minor: remove debug output.<commit_after>#include "./labelling_coordinator.h" #include <Eigen/Core> #include <map> #include <vector> #include "./labelling/labels_container.h" #include "./labelling/clustering.h" #include "./labelling/labels.h" #include "./placement/constraint_updater.h" #include "./placement/persistent_constraint_updater.h" #include "./placement/cuda_texture_mapper.h" #include "./graphics/buffer_drawer.h" #include "./nodes.h" #include "./label_node.h" #include "./texture_mapper_manager.h" LabellingCoordinator::LabellingCoordinator( int layerCount, std::shared_ptr<Forces::Labeller> forcesLabeller, std::shared_ptr<Labels> labels, std::shared_ptr<Nodes> nodes) : layerCount(layerCount), forcesLabeller(forcesLabeller), labels(labels), nodes(nodes), clustering(labels, layerCount - 1) { } void LabellingCoordinator::initialize( int bufferSize, std::shared_ptr<Graphics::BufferDrawer> drawer, std::shared_ptr<TextureMapperManager> textureMapperManager, int width, int height) { auto constraintUpdater = std::make_shared<ConstraintUpdater>(drawer, bufferSize, bufferSize); persistentConstraintUpdater = std::make_shared<PersistentConstraintUpdater>(constraintUpdater); for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex) { auto labelsContainer = std::make_shared<LabelsContainer>(); labelsInLayer.push_back(labelsContainer); auto labeller = std::make_shared<Placement::Labeller>(labelsContainer); labeller->resize(width, height); labeller->initialize( textureMapperManager->getOccupancyTextureMapper(layerIndex), textureMapperManager->getDistanceTransformTextureMapper(layerIndex), textureMapperManager->getApolloniusTextureMapper(layerIndex), textureMapperManager->getConstraintTextureMapper(), persistentConstraintUpdater); placementLabellers.push_back(labeller); } } void LabellingCoordinator::cleanup() { for (auto placementLabeller : placementLabellers) placementLabeller->cleanup(); } void LabellingCoordinator::update(double frameTime, Eigen::Matrix4f projection, Eigen::Matrix4f view, int activeLayerNumber) { labellerFrameData = LabellerFrameData(frameTime, projection, view); auto positions = getPlacementPositions(activeLayerNumber); if (forcesEnabled) positions = getForcesPositions(positions); distributeLabelsToLayers(); updateLabelPositionsInLabelNodes(positions); } void LabellingCoordinator::updatePlacement() { persistentConstraintUpdater->clear(); for (auto placementLabeller : placementLabellers) placementLabeller->update(labellerFrameData); } std::vector<float> LabellingCoordinator::updateClusters() { clustering.update(labellerFrameData.viewProjection); auto clusters = clustering.getFarthestClusterMembersWithLabelIds(); std::vector<float> zValues; for (auto pair : clusters) { zValues.push_back(pair.first); } return zValues; } void LabellingCoordinator::resize(int width, int height) { for (auto placementLabeller : placementLabellers) placementLabeller->resize(width, height); forcesLabeller->resize(width, height); } std::map<int, Eigen::Vector3f> LabellingCoordinator::getPlacementPositions(int activeLayerNumber) { std::map<int, Eigen::Vector3f> placementPositions; int layerIndex = 0; for (auto placementLabeller : placementLabellers) { if (activeLayerNumber == 0 || activeLayerNumber - 1 == layerIndex) { auto newPositionsForLayer = placementLabeller->getLastPlacementResult(); placementPositions.insert(newPositionsForLayer.begin(), newPositionsForLayer.end()); } layerIndex++; } return placementPositions; } std::map<int, Eigen::Vector3f> LabellingCoordinator::getForcesPositions( std::map<int, Eigen::Vector3f> placementPositions) { if (firstFramesWithoutPlacement && placementPositions.size()) { firstFramesWithoutPlacement = false; forcesLabeller->setPositions(labellerFrameData, placementPositions); } return forcesLabeller->update(labellerFrameData, placementPositions); } void LabellingCoordinator::distributeLabelsToLayers() { auto centerWithLabelIds = clustering.getCentersWithLabelIds(); int layerIndex = 0; for (auto &pair : centerWithLabelIds) { auto &container = labelsInLayer[layerIndex]; container->clear(); for (int labelId : pair.second) { container->add(labels->getById(labelId)); labelIdToLayerIndex[labelId] = layerIndex; } layerIndex++; } } void LabellingCoordinator::updateLabelPositionsInLabelNodes( std::map<int, Eigen::Vector3f> newPositions) { for (auto &labelNode : nodes->getLabelNodes()) { if (newPositions.count(labelNode->label.id)) { labelNode->setIsVisible(true); labelNode->labelPosition = newPositions[labelNode->label.id]; labelNode->layerIndex = labelIdToLayerIndex[labelNode->label.id]; } else { labelNode->setIsVisible(false); } } } <|endoftext|>
<commit_before>// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/browser/application_system_tizen.h" #include <cstdio> #include <string> #include <appcore/appcore-common.h> // NOLINT #include <pkgmgr-info.h> // NOLINT #include "base/command_line.h" #include "base/strings/string_util.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "net/base/filename_util.h" #include "xwalk/application/browser/application_service_tizen.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/id_util.h" #include "xwalk/application/extension/application_runtime_extension.h" #include "xwalk/application/extension/application_widget_extension.h" #include "xwalk/runtime/browser/xwalk_browser_context.h" #include "xwalk/runtime/common/xwalk_switches.h" enum app_event { AE_UNKNOWN, AE_CREATE, AE_TERMINATE, AE_PAUSE, AE_RESUME, AE_RESET, AE_LOWMEM_POST, AE_MEM_FLUSH, AE_MAX }; // Private struct from appcore-internal, necessary to get events from // the system. struct ui_ops { void* data; void (*cb_app)(enum app_event evnt, void* data, bundle* b); }; static ui_ops appcore_ops; namespace xwalk { namespace application { ApplicationSystemTizen::ApplicationSystemTizen(XWalkBrowserContext* context) : ApplicationSystem(context) { } ApplicationSystemTizen::~ApplicationSystemTizen() { } namespace { struct AppcoreHandlerData { ApplicationSystemTizen* app_system; std::string app_id; ApplicationTizen* current_app; AppcoreHandlerData(ApplicationSystemTizen* system, const std::string& id) : app_system(system), app_id(id), current_app(nullptr) { } }; void application_event_cb(app_event event, void* data, bundle* b) { LOG(INFO) << "Received Tizen appcore event: " << event; AppcoreHandlerData* handler_data = reinterpret_cast<AppcoreHandlerData*>(data); ApplicationSystemTizen* app_system = handler_data->app_system; CHECK(app_system); switch (event) { case AE_UNKNOWN: case AE_CREATE: break; case AE_TERMINATE: if (handler_data->current_app) { handler_data->current_app->Terminate(); delete handler_data; } break; case AE_PAUSE: if (handler_data->current_app) handler_data->current_app->Suspend(); break; case AE_RESUME: if (handler_data->current_app) handler_data->current_app->Resume(); break; case AE_RESET: { const std::string& app_id = handler_data->app_id; LOG(INFO) << "Attempting to launch the app with id: " << app_id; if (!IsValidApplicationID(app_id)) break; ApplicationServiceTizen* app_service_tizen = ToApplicationServiceTizen(app_system->application_service()); // TODO(t.iwanek): // In tizen platform RESET event should reload application // It should be handled it here. // By now it will just ignore second launch of an application std::string encoded_bundle; bundle_raw* r = nullptr; int len = 0; if (!bundle_encode(b, &r, &len)) { encoded_bundle.assign(reinterpret_cast<char*>(r), len); bundle_free_encoded_rawdata(&r); } Application* app = app_service_tizen->LaunchFromAppID(app_id, encoded_bundle); LOG(INFO) << "Application launched with id: " << app->id(); handler_data->current_app = static_cast<ApplicationTizen*>(app); break; } case AE_LOWMEM_POST: case AE_MEM_FLUSH: case AE_MAX: break; } } } // namespace bool ApplicationSystemTizen::LaunchFromCommandLine( const base::CommandLine& cmd_line, const GURL& url) { // Handles raw app_id passed as first non-switch argument. const base::CommandLine::StringVector& args = cmd_line.argv(); CHECK(!args.empty()); base::FilePath exec_path(args[0]); std::string app_id = exec_path.BaseName().MaybeAsASCII(); const std::string& name = std::string("xwalk-") + app_id; appcore_ops.cb_app = application_event_cb; appcore_ops.data = new AppcoreHandlerData(this, app_id); // pass only positional arguments to appcore (possible aul parameters) // skip chromium flags size_t positionals = 0; size_t size = args.size() + 1; scoped_ptr<char*[]> argv(new char*[size]); memset(argv.get(), 0x0, size); for (size_t i = 0; i < size - 1; ++i) { if (!StartsWithASCII(args[i], "--", false)) argv[positionals++] = const_cast<char*>(args[i].c_str()); } if (appcore_init(name.c_str(), &appcore_ops, positionals, argv.get())) { LOG(ERROR) << "Failed to initialize appcore"; return false; } return true; } } // namespace application } // namespace xwalk <commit_msg>Fix crash issue when app control event was invoked<commit_after>// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/browser/application_system_tizen.h" #include <cstdio> #include <string> #include <appcore/appcore-common.h> // NOLINT #include <pkgmgr-info.h> // NOLINT #include "base/command_line.h" #include "base/strings/string_util.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "net/base/filename_util.h" #include "xwalk/application/browser/application_service_tizen.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/id_util.h" #include "xwalk/application/extension/application_runtime_extension.h" #include "xwalk/application/extension/application_widget_extension.h" #include "xwalk/runtime/browser/xwalk_browser_context.h" #include "xwalk/runtime/common/xwalk_switches.h" enum app_event { AE_UNKNOWN, AE_CREATE, AE_TERMINATE, AE_PAUSE, AE_RESUME, AE_RESET, AE_LOWMEM_POST, AE_MEM_FLUSH, AE_MAX }; // Private struct from appcore-internal, necessary to get events from // the system. struct ui_ops { void* data; void (*cb_app)(enum app_event evnt, void* data, bundle* b); }; static ui_ops appcore_ops; namespace xwalk { namespace application { ApplicationSystemTizen::ApplicationSystemTizen(XWalkBrowserContext* context) : ApplicationSystem(context) { } ApplicationSystemTizen::~ApplicationSystemTizen() { } namespace { struct AppcoreHandlerData { ApplicationSystemTizen* app_system; std::string app_id; ApplicationTizen* current_app; AppcoreHandlerData(ApplicationSystemTizen* system, const std::string& id) : app_system(system), app_id(id), current_app(nullptr) { } }; void application_event_cb(app_event event, void* data, bundle* b) { LOG(INFO) << "Received Tizen appcore event: " << event; AppcoreHandlerData* handler_data = reinterpret_cast<AppcoreHandlerData*>(data); ApplicationSystemTizen* app_system = handler_data->app_system; CHECK(app_system); switch (event) { case AE_UNKNOWN: case AE_CREATE: break; case AE_TERMINATE: if (handler_data->current_app) { handler_data->current_app->Terminate(); delete handler_data; } break; case AE_PAUSE: if (handler_data->current_app) handler_data->current_app->Suspend(); break; case AE_RESUME: if (handler_data->current_app) handler_data->current_app->Resume(); break; case AE_RESET: { const std::string& app_id = handler_data->app_id; LOG(INFO) << "Attempting to launch the app with id: " << app_id; if (!IsValidApplicationID(app_id)) break; ApplicationServiceTizen* app_service_tizen = ToApplicationServiceTizen(app_system->application_service()); // TODO(t.iwanek): // In tizen platform RESET event should reload application // It should be handled it here. // By now it will just ignore second launch of an application std::string encoded_bundle; bundle_raw* r = nullptr; int len = 0; if (!bundle_encode(b, &r, &len)) { encoded_bundle.assign(reinterpret_cast<char*>(r), len); bundle_free_encoded_rawdata(&r); } Application* app = app_service_tizen->LaunchFromAppID(app_id, encoded_bundle); if (app) { LOG(INFO) << "Application launched with id: " << app->id(); handler_data->current_app = static_cast<ApplicationTizen*>(app); } break; } case AE_LOWMEM_POST: case AE_MEM_FLUSH: case AE_MAX: break; } } } // namespace bool ApplicationSystemTizen::LaunchFromCommandLine( const base::CommandLine& cmd_line, const GURL& url) { // Handles raw app_id passed as first non-switch argument. const base::CommandLine::StringVector& args = cmd_line.argv(); CHECK(!args.empty()); base::FilePath exec_path(args[0]); std::string app_id = exec_path.BaseName().MaybeAsASCII(); const std::string& name = std::string("xwalk-") + app_id; appcore_ops.cb_app = application_event_cb; appcore_ops.data = new AppcoreHandlerData(this, app_id); // pass only positional arguments to appcore (possible aul parameters) // skip chromium flags size_t positionals = 0; size_t size = args.size() + 1; scoped_ptr<char*[]> argv(new char*[size]); memset(argv.get(), 0x0, size); for (size_t i = 0; i < size - 1; ++i) { if (!StartsWithASCII(args[i], "--", false)) argv[positionals++] = const_cast<char*>(args[i].c_str()); } if (appcore_init(name.c_str(), &appcore_ops, positionals, argv.get())) { LOG(ERROR) << "Failed to initialize appcore"; return false; } return true; } } // namespace application } // namespace xwalk <|endoftext|>
<commit_before>/** \brief A tool to add DDC metadata to title data using various means. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <set> #include <unordered_map> #include <cstdlib> #include <cstring> #include "DirectoryEntry.h" #include "Leader.h" #include "MarcUtil.h" #include "RegexMatcher.h" #include "Subfields.h" #include "util.h" bool IsPossibleDDC(const std::string &ddc_candidate) { static const RegexMatcher *matcher(RegexMatcher::RegexMatcherFactory("^\\d\\d\\d")); std::string err_msg; if (not matcher->matched(ddc_candidate, &err_msg)) { if (err_msg.empty()) return false; Error("unexpected regex error while trying to match \"" + ddc_candidate + "\": " + err_msg); } return true; } void ExtractDDCsFromField(const std::string &tag, const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields, std::set<std::string> * const ddcs) { const auto begin_end(DirectoryEntry::FindFields(tag, dir_entries)); for (auto iter(begin_end.first); iter != begin_end.second; ++iter) { const Subfields subfields(fields[iter - dir_entries.begin()]); if (subfields.hasSubfield('z')) // Auxillary table number => not a regular DDC in $a! continue; const auto subfield_a_begin_end(subfields.getIterators('a')); for (auto ddc(subfield_a_begin_end.first); ddc != subfield_a_begin_end.second; ++ddc) { if (IsPossibleDDC(ddc->second)) ddcs->insert(ddc->second); } } } void ExtractDDCsFromNormdata(const bool verbose, FILE * const norm_input, std::unordered_map<std::string, std::set<std::string>> * const norm_ids_to_ddcs_map) { norm_ids_to_ddcs_map->clear(); if (verbose) std::cerr << "Starting loading of norm data.\n"; unsigned count(0), ddc_record_count(0); while (const MarcUtil::Record record = MarcUtil::Record(norm_input)) { ++count; const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const auto _001_iter(DirectoryEntry::FindField("001", dir_entries)); if (_001_iter == dir_entries.end()) continue; const std::vector<std::string> &fields(record.getFields()); const std::string &control_number(fields[_001_iter - dir_entries.begin()]); std::set<std::string> ddcs; ExtractDDCsFromField("083", dir_entries, fields, &ddcs); ExtractDDCsFromField("089", dir_entries, fields, &ddcs); if (not ddcs.empty()) { ++ddc_record_count; norm_ids_to_ddcs_map->insert(std::make_pair(control_number, ddcs)); } } if (verbose) { std::cerr << "Read " << count << " norm data records.\n"; std::cerr << ddc_record_count << " records had DDC entries.\n"; } } void ExtractTopicIDs(const std::string &tags, const MarcUtil::Record &record, const std::set<std::string> &existing_ddcs, std::set<std::string> * const topic_ids) { topic_ids->clear(); std::vector<std::string> individual_tags; StringUtil::Split(tags, ':', &individual_tags); const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const std::vector<std::string> &fields(record.getFields()); for (const auto &tag : individual_tags) { const ssize_t first_index(record.getFieldIndex(tag)); if (first_index == -1) continue; for (size_t index(first_index); index < dir_entries.size() and dir_entries[index].getTag() == tag; ++index) { const Subfields subfields(fields[index]); const auto begin_end(subfields.getIterators('0')); for (auto subfield0(begin_end.first); subfield0 != begin_end.second; ++subfield0) { if (not StringUtil::StartsWith(subfield0->second, "(DE-576)")) continue; const std::string topic_id(subfield0->second.substr(8)); if (existing_ddcs.find(topic_id) == existing_ddcs.end()) // This one is new! topic_ids->insert(topic_id); } } } } void AugmentRecordsWithDDCs(const bool verbose, FILE * const title_input, FILE * const title_output, const std::unordered_map<std::string, std::set<std::string>> &norm_ids_to_ddcs_map) { if (verbose) std::cerr << "Starting augmenting of data.\n"; unsigned count(0), augmented_count(0), already_had_ddcs(0), never_had_ddcs_and_now_have_ddcs(0); while (MarcUtil::Record record = MarcUtil::Record(title_input)) { ++count; // Extract already existing DDCs: std::set<std::string> existing_ddcs; const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const std::vector<std::string> &fields(record.getFields()); ExtractDDCsFromField("082", dir_entries, fields, &existing_ddcs); ExtractDDCsFromField("083", dir_entries, fields, &existing_ddcs); if (not existing_ddcs.empty()) ++already_had_ddcs; std::set<std::string> topic_ids; // = the IDs of the corresponding norm data records ExtractTopicIDs("600:610:611:630:650:653:656:689", record, existing_ddcs, &topic_ids); if (topic_ids.empty()) { record.write(title_output); continue; } std::set<std::string> new_ddcs; for (const auto &topic_id : topic_ids) { const auto iter(norm_ids_to_ddcs_map.find(topic_id)); if (iter != norm_ids_to_ddcs_map.end()) new_ddcs.insert(iter->second.begin(), iter->second.end()); } if (not new_ddcs.empty()) { ++augmented_count; if (existing_ddcs.empty()) ++never_had_ddcs_and_now_have_ddcs; for (const auto &new_ddc : new_ddcs) { const std::string new_field("0 ""\x1F""a" + new_ddc); record.insertField("082", new_field); } } record.write(title_output); } if (verbose) { std::cerr << "Read " << count << " title data records.\n"; std::cerr << already_had_ddcs << " already had DDCs.\n"; std::cerr << "Augmented " << augmented_count << " records.\n"; std::cerr << never_had_ddcs_and_now_have_ddcs << " now have DDCs but didn't before.\n"; } } void Usage() { std::cerr << "usage: " << ::progname << " [--verbose] input_title_data norm_data output_title_data\n"; std::exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 4 and argc != 5) Usage(); bool verbose(false); if (argc == 5) { if (std::strcmp(argv[1], "--verbose") == 0) verbose = true; else Usage(); } const std::string title_input_filename(argv[verbose ? 2 : 1]); FILE *title_input = std::fopen(title_input_filename.c_str(), "rbm"); if (title_input == nullptr) Error("can't open \"" + title_input_filename + "\" for reading!"); const std::string norm_input_filename(argv[verbose ? 3 : 2]); FILE *norm_input = std::fopen(norm_input_filename.c_str(), "rbm"); if (norm_input == nullptr) Error("can't open \"" + norm_input_filename + "\" for reading!"); const std::string title_output_filename(argv[verbose ? 4 : 3]); FILE *title_output = std::fopen(title_output_filename.c_str(), "wb"); if (title_output == nullptr) Error("can't open \"" + title_output_filename + "\" for writing!"); if (unlikely(title_input_filename == title_output_filename)) Error("Title input file name equals title output file name!"); if (unlikely(norm_input_filename == title_output_filename)) Error("Norm data input file name equals title output file name!"); try { std::unordered_map<std::string, std::set<std::string>> norm_ids_to_ddcs_map; ExtractDDCsFromNormdata(verbose, norm_input, &norm_ids_to_ddcs_map); std::fclose(norm_input); AugmentRecordsWithDDCs(verbose, title_input, title_output, norm_ids_to_ddcs_map); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } std::fclose(title_input); } <commit_msg>Add a tag in 082 for the newly added DDC's.<commit_after>/** \brief A tool to add DDC metadata to title data using various means. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <set> #include <unordered_map> #include <cstdlib> #include <cstring> #include "DirectoryEntry.h" #include "Leader.h" #include "MarcUtil.h" #include "RegexMatcher.h" #include "Subfields.h" #include "util.h" bool IsPossibleDDC(const std::string &ddc_candidate) { static const RegexMatcher *matcher(RegexMatcher::RegexMatcherFactory("^\\d\\d\\d")); std::string err_msg; if (not matcher->matched(ddc_candidate, &err_msg)) { if (err_msg.empty()) return false; Error("unexpected regex error while trying to match \"" + ddc_candidate + "\": " + err_msg); } return true; } void ExtractDDCsFromField(const std::string &tag, const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields, std::set<std::string> * const ddcs) { const auto begin_end(DirectoryEntry::FindFields(tag, dir_entries)); for (auto iter(begin_end.first); iter != begin_end.second; ++iter) { const Subfields subfields(fields[iter - dir_entries.begin()]); if (subfields.hasSubfield('z')) // Auxillary table number => not a regular DDC in $a! continue; const auto subfield_a_begin_end(subfields.getIterators('a')); for (auto ddc(subfield_a_begin_end.first); ddc != subfield_a_begin_end.second; ++ddc) { if (IsPossibleDDC(ddc->second)) ddcs->insert(ddc->second); } } } void ExtractDDCsFromNormdata(const bool verbose, FILE * const norm_input, std::unordered_map<std::string, std::set<std::string>> * const norm_ids_to_ddcs_map) { norm_ids_to_ddcs_map->clear(); if (verbose) std::cerr << "Starting loading of norm data.\n"; unsigned count(0), ddc_record_count(0); while (const MarcUtil::Record record = MarcUtil::Record(norm_input)) { ++count; const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const auto _001_iter(DirectoryEntry::FindField("001", dir_entries)); if (_001_iter == dir_entries.end()) continue; const std::vector<std::string> &fields(record.getFields()); const std::string &control_number(fields[_001_iter - dir_entries.begin()]); std::set<std::string> ddcs; ExtractDDCsFromField("083", dir_entries, fields, &ddcs); ExtractDDCsFromField("089", dir_entries, fields, &ddcs); if (not ddcs.empty()) { ++ddc_record_count; norm_ids_to_ddcs_map->insert(std::make_pair(control_number, ddcs)); } } if (verbose) { std::cerr << "Read " << count << " norm data records.\n"; std::cerr << ddc_record_count << " records had DDC entries.\n"; } } void ExtractTopicIDs(const std::string &tags, const MarcUtil::Record &record, const std::set<std::string> &existing_ddcs, std::set<std::string> * const topic_ids) { topic_ids->clear(); std::vector<std::string> individual_tags; StringUtil::Split(tags, ':', &individual_tags); const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const std::vector<std::string> &fields(record.getFields()); for (const auto &tag : individual_tags) { const ssize_t first_index(record.getFieldIndex(tag)); if (first_index == -1) continue; for (size_t index(first_index); index < dir_entries.size() and dir_entries[index].getTag() == tag; ++index) { const Subfields subfields(fields[index]); const auto begin_end(subfields.getIterators('0')); for (auto subfield0(begin_end.first); subfield0 != begin_end.second; ++subfield0) { if (not StringUtil::StartsWith(subfield0->second, "(DE-576)")) continue; const std::string topic_id(subfield0->second.substr(8)); if (existing_ddcs.find(topic_id) == existing_ddcs.end()) // This one is new! topic_ids->insert(topic_id); } } } } void AugmentRecordsWithDDCs(const bool verbose, FILE * const title_input, FILE * const title_output, const std::unordered_map<std::string, std::set<std::string>> &norm_ids_to_ddcs_map) { if (verbose) std::cerr << "Starting augmenting of data.\n"; unsigned count(0), augmented_count(0), already_had_ddcs(0), never_had_ddcs_and_now_have_ddcs(0); while (MarcUtil::Record record = MarcUtil::Record(title_input)) { ++count; // Extract already existing DDCs: std::set<std::string> existing_ddcs; const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const std::vector<std::string> &fields(record.getFields()); ExtractDDCsFromField("082", dir_entries, fields, &existing_ddcs); ExtractDDCsFromField("083", dir_entries, fields, &existing_ddcs); if (not existing_ddcs.empty()) ++already_had_ddcs; std::set<std::string> topic_ids; // = the IDs of the corresponding norm data records ExtractTopicIDs("600:610:611:630:650:653:656:689", record, existing_ddcs, &topic_ids); if (topic_ids.empty()) { record.write(title_output); continue; } std::set<std::string> new_ddcs; for (const auto &topic_id : topic_ids) { const auto iter(norm_ids_to_ddcs_map.find(topic_id)); if (iter != norm_ids_to_ddcs_map.end()) new_ddcs.insert(iter->second.begin(), iter->second.end()); } if (not new_ddcs.empty()) { ++augmented_count; if (existing_ddcs.empty()) ++never_had_ddcs_and_now_have_ddcs; for (const auto &new_ddc : new_ddcs) { const std::string new_field("0 ""\x1F""a" + new_ddc + "\x1F""cfrom_topic_norm_data"); record.insertField("082", new_field); } } record.write(title_output); } if (verbose) { std::cerr << "Read " << count << " title data records.\n"; std::cerr << already_had_ddcs << " already had DDCs.\n"; std::cerr << "Augmented " << augmented_count << " records.\n"; std::cerr << never_had_ddcs_and_now_have_ddcs << " now have DDCs but didn't before.\n"; } } void Usage() { std::cerr << "usage: " << ::progname << " [--verbose] input_title_data norm_data output_title_data\n"; std::exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 4 and argc != 5) Usage(); bool verbose(false); if (argc == 5) { if (std::strcmp(argv[1], "--verbose") == 0) verbose = true; else Usage(); } const std::string title_input_filename(argv[verbose ? 2 : 1]); FILE *title_input = std::fopen(title_input_filename.c_str(), "rbm"); if (title_input == nullptr) Error("can't open \"" + title_input_filename + "\" for reading!"); const std::string norm_input_filename(argv[verbose ? 3 : 2]); FILE *norm_input = std::fopen(norm_input_filename.c_str(), "rbm"); if (norm_input == nullptr) Error("can't open \"" + norm_input_filename + "\" for reading!"); const std::string title_output_filename(argv[verbose ? 4 : 3]); FILE *title_output = std::fopen(title_output_filename.c_str(), "wb"); if (title_output == nullptr) Error("can't open \"" + title_output_filename + "\" for writing!"); if (unlikely(title_input_filename == title_output_filename)) Error("Title input file name equals title output file name!"); if (unlikely(norm_input_filename == title_output_filename)) Error("Norm data input file name equals title output file name!"); try { std::unordered_map<std::string, std::set<std::string>> norm_ids_to_ddcs_map; ExtractDDCsFromNormdata(verbose, norm_input, &norm_ids_to_ddcs_map); std::fclose(norm_input); AugmentRecordsWithDDCs(verbose, title_input, title_output, norm_ids_to_ddcs_map); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } std::fclose(title_input); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <map> #include <string> #include <sstream> #include <boost/chrono/thread_clock.hpp> using namespace std; using namespace boost::chrono; typedef long long count_t; count_t benchmark_empty(count_t count) { for (count_t i = 0; i < count; ++i) { ; } return count; } count_t benchmark_add(count_t count) { count_t a = 0; for (count_t i = 0; i < count; ++i) { a += i; } return count; } count_t non_inline_func(count_t x) { return x; } count_t benchmark_func_call(count_t count) { count_t a = 0; for (count_t i = 0; i < count; ++i) { a += non_inline_func(i); } cout << "a: " << a << endl; return count; } inline count_t inline_func(count_t x) { return x; } count_t benchmark_inline_func_call(count_t count) { count_t a = 0; for (count_t i = 0; i < count; ++i) { a += inline_func(i); } cout << "a: " << a << endl; return count; } count_t benchmark_deref_ptr(count_t count) { count_t a = 0; count_t* b = &a; count_t c; count_t result; for (count_t i = 0; i < count; ++i) { c = *b; } result = c; return result; } count_t benchmark_write_64k(count_t count) { const int memSize = 1024 * 64; unsigned char mem[memSize]; for (count_t i = 0; i < count; ++i) { for (int j = 0; j < memSize; ++j) { mem[j] = j; } } return mem[memSize - 1]; } count_t benchmark_read_64k(count_t count) { const int memSize = 1024 * 64; unsigned char mem[memSize]; for (int j = 0; j < memSize; ++j) { mem[j] = j; } int result = 1; for (count_t i = 0; i < count; ++i) { for (int j = 0; j < memSize; ++j) { result &= mem[j]; } } return result; } count_t benchmark_read_64k_vec(count_t count) { const int memSize = 1024 * 64; vector<unsigned char> mem(memSize); for (int j = 0; j < memSize; ++j) { mem[j] = j; } int result = 1; for (count_t i = 0; i < count; ++i) { for (int j = 0; j < memSize; ++j) { result &= mem[j]; } } return result; } count_t benchmark_read_64k_vec_at(count_t count) { const int memSize = 1024 * 64; vector<unsigned char> mem(memSize); for (int j = 0; j < memSize; ++j) { mem[j] = j; } int result = 1; for (count_t i = 0; i < count; ++i) { for (int j = 0; j < memSize; ++j) { result &= mem.at(j); } } return result; } count_t benchmark_try_catch(count_t count) { int result = 0; for (count_t i = 0; i < count; ++i) { try { throw exception(); } catch (exception& e) { ++result; } } return result; } int a_func(int a) { return 2 * a; } count_t benchmark_func_ptr(count_t count) { int result = 0; auto f_ptr = a_func; for (count_t i = 0; i < count; ++i) { result += f_ptr(1); } return result; } class C { public: int a_method(int a) { return 2 * a; } virtual int a_virtual_method(int a) { return 2 * a; } }; class C2 : public C { public: virtual int a_virtual_method(int a) { return 3 * a; } }; count_t benchmark_nonvirt_method(count_t count) { int result = 0; C c; for (count_t i = 0; i < count; ++i) { result += c.a_method(1); } return result; } count_t benchmark_virt_method(count_t count) { int result = 0; C2 c2; for (count_t i = 0; i < count; ++i) { result += c2.a_virtual_method(1); } return result; } count_t benchmark_lambda(count_t count) { int result = 0; int a; for (count_t i = 0; i < count; ++i) { result += [&a, i]() -> int { return a + i; }(); } return result; } typedef count_t (*benchmark_ptr)(count_t); map<string, benchmark_ptr> commands = { {"empty", benchmark_empty}, {"add", benchmark_add}, {"func_call", benchmark_func_call}, {"inline_func_call", benchmark_func_call}, {"deref_ptr", benchmark_deref_ptr}, {"write_64k", benchmark_write_64k}, {"read_64k", benchmark_read_64k}, {"read_64k_vec", benchmark_read_64k_vec}, {"read_64k_vec_at", benchmark_read_64k_vec_at}, {"try_catch", benchmark_try_catch}, {"func_ptr", benchmark_func_ptr}, {"nonvirt_method", benchmark_nonvirt_method}, {"virt_method", benchmark_virt_method}, {"lambda", benchmark_lambda}, }; int main(int argc, char const* argv[]) { if (argc < 3) { cerr << "usage" << endl; exit(1); } auto cmd_name = argv[1]; auto count_str = argv[2]; count_t count; istringstream count_strm(count_str); if (!(count_strm >> count)) { cerr << "Invalid count: '" << count_str << endl; exit(1); } auto cmd_it = commands.find(cmd_name); if (cmd_it == commands.end()) { cerr << "Command '" << cmd_name << "' unknown" << endl; exit(1); } thread_clock::time_point start = thread_clock::now(); auto result = cmd_it->second(count); thread_clock::time_point stop = thread_clock::now(); auto duration = duration_cast<nanoseconds>(stop - start).count(); auto duration_per_call_ns = duration / static_cast<double>(count); auto duration_ms = duration / 1000000.; std::cout << "Result: " << result << endl; std::cout << "duration per call: " << duration_per_call_ns << " ns " << "(" << (duration_per_call_ns / 1000.) << " µs) \n"; std::cout << (1. / duration_per_call_ns * 1000) << " million calls per s\n"; std::cout << "duration: " << duration_ms << " ms\n"; return 0; } <commit_msg>Added benchmarks for bitsets<commit_after>#include <iostream> #include <vector> #include <map> #include <string> #include <sstream> #include <bitset> #include <boost/chrono/thread_clock.hpp> using namespace std; using namespace boost::chrono; typedef long long count_t; count_t benchmark_empty(count_t count) { for (count_t i = 0; i < count; ++i) { ; } return count; } count_t benchmark_add(count_t count) { count_t a = 0; for (count_t i = 0; i < count; ++i) { a += i; } return count; } count_t non_inline_func(count_t x) { return x; } count_t benchmark_func_call(count_t count) { count_t a = 0; for (count_t i = 0; i < count; ++i) { a += non_inline_func(i); } cout << "a: " << a << endl; return count; } inline count_t inline_func(count_t x) { return x; } count_t benchmark_inline_func_call(count_t count) { count_t a = 0; for (count_t i = 0; i < count; ++i) { a += inline_func(i); } cout << "a: " << a << endl; return count; } count_t benchmark_deref_ptr(count_t count) { count_t a = 0; count_t* b = &a; count_t c; count_t result; for (count_t i = 0; i < count; ++i) { c = *b; } result = c; return result; } count_t benchmark_write_64k(count_t count) { const int memSize = 1024 * 64; unsigned char mem[memSize]; for (count_t i = 0; i < count; ++i) { for (int j = 0; j < memSize; ++j) { mem[j] = j; } } return mem[memSize - 1]; } count_t benchmark_read_64k(count_t count) { const int memSize = 1024 * 64; unsigned char mem[memSize]; for (int j = 0; j < memSize; ++j) { mem[j] = j; } int result = 1; for (count_t i = 0; i < count; ++i) { for (int j = 0; j < memSize; ++j) { result &= mem[j]; } } return result; } count_t benchmark_read_64k_vec(count_t count) { const int memSize = 1024 * 64; vector<unsigned char> mem(memSize); for (int j = 0; j < memSize; ++j) { mem[j] = j; } int result = 1; for (count_t i = 0; i < count; ++i) { for (int j = 0; j < memSize; ++j) { result &= mem[j]; } } return result; } count_t benchmark_read_64k_vec_at(count_t count) { const int memSize = 1024 * 64; vector<unsigned char> mem(memSize); for (int j = 0; j < memSize; ++j) { mem[j] = j; } int result = 1; for (count_t i = 0; i < count; ++i) { for (int j = 0; j < memSize; ++j) { result &= mem.at(j); } } return result; } count_t benchmark_try_catch(count_t count) { int result = 0; for (count_t i = 0; i < count; ++i) { try { throw exception(); } catch (exception& e) { ++result; } } return result; } int a_func(int a) { return 2 * a; } count_t benchmark_func_ptr(count_t count) { int result = 0; auto f_ptr = a_func; for (count_t i = 0; i < count; ++i) { result += f_ptr(1); } return result; } class C { public: int a_method(int a) { return 2 * a; } virtual int a_virtual_method(int a) { return 2 * a; } }; class C2 : public C { public: virtual int a_virtual_method(int a) { return 3 * a; } }; count_t benchmark_nonvirt_method(count_t count) { int result = 0; C c; for (count_t i = 0; i < count; ++i) { result += c.a_method(1); } return result; } count_t benchmark_virt_method(count_t count) { int result = 0; C2 c2; for (count_t i = 0; i < count; ++i) { result += c2.a_virtual_method(1); } return result; } count_t benchmark_lambda(count_t count) { int result = 0; int a; for (count_t i = 0; i < count; ++i) { result += [&a, i]() -> int { return a + i; }(); } return result; } count_t benchmark_xor(count_t count) { int result = 0; unsigned char c = 1; for (count_t i = 0; i < count; ++i) { c ^= i; } result = c; return result; } count_t benchmark_xor_bitset(count_t count) { int result = 0; bitset<8> c = 1; for (count_t i = 0; i < count; ++i) { c ^= i; } result = c.to_ulong(); return result; } typedef count_t (*benchmark_ptr)(count_t); map<string, benchmark_ptr> commands = { {"empty", benchmark_empty}, {"add", benchmark_add}, {"func_call", benchmark_func_call}, {"inline_func_call", benchmark_func_call}, {"deref_ptr", benchmark_deref_ptr}, {"write_64k", benchmark_write_64k}, {"read_64k", benchmark_read_64k}, {"read_64k_vec", benchmark_read_64k_vec}, {"read_64k_vec_at", benchmark_read_64k_vec_at}, {"try_catch", benchmark_try_catch}, {"func_ptr", benchmark_func_ptr}, {"nonvirt_method", benchmark_nonvirt_method}, {"virt_method", benchmark_virt_method}, {"lambda", benchmark_lambda}, {"xor", benchmark_xor}, {"xor_bitset", benchmark_xor_bitset}, }; int main(int argc, char const* argv[]) { if (argc < 3) { cerr << "usage" << endl; exit(1); } auto cmd_name = argv[1]; auto count_str = argv[2]; count_t count; istringstream count_strm(count_str); if (!(count_strm >> count)) { cerr << "Invalid count: '" << count_str << endl; exit(1); } auto cmd_it = commands.find(cmd_name); if (cmd_it == commands.end()) { cerr << "Command '" << cmd_name << "' unknown" << endl; exit(1); } thread_clock::time_point start = thread_clock::now(); auto result = cmd_it->second(count); thread_clock::time_point stop = thread_clock::now(); auto duration = duration_cast<nanoseconds>(stop - start).count(); auto duration_per_call_ns = duration / static_cast<double>(count); auto duration_ms = duration / 1000000.; std::cout << "Result: " << result << endl; std::cout << "duration per call: " << duration_per_call_ns << " ns " << "(" << (duration_per_call_ns / 1000.) << " µs) \n"; std::cout << (1. / duration_per_call_ns * 1000) << " million calls per s\n"; std::cout << "duration: " << duration_ms << " ms\n"; return 0; } <|endoftext|>
<commit_before>#pragma once #include "Head.h" #include <iostream> #include "maths.hpp" constexpr const int32_t BASE_MOD = 1000000007; /// caide keep template<typename T> inline T& add_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a += b) >= mod) { a -= mod; } return a; } template<typename T> inline T& sub_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a -= b) < 0) { a += mod; } return a; } template<typename T> inline T& mul_mod(T& a, const T b, const T mod = BASE_MOD) { a = static_cast<ll>(a) * b % mod; return a; } template<typename T, T MOD = BASE_MOD> class ModInt { public: /// caide keep constexpr ModInt() : ModInt(0) {} template<typename U> constexpr ModInt(const U value) : value_(normalize(value)) { static_assert(MOD > 0, "Modulo must be strictly positive."); // static_assert((std::equal<T, int32_t> && mod <= 0x3f3f3f3f) || (std::equal<T, int64_t> && mod <= 0x3f3f3f3f3f3f3f3fLL), "Modulo must be less than half of the max value for typename."); } constexpr T value() const { return value_; } constexpr bool operator ==(const ModInt rhs) const { return value_ == rhs.value_; } constexpr bool operator !=(const ModInt rhs) const { return !operator==(rhs); } constexpr bool operator <(const ModInt& rhs) const { return value_ < rhs.value_; } constexpr bool operator >(const ModInt& rhs) const { return value_ > rhs.value_; } constexpr ModInt operator +(const ModInt rhs) const { T x = value_; return{ add_mod(x, rhs.value_, MOD) }; } constexpr ModInt operator -(const ModInt rhs) const { T x = value_; return{ sub_mod(x, rhs.value_, MOD) }; } ModInt operator *(const ModInt rhs) const { T x = value_; return{ mul_mod(x, rhs.value_, MOD) }; } ModInt& operator +=(const ModInt rhs) { add_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator -=(const ModInt rhs) { sub_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator *=(const ModInt rhs) { mul_mod(value_, rhs.value_, MOD); return *this; } ModInt operator ++(int) { const ModInt ret(value_); add_mod(value_, 1, MOD); return ret; } ModInt operator --(int) { const ModInt ret(value_); sub_mod(value_, 1, MOD); return ret; } ModInt& operator ++() { add_mod(value_, 1, MOD); return *this; } ModInt& operator --() { sub_mod(value_, 1, MOD); return *this; } constexpr ModInt inverse() const { return{ inverseElement(static_cast<ll>(value_), MOD) }; } friend std::istream& operator >>(std::istream& in, ModInt& rhs) { T x; in >> x; rhs.value = rhs.normalize(x); return in; } friend std::ostream& operator <<(std::ostream& out, ModInt& rhs) { out << rhs.value_; return out; } private: T value_; template<typename U> T normalize(const U value) const { if (value >= 0 && value < MOD) { return value; } const T ret = value % MOD; if (ret < 0) { return ret + MOD; } return ret; } }; namespace std { template<typename T, T MOD> struct is_integral<ModInt<T, MOD>> : std::true_type {}; } <commit_msg>Minor fix in ModInt.<commit_after>#pragma once #include "Head.h" #include <iostream> #include "maths.hpp" constexpr const int32_t BASE_MOD = 1000000007; /// caide keep template<typename T> inline T& add_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a += b) >= mod) { a -= mod; } return a; } template<typename T> inline T& sub_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a -= b) < 0) { a += mod; } return a; } template<typename T> inline T& mul_mod(T& a, const T b, const T mod = BASE_MOD) { a = static_cast<ll>(a) * b % mod; return a; } template<typename T, T MOD = BASE_MOD> class ModInt { public: /// caide keep constexpr ModInt() : ModInt(0) {} template<typename U> constexpr ModInt(const U value) : value_(normalize(value)) { static_assert(MOD > 0, "Modulo must be strictly positive."); // static_assert((std::equal<T, int32_t> && mod <= 0x3f3f3f3f) || (std::equal<T, int64_t> && mod <= 0x3f3f3f3f3f3f3f3fLL), "Modulo must be less than half of the max value for typename."); } constexpr T value() const { return value_; } constexpr bool operator ==(const ModInt rhs) const { return value_ == rhs.value_; } constexpr bool operator !=(const ModInt rhs) const { return !operator==(rhs); } constexpr bool operator <(const ModInt& rhs) const { return value_ < rhs.value_; } constexpr bool operator >(const ModInt& rhs) const { return value_ > rhs.value_; } constexpr ModInt operator +(const ModInt rhs) const { T x = value_; return{ add_mod(x, rhs.value_, MOD) }; } constexpr ModInt operator -(const ModInt rhs) const { T x = value_; return{ sub_mod(x, rhs.value_, MOD) }; } ModInt operator *(const ModInt rhs) const { T x = value_; return{ mul_mod(x, rhs.value_, MOD) }; } ModInt& operator +=(const ModInt rhs) { add_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator -=(const ModInt rhs) { sub_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator *=(const ModInt rhs) { mul_mod(value_, rhs.value_, MOD); return *this; } ModInt operator ++(int) { const ModInt ret(value_); add_mod(value_, static_cast<T>(1), MOD); return ret; } ModInt operator --(int) { const ModInt ret(value_); sub_mod(value_, static_cast<T>(1), MOD); return ret; } ModInt& operator ++() { add_mod(value_, static_cast<T>(1), MOD); return *this; } ModInt& operator --() { sub_mod(value_, static_cast<T>(1), MOD); return *this; } constexpr ModInt inverse() const { return{ inverseElement(static_cast<ll>(value_), MOD) }; } friend std::istream& operator >>(std::istream& in, ModInt& rhs) { T x; in >> x; rhs.value = rhs.normalize(x); return in; } friend std::ostream& operator <<(std::ostream& out, ModInt& rhs) { out << rhs.value_; return out; } private: T value_; template<typename U> T normalize(const U value) const { if (value >= 0 && value < MOD) { return value; } const T ret = value % MOD; if (ret < 0) { return ret + MOD; } return ret; } }; namespace std { template<typename T, T MOD> struct is_integral<ModInt<T, MOD>> : std::true_type {}; } <|endoftext|>
<commit_before>#include <algorithm> #include <vector> #include <queue> #include <boost/functional/hash.hpp> #include <unordered_map> #include "tree_fragment.h" #include "translator.h" #include "hg.h" #include "sentence_metadata.h" #include "filelib.h" #include "stringlib.h" #include "tdict.h" #include "verbose.h" using namespace std; struct Tree2StringGrammarNode { map<unsigned, Tree2StringGrammarNode> next; vector<TRulePtr> rules; }; void ReadTree2StringGrammar(istream* in, Tree2StringGrammarNode* root) { string line; while(getline(*in, line)) { size_t pos = line.find("|||"); assert(pos != string::npos); assert(pos > 3); unsigned xc = 0; while (line[pos - 1] == ' ') { --pos; xc++; } cdec::TreeFragment rule_src(line.substr(0, pos), true); Tree2StringGrammarNode* cur = root; ostringstream os; int lhs = -(rule_src.root & cdec::ALL_MASK); // build source RHS for SCFG projection // TODO - this is buggy - it will generate a well-formed SCFG rule // but it will not generate source strings correctly vector<int> frhs; for (auto sym : rule_src) { cur = &cur->next[sym]; if (sym) { if (cdec::IsFrontier(sym)) { // frontier symbols -> variables int nt = (sym & cdec::ALL_MASK); frhs.push_back(-nt); } else if (cdec::IsTerminal(sym)) { frhs.push_back(sym); } } } os << '[' << TD::Convert(-lhs) << "] |||"; for (auto x : frhs) { os << ' '; if (x < 0) os << '[' << TD::Convert(-x) << ']'; else os << TD::Convert(x); } pos += 3 + xc; while(line[pos] == ' ') { ++pos; } os << " ||| " << line.substr(pos); TRulePtr rule(new TRule(os.str())); cur->rules.push_back(rule); } } struct ParserState { ParserState() : in_iter(), node() {} cdec::TreeFragment::iterator in_iter; ParserState(const cdec::TreeFragment::iterator& it, Tree2StringGrammarNode* n) : in_iter(it), input_node_idx(it.node_idx()), node(n) {} ParserState(const cdec::TreeFragment::iterator& it, Tree2StringGrammarNode* n, const ParserState& p) : in_iter(it), future_work(p.future_work), input_node_idx(p.input_node_idx), node(n) {} vector<ParserState> future_work; int input_node_idx; // lhs of top level NT Tree2StringGrammarNode* node; }; struct Tree2StringTranslatorImpl { Tree2StringGrammarNode root; Tree2StringTranslatorImpl(const boost::program_options::variables_map& conf) { ReadFile rf(conf["grammar"].as<vector<string>>()[0]); ReadTree2StringGrammar(rf.stream(), &root); } bool Translate(const string& input, SentenceMetadata* smeta, const vector<double>& weights, Hypergraph* minus_lm_forest) { cdec::TreeFragment input_tree(input, false); Hypergraph hg; hg.ReserveNodes(input_tree.nodes.size()); vector<int> tree2hg(input_tree.nodes.size() + 1, -1); queue<ParserState> q; q.push(ParserState(input_tree.begin(), &root)); unsigned tree_top = q.front().input_node_idx; while(!q.empty()) { ParserState& s = q.front(); if (s.in_iter.at_end()) { // completed a traversal of a subtree //cerr << "I traversed a subtree of the input rooted at node=" << s.input_node_idx << " sym=" << // TD::Convert(input_tree.nodes[s.input_node_idx].lhs & cdec::ALL_MASK) << endl; if (s.node->rules.size()) { TailNodeVector tail; int& node_id = tree2hg[s.input_node_idx]; if (node_id < 0) node_id = hg.AddNode(-(input_tree.nodes[s.input_node_idx].lhs & cdec::ALL_MASK))->id_; for (auto& n : s.future_work) { int& nix = tree2hg[n.input_node_idx]; if (nix < 0) nix = hg.AddNode(-(input_tree.nodes[n.input_node_idx].lhs & cdec::ALL_MASK))->id_; tail.push_back(nix); } for (auto& r : s.node->rules) { assert(tail.size() == r->Arity()); HG::Edge* new_edge = hg.AddEdge(r, tail); new_edge->feature_values_ = r->GetFeatureValues(); // TODO: set i and j hg.ConnectEdgeToHeadNode(new_edge, &hg.nodes_[node_id]); } for (auto& w : s.future_work) q.push(w); } else { //cerr << "I can't build anything :(\n"; } } else { // more input tree to match unsigned sym = *s.in_iter; if (cdec::IsLHS(sym)) { auto nit = s.node->next.find(sym); if (nit != s.node->next.end()) { //cerr << "MATCHED LHS: " << TD::Convert(sym & cdec::ALL_MASK) << endl; q.push(ParserState(++s.in_iter, &nit->second, s)); } } else if (cdec::IsRHS(sym)) { //cerr << "Attempting to match RHS: " << TD::Convert(sym & cdec::ALL_MASK) << endl; cdec::TreeFragment::iterator var = s.in_iter; var.truncate(); auto nit1 = s.node->next.find(sym); auto nit2 = s.node->next.find(*var); if (nit2 != s.node->next.end()) { //cerr << "MATCHED VAR RHS: " << TD::Convert(sym & cdec::ALL_MASK) << endl; ParserState new_s(++var, &nit2->second, s); ParserState new_work(s.in_iter.remainder(), &root); new_s.future_work.push_back(new_work); // if this traversal of the input succeeds, future_work goes on the q q.push(new_s); } if (nit1 != s.node->next.end()) { //cerr << "MATCHED FULL RHS: " << TD::Convert(sym & cdec::ALL_MASK) << endl; q.push(ParserState(++s.in_iter, &nit1->second, s)); } } else if (cdec::IsTerminal(sym)) { auto nit = s.node->next.find(sym); if (nit != s.node->next.end()) { //cerr << "MATCHED TERMINAL: " << TD::Convert(sym) << endl; q.push(ParserState(++s.in_iter, &nit->second, s)); } } else { cerr << "This can never happen!\n"; abort(); } } q.pop(); } int goal = tree2hg[tree_top]; if (goal < 0) return false; //cerr << "Goal node: " << goal << endl; hg.TopologicallySortNodesAndEdges(goal); hg.Reweight(weights); // there might be nodes that cannot be derived // the following takes care of them vector<bool> prune(hg.edges_.size(), false); hg.PruneEdges(prune, true); //hg.PrintGraphviz(); minus_lm_forest->swap(hg); return true; } }; Tree2StringTranslator::Tree2StringTranslator(const boost::program_options::variables_map& conf) : pimpl_(new Tree2StringTranslatorImpl(conf)) {} bool Tree2StringTranslator::TranslateImpl(const string& input, SentenceMetadata* smeta, const vector<double>& weights, Hypergraph* minus_lm_forest) { return pimpl_->Translate(input, smeta, weights, minus_lm_forest); } void Tree2StringTranslator::ProcessMarkupHintsImpl(const map<string, string>& kv) { } void Tree2StringTranslator::SentenceCompleteImpl() { } std::string Tree2StringTranslator::GetDecoderType() const { return "tree2string"; } <commit_msg>deal with multiple grammars in t2s<commit_after>#include <algorithm> #include <vector> #include <queue> #include <map> #include <unordered_set> #include <boost/shared_ptr.hpp> #include <boost/functional/hash.hpp> #include "tree_fragment.h" #include "translator.h" #include "hg.h" #include "sentence_metadata.h" #include "filelib.h" #include "stringlib.h" #include "tdict.h" #include "verbose.h" using namespace std; struct Tree2StringGrammarNode { map<unsigned, Tree2StringGrammarNode> next; vector<TRulePtr> rules; }; void ReadTree2StringGrammar(istream* in, Tree2StringGrammarNode* root) { string line; while(getline(*in, line)) { size_t pos = line.find("|||"); assert(pos != string::npos); assert(pos > 3); unsigned xc = 0; while (line[pos - 1] == ' ') { --pos; xc++; } cdec::TreeFragment rule_src(line.substr(0, pos), true); Tree2StringGrammarNode* cur = root; ostringstream os; int lhs = -(rule_src.root & cdec::ALL_MASK); // build source RHS for SCFG projection // TODO - this is buggy - it will generate a well-formed SCFG rule // but it will not generate source strings correctly vector<int> frhs; for (auto sym : rule_src) { cur = &cur->next[sym]; if (sym) { if (cdec::IsFrontier(sym)) { // frontier symbols -> variables int nt = (sym & cdec::ALL_MASK); frhs.push_back(-nt); } else if (cdec::IsTerminal(sym)) { frhs.push_back(sym); } } } os << '[' << TD::Convert(-lhs) << "] |||"; for (auto x : frhs) { os << ' '; if (x < 0) os << '[' << TD::Convert(-x) << ']'; else os << TD::Convert(x); } pos += 3 + xc; while(line[pos] == ' ') { ++pos; } os << " ||| " << line.substr(pos); TRulePtr rule(new TRule(os.str())); cur->rules.push_back(rule); } } struct ParserState { ParserState() : in_iter(), node() {} cdec::TreeFragment::iterator in_iter; ParserState(const cdec::TreeFragment::iterator& it, Tree2StringGrammarNode* n) : in_iter(it), input_node_idx(it.node_idx()), node(n) {} ParserState(const cdec::TreeFragment::iterator& it, Tree2StringGrammarNode* n, const ParserState& p) : in_iter(it), future_work(p.future_work), input_node_idx(p.input_node_idx), node(n) {} bool operator==(const ParserState& o) const { return node == o.node && input_node_idx == o.input_node_idx && future_work == o.future_work && in_iter == o.in_iter; } vector<unsigned> future_work; int input_node_idx; // lhs of top level NT Tree2StringGrammarNode* node; }; namespace std { template<> struct hash<ParserState> { size_t operator()(const ParserState& s) const { size_t h = boost::hash_range(s.future_work.begin(), s.future_work.end()); boost::hash_combine(h, boost::hash_value(s.node)); boost::hash_combine(h, boost::hash_value(s.input_node_idx)); //boost::hash_combine(h, ); return h; } }; }; struct Tree2StringTranslatorImpl { vector<boost::shared_ptr<Tree2StringGrammarNode>> root; bool add_pass_through_rules; Tree2StringTranslatorImpl(const boost::program_options::variables_map& conf) : add_pass_through_rules(conf.count("add_pass_through_rules")) { if (conf.count("grammar")) { const vector<string> gf = conf["grammar"].as<vector<string>>(); root.resize(gf.size()); unsigned gc = 0; for (auto& f : gf) { ReadFile rf(f); root[gc].reset(new Tree2StringGrammarNode); ReadTree2StringGrammar(rf.stream(), &*root[gc++]); } } } bool Translate(const string& input, SentenceMetadata* smeta, const vector<double>& weights, Hypergraph* minus_lm_forest) { cdec::TreeFragment input_tree(input, false); Hypergraph hg; hg.ReserveNodes(input_tree.nodes.size()); vector<int> tree2hg(input_tree.nodes.size() + 1, -1); queue<ParserState> q; unordered_set<ParserState> unique; // only create items one time for (auto& g : root) { q.push(ParserState(input_tree.begin(), g.get())); unique.insert(q.back()); } unsigned tree_top = q.front().input_node_idx; while(!q.empty()) { ParserState& s = q.front(); if (s.in_iter.at_end()) { // completed a traversal of a subtree //cerr << "I traversed a subtree of the input rooted at node=" << s.input_node_idx << " sym=" << // TD::Convert(input_tree.nodes[s.input_node_idx].lhs & cdec::ALL_MASK) << endl; if (s.node->rules.size()) { int& node_id = tree2hg[s.input_node_idx]; if (node_id < 0) node_id = hg.AddNode(-(input_tree.nodes[s.input_node_idx].lhs & cdec::ALL_MASK))->id_; TailNodeVector tail; for (auto n : s.future_work) { int& nix = tree2hg[n]; if (nix < 0) nix = hg.AddNode(-(input_tree.nodes[n].lhs & cdec::ALL_MASK))->id_; tail.push_back(nix); } for (auto& r : s.node->rules) { assert(tail.size() == r->Arity()); HG::Edge* new_edge = hg.AddEdge(r, tail); new_edge->feature_values_ = r->GetFeatureValues(); // TODO: set i and j hg.ConnectEdgeToHeadNode(new_edge, &hg.nodes_[node_id]); } for (auto n : s.future_work) { const auto it = input_tree.begin(n); // start tree iterator at node n for (auto& g : root) { ParserState s(it, g.get()); if (unique.insert(s).second) q.push(s); } } } else { //cerr << "I can't build anything :(\n"; } } else { // more input tree to match unsigned sym = *s.in_iter; if (cdec::IsLHS(sym)) { auto nit = s.node->next.find(sym); if (nit != s.node->next.end()) { //cerr << "MATCHED LHS: " << TD::Convert(sym & cdec::ALL_MASK) << endl; ParserState news(++s.in_iter, &nit->second, s); if (unique.insert(news).second) q.push(news); } } else if (cdec::IsRHS(sym)) { //cerr << "Attempting to match RHS: " << TD::Convert(sym & cdec::ALL_MASK) << endl; cdec::TreeFragment::iterator var = s.in_iter; var.truncate(); auto nit1 = s.node->next.find(sym); auto nit2 = s.node->next.find(*var); if (nit2 != s.node->next.end()) { //cerr << "MATCHED VAR RHS: " << TD::Convert(sym & cdec::ALL_MASK) << endl; ++var; const unsigned new_work = s.in_iter.child_node(); ParserState new_s(var, &nit2->second, s); new_s.future_work.push_back(new_work); // if this traversal of the input succeeds, future_work goes on the q if (unique.insert(new_s).second) q.push(new_s); } if (nit1 != s.node->next.end()) { //cerr << "MATCHED FULL RHS: " << TD::Convert(sym & cdec::ALL_MASK) << endl; const ParserState new_s(++s.in_iter, &nit1->second, s); if (unique.insert(new_s).second) q.push(new_s); } } else if (cdec::IsTerminal(sym)) { auto nit = s.node->next.find(sym); if (nit != s.node->next.end()) { //cerr << "MATCHED TERMINAL: " << TD::Convert(sym) << endl; const ParserState new_s(++s.in_iter, &nit->second, s); if (unique.insert(new_s).second) q.push(new_s); } } else { cerr << "This can never happen!\n"; abort(); } } q.pop(); } int goal = tree2hg[tree_top]; if (goal < 0) return false; //cerr << "Goal node: " << goal << endl; hg.TopologicallySortNodesAndEdges(goal); hg.Reweight(weights); // there might be nodes that cannot be derived // the following takes care of them vector<bool> prune(hg.edges_.size(), false); hg.PruneEdges(prune, true); //hg.PrintGraphviz(); minus_lm_forest->swap(hg); return true; } }; Tree2StringTranslator::Tree2StringTranslator(const boost::program_options::variables_map& conf) : pimpl_(new Tree2StringTranslatorImpl(conf)) {} bool Tree2StringTranslator::TranslateImpl(const string& input, SentenceMetadata* smeta, const vector<double>& weights, Hypergraph* minus_lm_forest) { return pimpl_->Translate(input, smeta, weights, minus_lm_forest); } void Tree2StringTranslator::ProcessMarkupHintsImpl(const map<string, string>& kv) { } void Tree2StringTranslator::SentenceCompleteImpl() { } std::string Tree2StringTranslator::GetDecoderType() const { return "tree2string"; } <|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetHLDReader.cpp * @brief The interface only mimics the JPetReader class */ #include "JPetHLDReader.h" #include <iostream> #include <cassert> JPetHLDReader::JPetHLDReader(): fBranch(0), fTree(0), fEvent(0), fFile(NULL), fCurrentEventNumber(-1) { /* */ } JPetHLDReader::JPetHLDReader (const char* filename): fBranch(0), fTree(0), fEvent(0), fFile(NULL), fCurrentEventNumber(-1) { if (!openFileAndLoadData(filename, "T")) { ERROR("error in opening file"); } } JPetHLDReader::~JPetHLDReader () { closeFile(); } EventIII& JPetHLDReader::getCurrentEvent() { if (loadCurrentEvent()) { fEventW = new WrappedEvent(*fEvent); return *fEventW; //return *fEvent; } else { ERROR("Could not read the current event"); if (fEvent) { delete fEvent; } fEvent = new EventIII(); } fEventW = new WrappedEvent(*fEvent); return *fEventW; } bool JPetHLDReader::nextEvent() { fCurrentEventNumber++; return loadCurrentEvent(); } bool JPetHLDReader::firstEvent() { fCurrentEventNumber = 0; return loadCurrentEvent(); } bool JPetHLDReader::lastEvent() { fCurrentEventNumber = getNbOfAllEvents() - 1; return loadCurrentEvent(); } bool JPetHLDReader::nthEvent(int n) { fCurrentEventNumber = n; return loadCurrentEvent(); } void JPetHLDReader::closeFile () { if (fFile != NULL) { if (fFile->IsOpen()) fFile->Close(); delete fFile; fFile = NULL; } fBranch = 0; fEvent = 0; fTree = 0; } bool JPetHLDReader::loadData(const char* treename) { if (!isOpen() ) { ERROR("File not open"); return false; } if (!treename) { ERROR("empty tree name"); return false; } fTree = static_cast<TTree*>(fFile->Get(treename)); if (!fTree) { ERROR("in reading tree"); return false; } fBranch = fTree->GetBranch("eventIII"); if (!fBranch) { ERROR("in reading branch from tree"); return false; } fBranch->SetAddress(&fEvent); firstEvent(); return true; } bool JPetHLDReader::openFile (const char* filename) { closeFile(); fFile = new TFile(filename); if ((!fFile->IsOpen()) || fFile->IsZombie()) { ERROR("Cannot open file."); closeFile(); return false; } return true; } <commit_msg>Add some missing constructor initialization in JPetHLDReader<commit_after>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetHLDReader.cpp * @brief The interface only mimics the JPetReader class */ #include "JPetHLDReader.h" #include <iostream> #include <cassert> JPetHLDReader::JPetHLDReader(): fBranch(0), fTree(0), fEvent(0), fEventW(0), fFile(NULL), fCurrentEventNumber(-1) { /* */ } JPetHLDReader::JPetHLDReader (const char* filename): fBranch(0), fTree(0), fEvent(0), fEventW(0), fFile(NULL), fCurrentEventNumber(-1) { if (!openFileAndLoadData(filename, "T")) { ERROR("error in opening file"); } } JPetHLDReader::~JPetHLDReader () { closeFile(); } EventIII& JPetHLDReader::getCurrentEvent() { if (loadCurrentEvent()) { fEventW = new WrappedEvent(*fEvent); return *fEventW; //return *fEvent; } else { ERROR("Could not read the current event"); if (fEvent) { delete fEvent; } fEvent = new EventIII(); } fEventW = new WrappedEvent(*fEvent); return *fEventW; } bool JPetHLDReader::nextEvent() { fCurrentEventNumber++; return loadCurrentEvent(); } bool JPetHLDReader::firstEvent() { fCurrentEventNumber = 0; return loadCurrentEvent(); } bool JPetHLDReader::lastEvent() { fCurrentEventNumber = getNbOfAllEvents() - 1; return loadCurrentEvent(); } bool JPetHLDReader::nthEvent(int n) { fCurrentEventNumber = n; return loadCurrentEvent(); } void JPetHLDReader::closeFile () { if (fFile != NULL) { if (fFile->IsOpen()) fFile->Close(); delete fFile; fFile = NULL; } fBranch = 0; fEvent = 0; fTree = 0; } bool JPetHLDReader::loadData(const char* treename) { if (!isOpen() ) { ERROR("File not open"); return false; } if (!treename) { ERROR("empty tree name"); return false; } fTree = static_cast<TTree*>(fFile->Get(treename)); if (!fTree) { ERROR("in reading tree"); return false; } fBranch = fTree->GetBranch("eventIII"); if (!fBranch) { ERROR("in reading branch from tree"); return false; } fBranch->SetAddress(&fEvent); firstEvent(); return true; } bool JPetHLDReader::openFile (const char* filename) { closeFile(); fFile = new TFile(filename); if ((!fFile->IsOpen()) || fFile->IsZombie()) { ERROR("Cannot open file."); closeFile(); return false; } return true; } <|endoftext|>
<commit_before>/* Catena_Mb85rc64ta.cpp Wed Dec 06 2017 15:33:28 chwon */ /* Module: Catena_Mb85rc64ta.cpp Function: Class for Catena_Mb85rc64ta. Version: V0.6.0 Wed Dec 06 2017 15:33:28 chwon Edit level 2 Copyright notice: This file copyright (C) 2017 by MCCI Corporation 3520 Krums Corners Road Ithaca, NY 14850 An unpublished work. All rights reserved. This file is proprietary information, and may not be disclosed or copied without the prior permission of MCCI Corporation. Author: ChaeHee Won, MCCI Corporation October 2017 Revision history: 0.6.0 Fri Oct 13 2017 15:19:30 chwon Module created. 0.6.0 Wed Dec 06 2017 15:33:28 chwon Add readId and power control. */ #include <stdlib.h> #include <math.h> #include "Catena_Mb85rc64ta.h" using namespace McciCatena; /****************************************************************************\ | | Manifest constants & typedefs. | | This is strictly for private types and constants which will not | be exported. | \****************************************************************************/ /****************************************************************************\ | | Read-only data. | | If program is to be ROM-able, these must all be tagged read-only | using the ROM storage class; they may be global. | \****************************************************************************/ /****************************************************************************\ | | VARIABLES: | | If program is to be ROM-able, these must be initialized | using the BSS keyword. (This allows for compilers that require | every variable to have an initializer.) Note that only those | variables owned by this module should be declared here, using the BSS | keyword; this allows for linkers that dislike multiple declarations | of objects. | \****************************************************************************/ /* || Constructors */ Catena_Mb85rc64ta::Catena_Mb85rc64ta(void) { this->m_Initialized = false; } void Catena_Mb85rc64ta::prepIO(void) const { /* this->m_pWire->setClock(1000000); */ } /* || Public functions */ /* Name: Catena_Mb85rc64ta::begin Function: Begin method Definition: bool Catena_Mb85rc64ta::begin( uint8_t DeviceAddress, TwoWire *pWire ); Description: This function initializes I2C and configures the chip. Returns: true if success */ bool Catena_Mb85rc64ta::begin( uint8_t DeviceAddress, TwoWire *pWire ) { uint8_t i; uint8_t uError; /* scrub and save the address */ if (DeviceAddress == 0) DeviceAddress = CATENA_MB85RC64TA_ADDRESS; this->m_DeviceAddress = DeviceAddress & ~0x7; this->m_pWire = pWire; pWire->begin(); /* Make sure we're actually connected */ this->prepIO(); for (i = 0; i < 8; ++this->m_DeviceAddress, ++i) { /* force to put stand-by mode, just in case */ this->m_PowerDown = true; this->powerUp(); pWire->beginTransmission(this->m_DeviceAddress); uError = pWire->endTransmission(); if (uError == 0) { break; } } if (i == 8) { // device didn't ack return false; } /* Everything seems to be properly initialised and connected */ this->m_Initialized = true; return true; } /* Name: Catena_Mb85rc64ta::write8 Function: Writes a byte at the specific FRAM address Definition: bool Catena_Mb85rc64ta::write8( uint16_t framAddr, uint8_t value ); Description: This function writes a byte at the specific FRAM address. Returns: True for success, false for error. */ bool Catena_Mb85rc64ta::write8( uint16_t framAddr, uint8_t value ) { this->prepIO(); this->m_pWire->beginTransmission(this->m_DeviceAddress); if (this->m_pWire->write(framAddr >> 8) == 1 && this->m_pWire->write(framAddr & 0xFF) == 1 && this->m_pWire->write(value) == 1 && this->m_pWire->endTransmission() == 0) return true; else return false; } /* Name: Catena_Mb85rc64ta::write Function: Writes a buffer to the specific FRAM address Definition: size+t Catena_Mb85rc64ta::write( uint16_t framAddr, const uint8_t *pBuffer, size_t nBuffer ); Description: This function writes a buffer to the specific FRAM address Returns: Number of bytes written, which must be either nBuffer for success or some number less than nBuffer for failure. */ size_t Catena_Mb85rc64ta::write( uint16_t framAddr, const uint8_t *pBuffer, size_t nBuffer ) { // There are numerous limitations on TwoWire buffer size. On 8-bit // Arduinos, the buffer size is limited to 32 bytes. On STM32 Arduinos, // the buffer size is not limited, but depends on malloc(), which is // not really reliable on systems with small memory. So... do this in // chunks. constexpr size_t nChunk = 32; const auto nOriginal = nBuffer; this->prepIO(); while (nBuffer != 0) { const auto nThis = nBuffer > nChunk ? nChunk : nBuffer; this->m_pWire->beginTransmission(this->m_DeviceAddress); if (this->m_pWire->write(framAddr >> 8) && this->m_pWire->write(framAddr & 0xFF) && this->m_pWire->write(pBuffer, nThis) == nThis && this->m_pWire->endTransmission() == 0) { nBuffer -= nThis; pBuffer += nThis; } else // error! break; } // return count of bytes written. return nOriginal - nBuffer; } /* Name: Catena_Mb85rc64ta::read8 Function: Reads an 8 bit value from the specified FRAM address Definition: uint8_t Catena_Mb85rc64ta::read8( uint16_t framAddr ); Description: This function reads an 8 bit value from the specified FRAM address. Returns: The 8-bit value retrieved at framAddr. */ uint8_t Catena_Mb85rc64ta::read8( uint16_t framAddr ) { this->prepIO(); this->m_pWire->beginTransmission(this->m_DeviceAddress); if (this->m_pWire->write(framAddr >> 8) && this->m_pWire->write(framAddr & 0xFF) && this->m_pWire->endTransmission() == 0 && this->m_pWire->requestFrom(this->m_DeviceAddress, (uint8_t)1) == 1) return this->m_pWire->read(); else // error! return 0; } /* Name: Catena_Mb85rc64ta::read() Function: Reads a buffer from the specified FRAM address Definition: size_t Catena_Mb85rc64ta::read( uint16_t framAddr, uint8_t *pBuffer, size_t nBuffer ); Description: This function reads a buffer from the specified FRAM address. Returns: The number of bytes retrieved at framAddr. */ size_t Catena_Mb85rc64ta::read( uint16_t framAddr, uint8_t *pBuffer, size_t nBuffer ) { // There are numerous limitations on TwoWire buffer size. On 8-bit // Arduinos, the buffer size is limited to 32 bytes. On STM32 Arduinos, // the buffer size is not limited, but depends on malloc(), which is // not really reliable on systems with small memory. So... do this in // chunks. constexpr size_t nChunk = 32; const auto save_nBuffer = nBuffer; this->prepIO(); while (nBuffer > 0) { const auto nThis = nBuffer > nChunk ? nChunk : nBuffer; uint8_t nRead; this->m_pWire->beginTransmission(this->m_DeviceAddress); if (this->m_pWire->write(framAddr >> 8) && this->m_pWire->write(framAddr & 0xFF) && this->m_pWire->endTransmission() == 0) { nRead = this->m_pWire->requestFrom( this->m_DeviceAddress, (uint8_t) nThis ); if (nRead != nThis) { // error break; } while (nBuffer > 0) { *pBuffer++ = this->m_pWire->read(); --nBuffer; } framAddr += nRead; } else // error break; } // return count of bytes read. return save_nBuffer - nBuffer; } /* Name: Catena_Mb85rc64ta::readId Function: Get the FRAM JEDEC IDs Definition: bool Catena_Mb85rc64ta::readId( uint16_t *pManufactureId, uint16_t *pProductId ); Description: This function reads a buffer from the specified FRAM address. Returns: true for success, false for failure. */ bool Catena_Mb85rc64ta::readId( uint16_t *pManufactureId, uint16_t *pProductId ) { uint8_t data; this->prepIO(); this->m_pWire->beginTransmission(CATENA_MB85RC64TA_SLAVE_ID); if (this->m_pWire->write(this->m_DeviceAddress << 1) && this->m_pWire->endTransmission() == 0) { data = this->m_pWire->requestFrom( CATENA_MB85RC64TA_SLAVE_ID, 3 ); } else data = 0; if (data != 3) { Serial.println("FRAM readId() failed"); *pManufactureId = 0; *pProductId = 0; return false; } else { data = this->m_pWire->read(); *pManufactureId = data << 4; data = this->m_pWire->read(); *pManufactureId |= data & 0x0Fu; data = this->m_pWire->read(); *pProductId = data & 0xF0u << 8; data = this->m_pWire->read(); *pProductId |= data; return true; } } /* Name: Catena_Mb85rc64ta::powerDown Function: Put low power mode Definition: void Catena_Mb85rc64ta::powerDown( void ); Description: This function puts low power mode of the FRAM. Returns: No explicit result. Notes: No error checking. */ void Catena_Mb85rc64ta::powerDown( void ) { if (! this->m_PowerDown) { this->prepIO(); this->m_pWire->beginTransmission(CATENA_MB85RC64TA_SLAVE_ID); this->m_pWire->write(this->m_DeviceAddress << 1); this->m_pWire->endTransmission(false); this->m_pWire->beginTransmission(0x86 >> 1); this->m_pWire->endTransmission(); this->m_PowerDown = true; } } /* Name: Catena_Mb85rc64ta::powerUp Function: Exit from low power mode Definition: void Catena_Mb85rc64ta::powerUp( void ); Description: This function exits from low power mode of the FRAM. Returns: No explicit result. */ void Catena_Mb85rc64ta::powerUp( void ) { if (this->m_PowerDown) { uint32_t uSec; this->m_pWire->beginTransmission(this->m_DeviceAddress); this->m_pWire->endTransmission(false); /* tREC == Max 400us */ uSec = micros(); this->m_PowerDown = false; while ((micros() - uSec) < 400); } } /**** end of Catena_Mb85rc64ta.cpp ****/ <commit_msg>fix to make 8k FRAM access more robust<commit_after>/* Catena_Mb85rc64ta.cpp Wed Dec 06 2017 15:33:28 chwon */ /* Module: Catena_Mb85rc64ta.cpp Function: Class for Catena_Mb85rc64ta. Version: V0.6.0 Wed Dec 06 2017 15:33:28 chwon Edit level 2 Copyright notice: This file copyright (C) 2017 by MCCI Corporation 3520 Krums Corners Road Ithaca, NY 14850 An unpublished work. All rights reserved. This file is proprietary information, and may not be disclosed or copied without the prior permission of MCCI Corporation. Author: ChaeHee Won, MCCI Corporation October 2017 Revision history: 0.6.0 Fri Oct 13 2017 15:19:30 chwon Module created. 0.6.0 Wed Dec 06 2017 15:33:28 chwon Add readId and power control. */ #include <stdlib.h> #include <math.h> #include "Catena_Mb85rc64ta.h" using namespace McciCatena; /****************************************************************************\ | | Manifest constants & typedefs. | | This is strictly for private types and constants which will not | be exported. | \****************************************************************************/ /****************************************************************************\ | | Read-only data. | | If program is to be ROM-able, these must all be tagged read-only | using the ROM storage class; they may be global. | \****************************************************************************/ /****************************************************************************\ | | VARIABLES: | | If program is to be ROM-able, these must be initialized | using the BSS keyword. (This allows for compilers that require | every variable to have an initializer.) Note that only those | variables owned by this module should be declared here, using the BSS | keyword; this allows for linkers that dislike multiple declarations | of objects. | \****************************************************************************/ /* || Constructors */ Catena_Mb85rc64ta::Catena_Mb85rc64ta(void) { this->m_Initialized = false; } void Catena_Mb85rc64ta::prepIO(void) const { /* this->m_pWire->setClock(1000000); */ } /* || Public functions */ /* Name: Catena_Mb85rc64ta::begin Function: Begin method Definition: bool Catena_Mb85rc64ta::begin( uint8_t DeviceAddress, TwoWire *pWire ); Description: This function initializes I2C and configures the chip. Returns: true if success */ bool Catena_Mb85rc64ta::begin( uint8_t DeviceAddress, TwoWire *pWire ) { uint8_t i; uint8_t uError; /* scrub and save the address */ if (DeviceAddress == 0) DeviceAddress = CATENA_MB85RC64TA_ADDRESS; this->m_DeviceAddress = DeviceAddress & ~0x7; this->m_pWire = pWire; pWire->begin(); /* Make sure we're actually connected */ this->prepIO(); for (i = 0; i < 8; ++this->m_DeviceAddress, ++i) { /* force to put stand-by mode, just in case */ this->m_PowerDown = true; this->powerUp(); pWire->beginTransmission(this->m_DeviceAddress); uError = pWire->endTransmission(); if (uError == 0) { break; } } if (i == 8) { // device didn't ack return false; } /* Everything seems to be properly initialised and connected */ this->m_Initialized = true; return true; } /* Name: Catena_Mb85rc64ta::write8 Function: Writes a byte at the specific FRAM address Definition: bool Catena_Mb85rc64ta::write8( uint16_t framAddr, uint8_t value ); Description: This function writes a byte at the specific FRAM address. Returns: True for success, false for error. */ bool Catena_Mb85rc64ta::write8( uint16_t framAddr, uint8_t value ) { this->prepIO(); this->m_pWire->beginTransmission(this->m_DeviceAddress); if (this->m_pWire->write(framAddr >> 8) == 1 && this->m_pWire->write(framAddr & 0xFF) == 1 && this->m_pWire->write(value) == 1 && this->m_pWire->endTransmission() == 0) return true; else return false; } /* Name: Catena_Mb85rc64ta::write Function: Writes a buffer to the specific FRAM address Definition: size+t Catena_Mb85rc64ta::write( uint16_t framAddr, const uint8_t *pBuffer, size_t nBuffer ); Description: This function writes a buffer to the specific FRAM address Returns: Number of bytes written, which must be either nBuffer for success or some number less than nBuffer for failure. */ size_t Catena_Mb85rc64ta::write( uint16_t framAddr, const uint8_t *pBuffer, size_t nBuffer ) { // There are numerous limitations on TwoWire buffer size. On 8-bit // Arduinos, the buffer size is limited to 32 bytes. On STM32 Arduinos, // the buffer size is not limited, but depends on malloc(), which is // not really reliable on systems with small memory. So... do this in // chunks. constexpr size_t nChunk = 32; const auto nOriginal = nBuffer; this->prepIO(); while (nBuffer != 0) { const auto nThis = nBuffer > nChunk ? nChunk : nBuffer; this->m_pWire->beginTransmission(this->m_DeviceAddress); if (this->m_pWire->write(framAddr >> 8) && this->m_pWire->write(framAddr & 0xFF) && this->m_pWire->write(pBuffer, nThis) == nThis && this->m_pWire->endTransmission() == 0) { nBuffer -= nThis; pBuffer += nThis; framAddr += nThis; } else // error! break; } // return count of bytes written. return nOriginal - nBuffer; } /* Name: Catena_Mb85rc64ta::read8 Function: Reads an 8 bit value from the specified FRAM address Definition: uint8_t Catena_Mb85rc64ta::read8( uint16_t framAddr ); Description: This function reads an 8 bit value from the specified FRAM address. Returns: The 8-bit value retrieved at framAddr. */ uint8_t Catena_Mb85rc64ta::read8( uint16_t framAddr ) { this->prepIO(); this->m_pWire->beginTransmission(this->m_DeviceAddress); if (this->m_pWire->write(framAddr >> 8) && this->m_pWire->write(framAddr & 0xFF) && this->m_pWire->endTransmission() == 0 && this->m_pWire->requestFrom(this->m_DeviceAddress, (uint8_t)1) == 1) return this->m_pWire->read(); else // error! return 0; } /* Name: Catena_Mb85rc64ta::read() Function: Reads a buffer from the specified FRAM address Definition: size_t Catena_Mb85rc64ta::read( uint16_t framAddr, uint8_t *pBuffer, size_t nBuffer ); Description: This function reads a buffer from the specified FRAM address. Returns: The number of bytes retrieved at framAddr. */ size_t Catena_Mb85rc64ta::read( uint16_t framAddr, uint8_t *pBuffer, size_t nBuffer ) { // There are numerous limitations on TwoWire buffer size. On 8-bit // Arduinos, the buffer size is limited to 32 bytes. On STM32 Arduinos, // the buffer size is not limited, but depends on malloc(), which is // not really reliable on systems with small memory. So... do this in // chunks. constexpr size_t nChunk = 32; const auto save_nBuffer = nBuffer; this->prepIO(); while (nBuffer > 0) { const auto nThis = nBuffer > nChunk ? nChunk : nBuffer; uint8_t nRead; this->m_pWire->beginTransmission(this->m_DeviceAddress); if (this->m_pWire->write(framAddr >> 8) && this->m_pWire->write(framAddr & 0xFF) && this->m_pWire->endTransmission() == 0) { nRead = this->m_pWire->requestFrom( this->m_DeviceAddress, (uint8_t) nThis ); if (nRead != nThis) { // error break; } while (nRead > 0) { *pBuffer++ = this->m_pWire->read(); --nBuffer; --nRead; } framAddr += nThis; } else // error break; } // return count of bytes read. return save_nBuffer - nBuffer; } /* Name: Catena_Mb85rc64ta::readId Function: Get the FRAM JEDEC IDs Definition: bool Catena_Mb85rc64ta::readId( uint16_t *pManufactureId, uint16_t *pProductId ); Description: This function reads a buffer from the specified FRAM address. Returns: true for success, false for failure. */ bool Catena_Mb85rc64ta::readId( uint16_t *pManufactureId, uint16_t *pProductId ) { uint8_t data; this->prepIO(); this->m_pWire->beginTransmission(CATENA_MB85RC64TA_SLAVE_ID); if (this->m_pWire->write(this->m_DeviceAddress << 1) && this->m_pWire->endTransmission() == 0) { data = this->m_pWire->requestFrom( CATENA_MB85RC64TA_SLAVE_ID, 3 ); } else data = 0; if (data != 3) { Serial.println("FRAM readId() failed"); *pManufactureId = 0; *pProductId = 0; return false; } else { data = this->m_pWire->read(); *pManufactureId = data << 4; data = this->m_pWire->read(); *pManufactureId |= data & 0x0Fu; data = this->m_pWire->read(); *pProductId = data & 0xF0u << 8; data = this->m_pWire->read(); *pProductId |= data; return true; } } /* Name: Catena_Mb85rc64ta::powerDown Function: Put low power mode Definition: void Catena_Mb85rc64ta::powerDown( void ); Description: This function puts low power mode of the FRAM. Returns: No explicit result. Notes: No error checking. */ void Catena_Mb85rc64ta::powerDown( void ) { if (! this->m_PowerDown) { this->prepIO(); this->m_pWire->beginTransmission(CATENA_MB85RC64TA_SLAVE_ID); this->m_pWire->write(this->m_DeviceAddress << 1); this->m_pWire->endTransmission(false); this->m_pWire->beginTransmission(0x86 >> 1); this->m_pWire->endTransmission(); this->m_PowerDown = true; } } /* Name: Catena_Mb85rc64ta::powerUp Function: Exit from low power mode Definition: void Catena_Mb85rc64ta::powerUp( void ); Description: This function exits from low power mode of the FRAM. Returns: No explicit result. */ void Catena_Mb85rc64ta::powerUp( void ) { if (this->m_PowerDown) { uint32_t uSec; this->m_pWire->beginTransmission(this->m_DeviceAddress); this->m_pWire->endTransmission(false); /* tREC == Max 400us */ uSec = micros(); this->m_PowerDown = false; while ((micros() - uSec) < 400); } } /**** end of Catena_Mb85rc64ta.cpp ****/ <|endoftext|>
<commit_before>/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Orion dev team */ #include "common/JsonHelper.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <iomanip> /* **************************************************************************** * * toJsonString - */ std::string toJsonString(const std::string& input) { std::ostringstream ss; ss << '"'; for (std::string::const_iterator iter = input.begin(); iter != input.end(); ++iter) { /* FIXME P3: This function ensures that if the DB holds special characters (which are * not supported in JSON according to its specification), they are converted to their escaped * representations. The process wouldn't be necessary if the DB couldn't hold such special characters, * but as long as we support NGSIv1, it is better to have the check (e.g. a newline could be * used in an attribute value using XML). Even removing NGSIv1, we have to ensure that the * input parser (rapidjson) doesn't inject not supported JSON characters in the DB (this needs to be * investigated in the rapidjson documentation) */ switch (char ch = *iter) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '/': ss << "\\/"; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; default: /* Converting the rest of special chars 0-31 to \u00xx. Note that 0x80 - 0xFF are untouched as they * correspond to UTF-8 multi-byte characters */ if (ch >= 0 && ch <= 0x1F) { static const char intToHex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' } ; ss << "\\u00" << intToHex[(ch & 0xF0) >> 4] << intToHex[ch & 0x0F]; } else { ss << ch; } break; } //end-switch } //end-for ss << '"'; return ss.str(); } /* **************************************************************************** * * vectorToJson - */ template <> std::string vectorToJson(std::vector<std::string> &list) { switch (list.size()) { case 0: return "[]"; case 1: return "[ " + toJsonString(list[0]) + " ]"; default: std::ostringstream os; os << '['; os << toJsonString(list[0]); for (std::vector<std::string>::size_type i = 1; i != list.size(); ++i) { os << ',' << toJsonString(list[i]); } os << ']'; return os.str(); } } /* **************************************************************************** * * JsonHelper - */ JsonHelper::JsonHelper(): empty(true) { ss << std::fixed << std::setprecision(9); ss << '{'; } /* **************************************************************************** * * JsonHelper::addString - */ void JsonHelper::addString(const std::string& key, const std::string& value) { if (!empty) { ss << ','; } ss << toJsonString(key) << ':' << toJsonString(value); empty = false; } /* **************************************************************************** * * JsonHelper::addRaw - */ void JsonHelper::addRaw(const std::string& key, const std::string& value) { if (!empty) { ss << ','; } ss << toJsonString(key) << ':' << value; empty = false; } /* **************************************************************************** * * JsonHelper::addNumber - */ void JsonHelper::addNumber(const std::string& key, long long value) { if (!empty) { ss << ','; } ss << toJsonString(key) << ':' << value; empty = false; } /* **************************************************************************** * * JsonHelper::addFloat - */ void JsonHelper::addFloat(const std::string& key, float value) { if (!empty) { ss << ','; } ss << toJsonString(key) << ':' << std::fixed << std::setprecision(9) << value; empty = false; } /* **************************************************************************** * * JsonHelper::addDate - */ void JsonHelper::addDate(const std::string& key, long long timestamp) { if (!empty) { ss << ','; } // 80 bytes are large enough to store any ISO8601 string safely // We use gmtime() to get UTC strings, otherwise we would use localtime() // Date pattern: 1970-04-26T17:46:40.00Z char buffer[80]; time_t rawtime = (time_t) timestamp; strftime(buffer, sizeof(buffer),"%Y-%m-%dT%H:%M:%S.00Z", gmtime(&rawtime)); ss << toJsonString(key) << ':' << toJsonString(std::string(buffer)); empty = false; } /* **************************************************************************** * * JsonHelper::str - */ std::string JsonHelper::str() { ss << '}'; return ss.str(); } <commit_msg>FIX fix float format at JsonHelper rendering<commit_after>/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Orion dev team */ #include "common/JsonHelper.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <iomanip> /* **************************************************************************** * * toJsonString - */ std::string toJsonString(const std::string& input) { std::ostringstream ss; ss << '"'; for (std::string::const_iterator iter = input.begin(); iter != input.end(); ++iter) { /* FIXME P3: This function ensures that if the DB holds special characters (which are * not supported in JSON according to its specification), they are converted to their escaped * representations. The process wouldn't be necessary if the DB couldn't hold such special characters, * but as long as we support NGSIv1, it is better to have the check (e.g. a newline could be * used in an attribute value using XML). Even removing NGSIv1, we have to ensure that the * input parser (rapidjson) doesn't inject not supported JSON characters in the DB (this needs to be * investigated in the rapidjson documentation) */ switch (char ch = *iter) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '/': ss << "\\/"; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; default: /* Converting the rest of special chars 0-31 to \u00xx. Note that 0x80 - 0xFF are untouched as they * correspond to UTF-8 multi-byte characters */ if (ch >= 0 && ch <= 0x1F) { static const char intToHex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' } ; ss << "\\u00" << intToHex[(ch & 0xF0) >> 4] << intToHex[ch & 0x0F]; } else { ss << ch; } break; } //end-switch } //end-for ss << '"'; return ss.str(); } /* **************************************************************************** * * vectorToJson - */ template <> std::string vectorToJson(std::vector<std::string> &list) { switch (list.size()) { case 0: return "[]"; case 1: return "[ " + toJsonString(list[0]) + " ]"; default: std::ostringstream os; os << '['; os << toJsonString(list[0]); for (std::vector<std::string>::size_type i = 1; i != list.size(); ++i) { os << ',' << toJsonString(list[i]); } os << ']'; return os.str(); } } /* **************************************************************************** * * JsonHelper - */ JsonHelper::JsonHelper(): empty(true) { /* Set format for floats (it doesn't affect integers) */ ss << std::fixed << std::setprecision(9); ss << '{'; } /* **************************************************************************** * * JsonHelper::addString - */ void JsonHelper::addString(const std::string& key, const std::string& value) { if (!empty) { ss << ','; } ss << toJsonString(key) << ':' << toJsonString(value); empty = false; } /* **************************************************************************** * * JsonHelper::addRaw - */ void JsonHelper::addRaw(const std::string& key, const std::string& value) { if (!empty) { ss << ','; } ss << toJsonString(key) << ':' << value; empty = false; } /* **************************************************************************** * * JsonHelper::addNumber - */ void JsonHelper::addNumber(const std::string& key, long long value) { if (!empty) { ss << ','; } ss << toJsonString(key) << ':' << value; empty = false; } /* **************************************************************************** * * JsonHelper::addFloat - */ void JsonHelper::addFloat(const std::string& key, float value) { if (!empty) { ss << ','; } ss << toJsonString(key) << ':' << value; empty = false; } /* **************************************************************************** * * JsonHelper::addDate - */ void JsonHelper::addDate(const std::string& key, long long timestamp) { if (!empty) { ss << ','; } // 80 bytes are large enough to store any ISO8601 string safely // We use gmtime() to get UTC strings, otherwise we would use localtime() // Date pattern: 1970-04-26T17:46:40.00Z char buffer[80]; time_t rawtime = (time_t) timestamp; strftime(buffer, sizeof(buffer),"%Y-%m-%dT%H:%M:%S.00Z", gmtime(&rawtime)); ss << toJsonString(key) << ':' << toJsonString(std::string(buffer)); empty = false; } /* **************************************************************************** * * JsonHelper::str - */ std::string JsonHelper::str() { ss << '}'; return ss.str(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/ffmpeg_audio_decoder.h" #include "media/base/callback.h" #include "media/base/data_buffer.h" #include "media/base/limits.h" #include "media/ffmpeg/ffmpeg_common.h" #include "media/filters/ffmpeg_demuxer.h" #if !defined(USE_SSE) #if defined(__SSE__) || defined(ARCH_CPU_X86_64) || _M_IX86_FP==1 #define USE_SSE 1 #else #define USE_SSE 0 #endif #endif #if USE_SSE #include <xmmintrin.h> #endif namespace media { // Size of the decoded audio buffer. const size_t FFmpegAudioDecoder::kOutputBufferSize = AVCODEC_MAX_AUDIO_FRAME_SIZE; FFmpegAudioDecoder::FFmpegAudioDecoder() : codec_context_(NULL), estimated_next_timestamp_(StreamSample::kInvalidTimestamp) { } FFmpegAudioDecoder::~FFmpegAudioDecoder() { } // static bool FFmpegAudioDecoder::IsMediaFormatSupported(const MediaFormat& format) { std::string mime_type; return format.GetAsString(MediaFormat::kMimeType, &mime_type) && mime_type::kFFmpegAudio == mime_type; } void FFmpegAudioDecoder::DoInitialize(DemuxerStream* demuxer_stream, bool* success, Task* done_cb) { AutoTaskRunner done_runner(done_cb); *success = false; // Get the AVStream by querying for the provider interface. AVStreamProvider* av_stream_provider; if (!demuxer_stream->QueryInterface(&av_stream_provider)) { return; } AVStream* av_stream = av_stream_provider->GetAVStream(); // Grab the AVStream's codec context and make sure we have sensible values. codec_context_ = av_stream->codec; int bps = av_get_bits_per_sample_format(codec_context_->sample_fmt); DCHECK_GT(codec_context_->channels, 0); DCHECK_GT(bps, 0); DCHECK_GT(codec_context_->sample_rate, 0); if (codec_context_->channels <= 0 || codec_context_->channels > Limits::kMaxChannels || bps <= 0 || bps > Limits::kMaxBitsPerSample || codec_context_->sample_rate <= 0 || codec_context_->sample_rate > Limits::kMaxSampleRate) { return; } // Serialize calls to avcodec_open(). AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); if (!codec || avcodec_open(codec_context_, codec) < 0) { return; } // When calling avcodec_find_decoder(), |codec_context_| might be altered by // the decoder to give more accurate values of the output format of the // decoder. So set the media format after a decoder is allocated. // TODO(hclam): Reuse the information provided by the demuxer for now, we may // need to wait until the first buffer is decoded to know the correct // information. media_format_.SetAsInteger(MediaFormat::kChannels, codec_context_->channels); media_format_.SetAsInteger(MediaFormat::kSampleBits, av_get_bits_per_sample_format(codec_context_->sample_fmt)); media_format_.SetAsInteger(MediaFormat::kSampleRate, codec_context_->sample_rate); media_format_.SetAsString(MediaFormat::kMimeType, mime_type::kUncompressedAudio); // Prepare the output buffer. output_buffer_.reset(static_cast<uint8*>(av_malloc(kOutputBufferSize))); if (!output_buffer_.get()) { host()->SetError(PIPELINE_ERROR_OUT_OF_MEMORY); return; } *success = true; } void FFmpegAudioDecoder::DoSeek(base::TimeDelta time, Task* done_cb) { avcodec_flush_buffers(codec_context_); estimated_next_timestamp_ = StreamSample::kInvalidTimestamp; done_cb->Run(); delete done_cb; } // ConvertAudioF32ToS32() converts float audio (F32) to int (S32) in place. // This is a temporary solution. // The purpose of this short term fix is to enable WMApro, which decodes to // float. // The audio driver has been tested by passing the float audio thru. // FFmpeg for ChromeOS only exposes U8, S16 and F32. // To properly expose new audio sample types at the audio driver layer, a enum // should be created to represent all suppported types, including types // for Pepper. FFmpeg should be queried for type and passed along. // TODO(fbarchard): Remove this function. Expose all FFmpeg types to driver. // TODO(fbarchard): If this function is kept, move it to audio_util.cc #if USE_SSE const __m128 kFloatScaler = _mm_set1_ps( 2147483648.0f ); static void FloatToIntSaturate(float* p) { __m128 a = _mm_set1_ps(*p); a = _mm_mul_ss(a, kFloatScaler); *reinterpret_cast<int32*>(p) = _mm_cvtss_si32(a); } #else const float kFloatScaler = 2147483648.0f; const int kMinSample = std::numeric_limits<int32>::min(); const int kMaxSample = std::numeric_limits<int32>::max(); const float kMinSampleFloat = static_cast<float>(std::numeric_limits<int32>::min()); const float kMaxSampleFloat = static_cast<float>(std::numeric_limits<int32>::max()); static void FloatToIntSaturate(float* p) { float f = *p * kFloatScaler + 0.5f; int sample; if (f <= kMinSampleFloat) { sample = kMinSample; } else if (f >= kMaxSampleFloat) { sample = kMaxSample; } else { sample = static_cast<int32>(f); } *reinterpret_cast<int32*>(p) = sample; } #endif static void ConvertAudioF32ToS32(void* buffer, int buffer_size) { for (int i = 0; i < buffer_size / 4; ++i) { FloatToIntSaturate(reinterpret_cast<float*>(buffer) + i); } } void FFmpegAudioDecoder::DoDecode(Buffer* input) { // FFmpeg tends to seek Ogg audio streams in the middle of nowhere, giving us // a whole bunch of AV_NOPTS_VALUE packets. Discard them until we find // something valid. Refer to http://crbug.com/49709 // TODO(hclam): remove this once fixing the issue in FFmpeg. if (input->GetTimestamp() == StreamSample::kInvalidTimestamp && estimated_next_timestamp_ == StreamSample::kInvalidTimestamp && !input->IsEndOfStream()) { DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); return; } // Due to FFmpeg API changes we no longer have const read-only pointers. AVPacket packet; av_init_packet(&packet); packet.data = const_cast<uint8*>(input->GetData()); packet.size = input->GetDataSize(); int16_t* output_buffer = reinterpret_cast<int16_t*>(output_buffer_.get()); int output_buffer_size = kOutputBufferSize; int result = avcodec_decode_audio3(codec_context_, output_buffer, &output_buffer_size, &packet); if (codec_context_->sample_fmt == SAMPLE_FMT_FLT) { ConvertAudioF32ToS32(output_buffer, output_buffer_size); } // TODO(ajwong): Consider if kOutputBufferSize should just be an int instead // of a size_t. if (result < 0 || output_buffer_size < 0 || static_cast<size_t>(output_buffer_size) > kOutputBufferSize) { VLOG(1) << "Error decoding an audio frame with timestamp: " << input->GetTimestamp().InMicroseconds() << " us, duration: " << input->GetDuration().InMicroseconds() << " us, packet size: " << input->GetDataSize() << " bytes"; DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); return; } // If we have decoded something, enqueue the result. if (output_buffer_size) { DataBuffer* result_buffer = new DataBuffer(output_buffer_size); result_buffer->SetDataSize(output_buffer_size); uint8* data = result_buffer->GetWritableData(); memcpy(data, output_buffer, output_buffer_size); // We don't trust the demuxer, so always calculate the duration based on // the actual number of samples decoded. base::TimeDelta duration = CalculateDuration(output_buffer_size); result_buffer->SetDuration(duration); // Use an estimated timestamp unless the incoming buffer has a valid one. if (input->GetTimestamp() == StreamSample::kInvalidTimestamp) { result_buffer->SetTimestamp(estimated_next_timestamp_); // Keep the estimated timestamp invalid until we get an incoming buffer // with a valid timestamp. This can happen during seeks, etc... if (estimated_next_timestamp_ != StreamSample::kInvalidTimestamp) { estimated_next_timestamp_ += duration; } } else { result_buffer->SetTimestamp(input->GetTimestamp()); estimated_next_timestamp_ = input->GetTimestamp() + duration; } EnqueueResult(result_buffer); DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); return; } // We can get a positive result but no decoded data. This is ok because this // this can be a marker packet that only contains timestamp. In this case we // save the timestamp for later use. if (result && !input->IsEndOfStream() && input->GetTimestamp() != StreamSample::kInvalidTimestamp && input->GetDuration() != StreamSample::kInvalidTimestamp) { estimated_next_timestamp_ = input->GetTimestamp() + input->GetDuration(); DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); return; } // Three conditions to meet to declare end of stream for this decoder: // 1. FFmpeg didn't read anything. // 2. FFmpeg didn't output anything. // 3. An end of stream buffer is received. if (result == 0 && output_buffer_size == 0 && input->IsEndOfStream()) { DataBuffer* result_buffer = new DataBuffer(0); result_buffer->SetTimestamp(input->GetTimestamp()); result_buffer->SetDuration(input->GetDuration()); EnqueueResult(result_buffer); } DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); } base::TimeDelta FFmpegAudioDecoder::CalculateDuration(size_t size) { int64 denominator = codec_context_->channels * av_get_bits_per_sample_format(codec_context_->sample_fmt) / 8 * codec_context_->sample_rate; double microseconds = size / (denominator / static_cast<double>(base::Time::kMicrosecondsPerSecond)); return base::TimeDelta::FromMicroseconds(static_cast<int64>(microseconds)); } } // namespace <commit_msg>Fixed bug 57194 by removing the DCHECKs and replacing them with a DLOG in the error case. The DCHECK cases are already handled and can occur because FFmpeg does not return an error when it encounters them.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/ffmpeg_audio_decoder.h" #include "media/base/callback.h" #include "media/base/data_buffer.h" #include "media/base/limits.h" #include "media/ffmpeg/ffmpeg_common.h" #include "media/filters/ffmpeg_demuxer.h" #if !defined(USE_SSE) #if defined(__SSE__) || defined(ARCH_CPU_X86_64) || _M_IX86_FP==1 #define USE_SSE 1 #else #define USE_SSE 0 #endif #endif #if USE_SSE #include <xmmintrin.h> #endif namespace media { // Size of the decoded audio buffer. const size_t FFmpegAudioDecoder::kOutputBufferSize = AVCODEC_MAX_AUDIO_FRAME_SIZE; FFmpegAudioDecoder::FFmpegAudioDecoder() : codec_context_(NULL), estimated_next_timestamp_(StreamSample::kInvalidTimestamp) { } FFmpegAudioDecoder::~FFmpegAudioDecoder() { } // static bool FFmpegAudioDecoder::IsMediaFormatSupported(const MediaFormat& format) { std::string mime_type; return format.GetAsString(MediaFormat::kMimeType, &mime_type) && mime_type::kFFmpegAudio == mime_type; } void FFmpegAudioDecoder::DoInitialize(DemuxerStream* demuxer_stream, bool* success, Task* done_cb) { AutoTaskRunner done_runner(done_cb); *success = false; // Get the AVStream by querying for the provider interface. AVStreamProvider* av_stream_provider; if (!demuxer_stream->QueryInterface(&av_stream_provider)) { return; } AVStream* av_stream = av_stream_provider->GetAVStream(); // Grab the AVStream's codec context and make sure we have sensible values. codec_context_ = av_stream->codec; int bps = av_get_bits_per_sample_format(codec_context_->sample_fmt); if (codec_context_->channels <= 0 || codec_context_->channels > Limits::kMaxChannels || bps <= 0 || bps > Limits::kMaxBitsPerSample || codec_context_->sample_rate <= 0 || codec_context_->sample_rate > Limits::kMaxSampleRate) { DLOG(WARNING) << "Invalid audio stream -" << " channels: " << codec_context_->channels << " bps: " << bps << " sample rate: " << codec_context_->sample_rate; return; } // Serialize calls to avcodec_open(). AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); if (!codec || avcodec_open(codec_context_, codec) < 0) { return; } // When calling avcodec_find_decoder(), |codec_context_| might be altered by // the decoder to give more accurate values of the output format of the // decoder. So set the media format after a decoder is allocated. // TODO(hclam): Reuse the information provided by the demuxer for now, we may // need to wait until the first buffer is decoded to know the correct // information. media_format_.SetAsInteger(MediaFormat::kChannels, codec_context_->channels); media_format_.SetAsInteger(MediaFormat::kSampleBits, av_get_bits_per_sample_format(codec_context_->sample_fmt)); media_format_.SetAsInteger(MediaFormat::kSampleRate, codec_context_->sample_rate); media_format_.SetAsString(MediaFormat::kMimeType, mime_type::kUncompressedAudio); // Prepare the output buffer. output_buffer_.reset(static_cast<uint8*>(av_malloc(kOutputBufferSize))); if (!output_buffer_.get()) { host()->SetError(PIPELINE_ERROR_OUT_OF_MEMORY); return; } *success = true; } void FFmpegAudioDecoder::DoSeek(base::TimeDelta time, Task* done_cb) { avcodec_flush_buffers(codec_context_); estimated_next_timestamp_ = StreamSample::kInvalidTimestamp; done_cb->Run(); delete done_cb; } // ConvertAudioF32ToS32() converts float audio (F32) to int (S32) in place. // This is a temporary solution. // The purpose of this short term fix is to enable WMApro, which decodes to // float. // The audio driver has been tested by passing the float audio thru. // FFmpeg for ChromeOS only exposes U8, S16 and F32. // To properly expose new audio sample types at the audio driver layer, a enum // should be created to represent all suppported types, including types // for Pepper. FFmpeg should be queried for type and passed along. // TODO(fbarchard): Remove this function. Expose all FFmpeg types to driver. // TODO(fbarchard): If this function is kept, move it to audio_util.cc #if USE_SSE const __m128 kFloatScaler = _mm_set1_ps( 2147483648.0f ); static void FloatToIntSaturate(float* p) { __m128 a = _mm_set1_ps(*p); a = _mm_mul_ss(a, kFloatScaler); *reinterpret_cast<int32*>(p) = _mm_cvtss_si32(a); } #else const float kFloatScaler = 2147483648.0f; const int kMinSample = std::numeric_limits<int32>::min(); const int kMaxSample = std::numeric_limits<int32>::max(); const float kMinSampleFloat = static_cast<float>(std::numeric_limits<int32>::min()); const float kMaxSampleFloat = static_cast<float>(std::numeric_limits<int32>::max()); static void FloatToIntSaturate(float* p) { float f = *p * kFloatScaler + 0.5f; int sample; if (f <= kMinSampleFloat) { sample = kMinSample; } else if (f >= kMaxSampleFloat) { sample = kMaxSample; } else { sample = static_cast<int32>(f); } *reinterpret_cast<int32*>(p) = sample; } #endif static void ConvertAudioF32ToS32(void* buffer, int buffer_size) { for (int i = 0; i < buffer_size / 4; ++i) { FloatToIntSaturate(reinterpret_cast<float*>(buffer) + i); } } void FFmpegAudioDecoder::DoDecode(Buffer* input) { // FFmpeg tends to seek Ogg audio streams in the middle of nowhere, giving us // a whole bunch of AV_NOPTS_VALUE packets. Discard them until we find // something valid. Refer to http://crbug.com/49709 // TODO(hclam): remove this once fixing the issue in FFmpeg. if (input->GetTimestamp() == StreamSample::kInvalidTimestamp && estimated_next_timestamp_ == StreamSample::kInvalidTimestamp && !input->IsEndOfStream()) { DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); return; } // Due to FFmpeg API changes we no longer have const read-only pointers. AVPacket packet; av_init_packet(&packet); packet.data = const_cast<uint8*>(input->GetData()); packet.size = input->GetDataSize(); int16_t* output_buffer = reinterpret_cast<int16_t*>(output_buffer_.get()); int output_buffer_size = kOutputBufferSize; int result = avcodec_decode_audio3(codec_context_, output_buffer, &output_buffer_size, &packet); if (codec_context_->sample_fmt == SAMPLE_FMT_FLT) { ConvertAudioF32ToS32(output_buffer, output_buffer_size); } // TODO(ajwong): Consider if kOutputBufferSize should just be an int instead // of a size_t. if (result < 0 || output_buffer_size < 0 || static_cast<size_t>(output_buffer_size) > kOutputBufferSize) { VLOG(1) << "Error decoding an audio frame with timestamp: " << input->GetTimestamp().InMicroseconds() << " us, duration: " << input->GetDuration().InMicroseconds() << " us, packet size: " << input->GetDataSize() << " bytes"; DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); return; } // If we have decoded something, enqueue the result. if (output_buffer_size) { DataBuffer* result_buffer = new DataBuffer(output_buffer_size); result_buffer->SetDataSize(output_buffer_size); uint8* data = result_buffer->GetWritableData(); memcpy(data, output_buffer, output_buffer_size); // We don't trust the demuxer, so always calculate the duration based on // the actual number of samples decoded. base::TimeDelta duration = CalculateDuration(output_buffer_size); result_buffer->SetDuration(duration); // Use an estimated timestamp unless the incoming buffer has a valid one. if (input->GetTimestamp() == StreamSample::kInvalidTimestamp) { result_buffer->SetTimestamp(estimated_next_timestamp_); // Keep the estimated timestamp invalid until we get an incoming buffer // with a valid timestamp. This can happen during seeks, etc... if (estimated_next_timestamp_ != StreamSample::kInvalidTimestamp) { estimated_next_timestamp_ += duration; } } else { result_buffer->SetTimestamp(input->GetTimestamp()); estimated_next_timestamp_ = input->GetTimestamp() + duration; } EnqueueResult(result_buffer); DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); return; } // We can get a positive result but no decoded data. This is ok because this // this can be a marker packet that only contains timestamp. In this case we // save the timestamp for later use. if (result && !input->IsEndOfStream() && input->GetTimestamp() != StreamSample::kInvalidTimestamp && input->GetDuration() != StreamSample::kInvalidTimestamp) { estimated_next_timestamp_ = input->GetTimestamp() + input->GetDuration(); DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); return; } // Three conditions to meet to declare end of stream for this decoder: // 1. FFmpeg didn't read anything. // 2. FFmpeg didn't output anything. // 3. An end of stream buffer is received. if (result == 0 && output_buffer_size == 0 && input->IsEndOfStream()) { DataBuffer* result_buffer = new DataBuffer(0); result_buffer->SetTimestamp(input->GetTimestamp()); result_buffer->SetDuration(input->GetDuration()); EnqueueResult(result_buffer); } DecoderBase<AudioDecoder, Buffer>::OnDecodeComplete(); } base::TimeDelta FFmpegAudioDecoder::CalculateDuration(size_t size) { int64 denominator = codec_context_->channels * av_get_bits_per_sample_format(codec_context_->sample_fmt) / 8 * codec_context_->sample_rate; double microseconds = size / (denominator / static_cast<double>(base::Time::kMicrosecondsPerSecond)); return base::TimeDelta::FromMicroseconds(static_cast<int64>(microseconds)); } } // namespace <|endoftext|>
<commit_before>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2011 Sandro Santilli <strk@kbt.io * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: operation/union/UnaryUnionOp.java r320 (JTS-1.12) * **********************************************************************/ #include <memory> // for unique_ptr #include <cassert> // for assert #include <algorithm> // for copy #include <geos/operation/union/UnaryUnionOp.h> #include <geos/operation/union/CascadedUnion.h> #include <geos/operation/union/CascadedPolygonUnion.h> #include <geos/operation/union/PointGeometryUnion.h> #include <geos/geom/Coordinate.h> #include <geos/geom/Point.h> #include <geos/geom/MultiPoint.h> #include <geos/geom/MultiLineString.h> #include <geos/geom/MultiPolygon.h> #include <geos/geom/GeometryCollection.h> #include <geos/geom/Geometry.h> #include <geos/geom/Location.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/util/GeometryCombiner.h> #include <geos/algorithm/PointLocator.h> namespace geos { namespace operation { // geos::operation namespace geounion { // geos::operation::geounion /*private*/ std::unique_ptr<geom::Geometry> UnaryUnionOp::unionWithNull(std::unique_ptr<geom::Geometry> g0, std::unique_ptr<geom::Geometry> g1) { std::unique_ptr<geom::Geometry> ret; if((! g0.get()) && (! g1.get())) { return ret; } if(! g0.get()) { return g1; } if(! g1.get()) { return g0; } ret = g0->Union(g1.get()); return ret; } /*public*/ std::unique_ptr<geom::Geometry> UnaryUnionOp::Union() { typedef std::unique_ptr<geom::Geometry> GeomPtr; GeomPtr ret; if(! geomFact) { return ret; } /** * For points and lines, only a single union operation is * required, since the OGC model allowings self-intersecting * MultiPoint and MultiLineStrings. * This is not the case for polygons, so Cascaded Union is required. */ GeomPtr unionPoints; if(!points.empty()) { GeomPtr ptGeom = geomFact->buildGeometry(points.begin(), points.end()); unionPoints = unionNoOpt(*ptGeom); } GeomPtr unionLines; if(!lines.empty()) { /* JTS compatibility NOTE: * we use cascaded here for robustness [1] * but also add a final unionNoOpt step to deal with * self-intersecting lines [2] * * [1](http://trac.osgeo.org/geos/ticket/392 * [2](http://trac.osgeo.org/geos/ticket/482 * */ unionLines.reset(CascadedUnion::Union(lines.begin(), lines.end())); if(unionLines.get()) { unionLines = unionNoOpt(*unionLines); } } GeomPtr unionPolygons; if(!polygons.empty()) { unionPolygons.reset(CascadedPolygonUnion::Union(polygons.begin(), polygons.end())); } /** * Performing two unions is somewhat inefficient, * but is mitigated by unioning lines and points first */ GeomPtr unionLA = unionWithNull(std::move(unionLines), std::move(unionPolygons)); assert(!unionLines.get()); assert(!unionPolygons.get()); if(! unionPoints.get()) { ret = std::move(unionLA); assert(!unionLA.get()); } else if(! unionLA.get()) { ret = std::move(unionPoints); assert(!unionPoints.get()); } else { ret = PointGeometryUnion::Union(*unionPoints, *unionLA); } if(! ret.get()) { ret = geomFact->createGeometryCollection(); } return ret; } } // namespace geos::operation::union } // namespace geos::operation } // namespace geos <commit_msg>Do cascaded union of lines only after standard union fails<commit_after>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2011 Sandro Santilli <strk@kbt.io * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: operation/union/UnaryUnionOp.java r320 (JTS-1.12) * **********************************************************************/ #include <memory> // for unique_ptr #include <cassert> // for assert #include <algorithm> // for copy #include <geos/operation/union/UnaryUnionOp.h> #include <geos/operation/union/CascadedUnion.h> #include <geos/operation/union/CascadedPolygonUnion.h> #include <geos/operation/union/PointGeometryUnion.h> #include <geos/geom/Coordinate.h> #include <geos/geom/Point.h> #include <geos/geom/MultiPoint.h> #include <geos/geom/MultiLineString.h> #include <geos/geom/MultiPolygon.h> #include <geos/geom/GeometryCollection.h> #include <geos/geom/Geometry.h> #include <geos/geom/Location.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/util/GeometryCombiner.h> #include <geos/algorithm/PointLocator.h> namespace geos { namespace operation { // geos::operation namespace geounion { // geos::operation::geounion /*private*/ std::unique_ptr<geom::Geometry> UnaryUnionOp::unionWithNull(std::unique_ptr<geom::Geometry> g0, std::unique_ptr<geom::Geometry> g1) { std::unique_ptr<geom::Geometry> ret; if((! g0.get()) && (! g1.get())) { return ret; } if(! g0.get()) { return g1; } if(! g1.get()) { return g0; } ret = g0->Union(g1.get()); return ret; } /*public*/ std::unique_ptr<geom::Geometry> UnaryUnionOp::Union() { typedef std::unique_ptr<geom::Geometry> GeomPtr; GeomPtr ret; if(! geomFact) { return ret; } /** * For points and lines, only a single union operation is * required, since the OGC model allowings self-intersecting * MultiPoint and MultiLineStrings. * This is not the case for polygons, so Cascaded Union is required. */ GeomPtr unionPoints; if(!points.empty()) { GeomPtr ptGeom = geomFact->buildGeometry(points.begin(), points.end()); unionPoints = unionNoOpt(*ptGeom); } GeomPtr unionLines; if(!lines.empty()) { /* JTS compatibility NOTE: * we use cascaded here for robustness [1] * but also add a final unionNoOpt step to deal with * self-intersecting lines [2] * * [1](http://trac.osgeo.org/geos/ticket/392 * [2](http://trac.osgeo.org/geos/ticket/482 * */ try { auto combinedLines = geomFact->buildGeometry(lines.begin(), lines.end()); unionLines = unionNoOpt(*combinedLines); } catch (geos::util::TopologyException & e) { unionLines.reset(CascadedUnion::Union(lines.begin(), lines.end())); if(unionLines.get()) { unionLines = unionNoOpt(*unionLines); } } } GeomPtr unionPolygons; if(!polygons.empty()) { unionPolygons.reset(CascadedPolygonUnion::Union(polygons.begin(), polygons.end())); } /** * Performing two unions is somewhat inefficient, * but is mitigated by unioning lines and points first */ GeomPtr unionLA = unionWithNull(std::move(unionLines), std::move(unionPolygons)); assert(!unionLines.get()); assert(!unionPolygons.get()); if(! unionPoints.get()) { ret = std::move(unionLA); assert(!unionLA.get()); } else if(! unionLA.get()) { ret = std::move(unionPoints); assert(!unionPoints.get()); } else { ret = PointGeometryUnion::Union(*unionPoints, *unionLA); } if(! ret.get()) { ret = geomFact->createGeometryCollection(); } return ret; } } // namespace geos::operation::union } // namespace geos::operation } // namespace geos <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMetaImageIO.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <string> #include "itkMetaImageIO.h" #include "itkExceptionObject.h" namespace itk { MetaImageIO::MetaImageIO() { if(MET_SystemByteOrderMSB()) m_ByteOrder = BigEndian; else m_ByteOrder = LittleEndian; } MetaImageIO::~MetaImageIO() { m_Ifstream.close(); } void MetaImageIO::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); m_MetaImage.PrintInfo(); } void MetaImageIO::SetDataFileName( const char* filename ) { m_MetaImage.ElementDataFileName( filename ); } // This method will only test if the header looks like a // MetaImage. Some code is redundant with ReadImageInformation // a StateMachine could provide a better implementation bool MetaImageIO::CanReadFile( const char* filename ) { // First check the extension std::string fname = filename; if( fname == "" || !( fname.find(".mha") < fname.length() || fname.find(".mhd") < fname.length() ) ) { itkDebugMacro(<<"The filename extension is not recognized"); return false; } // Now check the file content std::ifstream inputStream; inputStream.open( filename, std::ios::in | std::ios::binary ); if( inputStream.fail() ) { return false; } char key[8000]; inputStream >> key; if( inputStream.eof() ) { inputStream.close(); return false; } if( strcmp(key,"NDims")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ObjectType")==0 ) { inputStream.close(); return true; } if( strcmp(key,"TransformType")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ID")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ParentID")==0 ) { inputStream.close(); return true; } if( strcmp(key,"BinaryData")==0 ) { inputStream.close(); return true; } if( strcmp(key,"Comment")==0 ) { inputStream.close(); return true; } if( strcmp(key,"AcquisitionDate")==0 ) { inputStream.close(); return true; } if( strcmp(key,"Modality")==0 ) { inputStream.close(); return true; } inputStream.close(); return false; } void MetaImageIO::ReadImageInformation() { if(!m_MetaImage.Read(m_FileName.c_str()), false) { ExceptionObject exception(__FILE__, __LINE__); exception.SetDescription("File cannot be read"); throw exception; } if(m_MetaImage.BinaryData()) { this->SetFileType(Binary); } else { this->SetFileType(ASCII); } this->SetNumberOfComponents(m_MetaImage.ElementNumberOfChannels()); switch(m_MetaImage.ElementType()) { default: case MET_OTHER: case MET_NONE: this->SetPixelType( UNKNOWN ); this->SetComponentType( UNKNOWN ); break; case MET_CHAR: case MET_CHAR_ARRAY: case MET_STRING: case MET_ASCII_CHAR: this->SetPixelType( CHAR ); this->SetComponentType( CHAR ); break; case MET_UCHAR: case MET_UCHAR_ARRAY: this->SetPixelType( UCHAR ); this->SetComponentType( UCHAR ); break; case MET_SHORT: case MET_SHORT_ARRAY: this->SetPixelType( SHORT ); this->SetComponentType( SHORT ); break; case MET_USHORT: case MET_USHORT_ARRAY: this->SetPixelType( USHORT ); this->SetComponentType( USHORT ); break; case MET_INT: case MET_INT_ARRAY: this->SetPixelType( INT ); this->SetComponentType( INT ); break; case MET_UINT: case MET_UINT_ARRAY: this->SetPixelType( UINT ); this->SetComponentType( UINT ); break; case MET_FLOAT: case MET_FLOAT_ARRAY: this->SetPixelType( FLOAT ); this->SetComponentType( FLOAT ); break; case MET_DOUBLE: case MET_DOUBLE_ARRAY: this->SetPixelType( DOUBLE ); this->SetComponentType( DOUBLE ); break; case MET_FLOAT_MATRIX: this->SetPixelType( FLOAT ); this->SetComponentType( FLOAT ); this->SetNumberOfComponents(m_NumberOfComponents * m_NumberOfComponents); break; } this->SetNumberOfDimensions(m_MetaImage.NDims()); int i; for(i=0; i<(int)m_NumberOfDimensions; i++) { this->SetDimensions(i, m_MetaImage.DimSize(i)); this->SetSpacing(i, m_MetaImage.ElementSpacing(i)); this->SetOrigin(i, m_MetaImage.Position(i)); } } void MetaImageIO::Read(void* buffer) { if(!m_MetaImage.Read(m_FileName.c_str(), true, buffer)) { ExceptionObject exception(__FILE__, __LINE__); exception.SetDescription("File cannot be read"); throw exception; } m_MetaImage.ElementByteOrderFix(); } MetaImage * MetaImageIO::GetMetaImagePointer(void) { return & m_MetaImage; } bool MetaImageIO::CanWriteFile( const char * name ) { std::string filename = name; if( filename == "" ) { return false; } if( filename.find(".mha") < filename.length() || filename.find(".mhd") < filename.length() ) { return true; } return false; } void MetaImageIO ::WriteImageInformation(void) { } /** * */ void MetaImageIO ::Write( const void* buffer) { int nDims = this->GetNumberOfDimensions(); bool binaryData = false; if(this->GetFileType() == Binary) { binaryData = true; } int nChannels = this->GetNumberOfComponents(); MET_ValueEnumType eType; switch(m_PixelType) { default: case UNKNOWN: eType = MET_OTHER; break; case CHAR: eType = MET_CHAR; break; case UCHAR: eType = MET_UCHAR; break; case SHORT: eType = MET_SHORT; break; case USHORT: eType = MET_USHORT; break; case INT: eType = MET_INT; break; case UINT: eType = MET_UINT; break; case FLOAT: eType = MET_FLOAT; break; case DOUBLE: eType = MET_DOUBLE; break; } int i; int * dSize = new int[nDims]; float * eSpacing = new float[nDims]; float * eOrigin = new float[nDims]; for(i=0; i<nDims; i++) { dSize[i] = this->GetDimensions(i); eSpacing[i] = this->GetSpacing(i); eOrigin[i] = this->GetOrigin(i); } m_MetaImage.InitializeEssential(nDims, dSize, eSpacing, eType, nChannels, (void *)buffer); m_MetaImage.Position(eOrigin); m_MetaImage.BinaryData(binaryData); if(strlen(m_MetaImage.ElementDataFileName())==0) { std::string dataName; dataName = m_FileName + ".raw"; m_MetaImage.Write(m_FileName.c_str(), dataName.c_str()); } else { m_MetaImage.Write(m_FileName.c_str()); } delete dSize; delete eSpacing; delete eOrigin; } } // end namespace itk <commit_msg>FIX: The OFFSET pixel type is translated into MetaImage MET_INT_ARRAY.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMetaImageIO.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <string> #include "itkMetaImageIO.h" #include "itkExceptionObject.h" namespace itk { MetaImageIO::MetaImageIO() { if(MET_SystemByteOrderMSB()) m_ByteOrder = BigEndian; else m_ByteOrder = LittleEndian; } MetaImageIO::~MetaImageIO() { m_Ifstream.close(); } void MetaImageIO::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); m_MetaImage.PrintInfo(); } void MetaImageIO::SetDataFileName( const char* filename ) { m_MetaImage.ElementDataFileName( filename ); } // This method will only test if the header looks like a // MetaImage. Some code is redundant with ReadImageInformation // a StateMachine could provide a better implementation bool MetaImageIO::CanReadFile( const char* filename ) { // First check the extension std::string fname = filename; if( fname == "" || !( fname.find(".mha") < fname.length() || fname.find(".mhd") < fname.length() ) ) { itkDebugMacro(<<"The filename extension is not recognized"); return false; } // Now check the file content std::ifstream inputStream; inputStream.open( filename, std::ios::in | std::ios::binary ); if( inputStream.fail() ) { return false; } char key[8000]; inputStream >> key; if( inputStream.eof() ) { inputStream.close(); return false; } if( strcmp(key,"NDims")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ObjectType")==0 ) { inputStream.close(); return true; } if( strcmp(key,"TransformType")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ID")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ParentID")==0 ) { inputStream.close(); return true; } if( strcmp(key,"BinaryData")==0 ) { inputStream.close(); return true; } if( strcmp(key,"Comment")==0 ) { inputStream.close(); return true; } if( strcmp(key,"AcquisitionDate")==0 ) { inputStream.close(); return true; } if( strcmp(key,"Modality")==0 ) { inputStream.close(); return true; } inputStream.close(); return false; } void MetaImageIO::ReadImageInformation() { if(!m_MetaImage.Read(m_FileName.c_str()), false) { ExceptionObject exception(__FILE__, __LINE__); exception.SetDescription("File cannot be read"); throw exception; } if(m_MetaImage.BinaryData()) { this->SetFileType(Binary); } else { this->SetFileType(ASCII); } this->SetNumberOfComponents(m_MetaImage.ElementNumberOfChannels()); switch(m_MetaImage.ElementType()) { default: case MET_OTHER: case MET_NONE: this->SetPixelType( UNKNOWN ); this->SetComponentType( UNKNOWN ); break; case MET_CHAR: case MET_CHAR_ARRAY: case MET_STRING: case MET_ASCII_CHAR: this->SetPixelType( CHAR ); this->SetComponentType( CHAR ); break; case MET_UCHAR: case MET_UCHAR_ARRAY: this->SetPixelType( UCHAR ); this->SetComponentType( UCHAR ); break; case MET_SHORT: case MET_SHORT_ARRAY: this->SetPixelType( SHORT ); this->SetComponentType( SHORT ); break; case MET_USHORT: case MET_USHORT_ARRAY: this->SetPixelType( USHORT ); this->SetComponentType( USHORT ); break; case MET_INT: case MET_INT_ARRAY: this->SetPixelType( INT ); this->SetComponentType( INT ); break; case MET_UINT: case MET_UINT_ARRAY: this->SetPixelType( UINT ); this->SetComponentType( UINT ); break; case MET_FLOAT: case MET_FLOAT_ARRAY: this->SetPixelType( FLOAT ); this->SetComponentType( FLOAT ); break; case MET_DOUBLE: case MET_DOUBLE_ARRAY: this->SetPixelType( DOUBLE ); this->SetComponentType( DOUBLE ); break; case MET_FLOAT_MATRIX: this->SetPixelType( FLOAT ); this->SetComponentType( FLOAT ); this->SetNumberOfComponents(m_NumberOfComponents * m_NumberOfComponents); break; } this->SetNumberOfDimensions(m_MetaImage.NDims()); int i; for(i=0; i<(int)m_NumberOfDimensions; i++) { this->SetDimensions(i, m_MetaImage.DimSize(i)); this->SetSpacing(i, m_MetaImage.ElementSpacing(i)); this->SetOrigin(i, m_MetaImage.Position(i)); } } void MetaImageIO::Read(void* buffer) { if(!m_MetaImage.Read(m_FileName.c_str(), true, buffer)) { ExceptionObject exception(__FILE__, __LINE__); exception.SetDescription("File cannot be read"); throw exception; } m_MetaImage.ElementByteOrderFix(); } MetaImage * MetaImageIO::GetMetaImagePointer(void) { return & m_MetaImage; } bool MetaImageIO::CanWriteFile( const char * name ) { std::string filename = name; if( filename == "" ) { return false; } if( filename.find(".mha") < filename.length() || filename.find(".mhd") < filename.length() ) { return true; } return false; } void MetaImageIO ::WriteImageInformation(void) { } /** * */ void MetaImageIO ::Write( const void* buffer) { int nDims = this->GetNumberOfDimensions(); bool binaryData = false; if(this->GetFileType() == Binary) { binaryData = true; } int nChannels = this->GetNumberOfComponents(); MET_ValueEnumType eType; switch(m_PixelType) { default: case UNKNOWN: eType = MET_OTHER; break; case CHAR: eType = MET_CHAR; break; case UCHAR: eType = MET_UCHAR; break; case SHORT: eType = MET_SHORT; break; case USHORT: eType = MET_USHORT; break; case INT: eType = MET_INT; break; case UINT: eType = MET_UINT; break; case FLOAT: eType = MET_FLOAT; break; case DOUBLE: eType = MET_DOUBLE; break; case OFFSET: eType = MET_INT_ARRAY; break; } int i; int * dSize = new int[nDims]; float * eSpacing = new float[nDims]; float * eOrigin = new float[nDims]; for(i=0; i<nDims; i++) { dSize[i] = this->GetDimensions(i); eSpacing[i] = this->GetSpacing(i); eOrigin[i] = this->GetOrigin(i); } m_MetaImage.InitializeEssential(nDims, dSize, eSpacing, eType, nChannels, (void *)buffer); m_MetaImage.Position(eOrigin); m_MetaImage.BinaryData(binaryData); if(strlen(m_MetaImage.ElementDataFileName())==0) { std::string dataName; dataName = m_FileName + ".raw"; m_MetaImage.Write(m_FileName.c_str(), dataName.c_str()); } else { m_MetaImage.Write(m_FileName.c_str()); } delete dSize; delete eSpacing; delete eOrigin; } } // end namespace itk <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <stdlib.h> #include <TROOT.h> #include <TTree.h> #include <TFile.h> #include <TSQLServer.h> #include <TSQLResult.h> #include <TSQLRow.h> #include "DataStruct.h" using namespace std; int main(int argc, char* argv[]) { // define the output file structure Spill* p_spill = new Spill; Spill& spill = *p_spill; spill.skipflag = false; TFile* saveFile = new TFile(argv[2], "recreate"); TTree* saveTree = new TTree("save", "save"); saveTree->Branch("spill", &p_spill, 256000, 99); //Connect to server TSQLServer* server = TSQLServer::Connect(Form("mysql://%s:%d", argv[3], atoi(argv[4])), "seaguest", "qqbar2mu+mu-"); server->Exec(Form("USE %s", argv[1])); cout << "Reading schema " << argv[1] << " and save to " << argv[2] << endl; char query[5000]; //sprintf(query, "SELECT spillID FROM Spill WHERE runID in (SELECT run FROM summary.production WHERE ktracked=1) ORDER BY spillID"); sprintf(query, "SELECT runID,spillID FROM Spill ORDER BY spillID"); TSQLResult* res = server->Query(query); int nSpillsRow = res->GetRowCount(); int nBadSpill_record = 0; int nBadSpill_duplicate = 0; int nBadSpill_quality = 0; for(int i = 0; i < nSpillsRow; ++i) { if(i % 100 == 0) { cout << "Converting spill " << i << "/" << nSpillsRow << endl; } //basic spillID info TSQLRow* row = res->Next(); int runID = atoi(row->GetField(0)); spill.spillID = atoi(row->GetField(1)); spill.trigSet = spill.triggerSet(); delete row; //magnet configuration sprintf(query, "SELECT value FROM Beam WHERE spillID=%d AND name IN ('F:NM3S','F:NM4AN') ORDER BY name", spill.spillID); TSQLResult* res_spill = server->Query(query); if(res_spill->GetRowCount() != 2) { spill.log(Form("lacks magnet info %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 2 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } TSQLRow* row_spill = res_spill->Next(); spill.FMAG = atof(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.KMAG = atoi(row_spill->GetField(0)); delete row_spill; delete res_spill; //EventID range sprintf(query, "SELECT MIN(eventID),MAX(eventID) FROM Event WHERE runID=%d AND spillID=%d", runID, spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 1) { spill.log(Form("lacks event table entry %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 1 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.eventID_min = atoi(row_spill->GetField(0)); spill.eventID_max = atoi(row_spill->GetField(1)); delete row_spill; delete res_spill; //target position sprintf(query, "SELECT a.targetPos,b.value,a.dataQuality,a.liveProton FROM Spill AS a,Target AS b WHERE a.spillID" "=%d AND b.spillID=%d AND b.name='TARGPOS_CONTROL'", spill.spillID, spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 1) { spill.log(Form("lacks target position info %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 1 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.targetPos = atoi(row_spill->GetField(0)); spill.TARGPOS_CONTROL = atoi(row_spill->GetField(1)); spill.quality = atoi(row_spill->GetField(2)); spill.liveProton = row_spill->GetField(3) == NULL ? -1. : atof(row_spill->GetField(3)); delete row_spill; delete res_spill; //Reconstruction info sprintf(query, "SELECT (SELECT COUNT(*) FROM Event WHERE spillID=%d)," "(SELECT COUNT(*) FROM kDimuon WHERE spillID=%d)," "(SELECT COUNT(*) FROM kTrack WHERE spillID=%d)", spill.spillID, spill.spillID, spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 1) { spill.log(Form("lacks reconstructed tables %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 1 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.nEvents = atoi(row_spill->GetField(0)); spill.nDimuons = atoi(row_spill->GetField(1)); spill.nTracks = atoi(row_spill->GetField(2)); delete row_spill; delete res_spill; //Beam/BeamDAQ sprintf(query, "SELECT a.value,b.NM3ION,b.QIESum,b.inhibit_block_sum,b.trigger_sum_no_inhibit," "b.dutyFactor53MHz FROM Beam AS a,BeamDAQ AS b WHERE a.spillID=%d AND b.spillID=%d AND " "a.name='S:G2SEM'", spill.spillID, spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 1) { spill.log(Form("lacks Beam/BeamDAQ info %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 1 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.G2SEM = atof(row_spill->GetField(0)); spill.NM3ION = atof(row_spill->GetField(1)); spill.QIESum = atof(row_spill->GetField(2)); spill.inhibitSum = atof(row_spill->GetField(3)); spill.busySum = atof(row_spill->GetField(4)); spill.dutyFactor = atof(row_spill->GetField(5)); delete row_spill; delete res_spill; //Scalar table -- EOS sprintf(query, "SELECT value FROM Scaler WHERE spillType='EOS' AND spillID=%d AND scalerName " "in ('TSGo','AcceptedMatrix1','AfterInhMatrix1') ORDER BY scalerName", spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 3) { spill.log(Form("lacks scaler info %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 3 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.acceptedMatrix1 = atof(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.afterInhMatrix1 = atof(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.TSGo = atof(row_spill->GetField(0)); delete row_spill; delete res_spill; //Scalar table -- BOS sprintf(query, "SELECT value FROM Scaler WHERE spillType='BOS' AND spillID=%d AND scalerName " "in ('TSGo','AcceptedMatrix1','AfterInhMatrix1') ORDER BY scalerName", spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 3) { spill.log(Form("lacks scaler info %d", res_spill->GetRowCount())); spill.acceptedMatrix1BOS = -1; spill.afterInhMatrix1BOS = -1; spill.TSGoBOS = -1; } else { row_spill = res_spill->Next(); spill.acceptedMatrix1BOS = atof(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.afterInhMatrix1BOS = atof(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.TSGoBOS = atof(row_spill->GetField(0)); delete row_spill; } delete res_spill; if(!spill.goodSpill()) { ++nBadSpill_quality; spill.log("spill bad"); spill.print(); } //Save saveTree->Fill(); } delete res; cout << "sqlSpillReader finished successfully." << endl; cout << saveTree->GetEntries() << " good spills, " << nBadSpill_record << " spills have insufficient info in database, " << nBadSpill_duplicate << " spills have duplicate entries in database, " << nBadSpill_quality << " rejected because of bad quality." << endl; saveFile->cd(); saveTree->Write(); saveFile->Close(); return EXIT_SUCCESS; } <commit_msg>fixed a bug in sql spill reader<commit_after>#include <iostream> #include <cmath> #include <stdlib.h> #include <TROOT.h> #include <TTree.h> #include <TFile.h> #include <TSQLServer.h> #include <TSQLResult.h> #include <TSQLRow.h> #include "DataStruct.h" using namespace std; Spill* gSpill; int getInt(const char* row) { if(row == NULL) { gSpill->log("Integer content is missing."); return -9999; } return atoi(row); } float getFloat(const char* row) { if(row == NULL) { gSpill->log("Floating content is missing."); return -9999.; } return atof(row); } int main(int argc, char* argv[]) { // define the output file structure Spill* p_spill = new Spill; Spill& spill = *p_spill; spill.skipflag = false; gSpill = p_spill; TFile* saveFile = new TFile(argv[2], "recreate"); TTree* saveTree = new TTree("save", "save"); saveTree->Branch("spill", &p_spill, 256000, 99); //Connect to server TSQLServer* server = TSQLServer::Connect(Form("mysql://%s:%d", argv[3], getInt(argv[4])), "seaguest", "qqbar2mu+mu-"); server->Exec(Form("USE %s", argv[1])); cout << "Reading schema " << argv[1] << " and save to " << argv[2] << endl; char query[5000]; //sprintf(query, "SELECT spillID FROM Spill WHERE runID in (SELECT run FROM summary.production WHERE ktracked=1) ORDER BY spillID"); sprintf(query, "SELECT runID,spillID FROM Spill ORDER BY spillID"); TSQLResult* res = server->Query(query); int nSpillsRow = res->GetRowCount(); int nBadSpill_record = 0; int nBadSpill_duplicate = 0; int nBadSpill_quality = 0; for(int i = 0; i < nSpillsRow; ++i) { if(i % 100 == 0) { cout << "Converting spill " << i << "/" << nSpillsRow << endl; } //basic spillID info TSQLRow* row = res->Next(); int runID = getInt(row->GetField(0)); spill.spillID = getInt(row->GetField(1)); spill.trigSet = spill.triggerSet(); delete row; //magnet configuration sprintf(query, "SELECT value FROM Beam WHERE spillID=%d AND name IN ('F:NM3S','F:NM4AN') ORDER BY name", spill.spillID); TSQLResult* res_spill = server->Query(query); if(res_spill->GetRowCount() != 2) { spill.log(Form("lacks magnet info %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 2 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } TSQLRow* row_spill = res_spill->Next(); spill.FMAG = getFloat(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.KMAG = getInt(row_spill->GetField(0)); delete row_spill; delete res_spill; //EventID range sprintf(query, "SELECT MIN(eventID),MAX(eventID) FROM Event WHERE runID=%d AND spillID=%d", runID, spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 1) { spill.log(Form("lacks event table entry %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 1 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.eventID_min = getInt(row_spill->GetField(0)); spill.eventID_max = getInt(row_spill->GetField(1)); delete row_spill; delete res_spill; //target position sprintf(query, "SELECT a.targetPos,b.value,a.dataQuality,a.liveProton FROM Spill AS a,Target AS b WHERE a.spillID" "=%d AND b.spillID=%d AND b.name='TARGPOS_CONTROL'", spill.spillID, spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 1) { spill.log(Form("lacks target position info %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 1 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.targetPos = getInt(row_spill->GetField(0)); spill.TARGPOS_CONTROL = getInt(row_spill->GetField(1)); spill.quality = getInt(row_spill->GetField(2)); spill.liveProton = row_spill->GetField(3) == NULL ? -1. : getFloat(row_spill->GetField(3)); delete row_spill; delete res_spill; //Reconstruction info sprintf(query, "SELECT (SELECT COUNT(*) FROM Event WHERE spillID=%d)," "(SELECT COUNT(*) FROM kDimuon WHERE spillID=%d)," "(SELECT COUNT(*) FROM kTrack WHERE spillID=%d)", spill.spillID, spill.spillID, spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 1) { spill.log(Form("lacks reconstructed tables %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 1 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.nEvents = getInt(row_spill->GetField(0)); spill.nDimuons = getInt(row_spill->GetField(1)); spill.nTracks = getInt(row_spill->GetField(2)); delete row_spill; delete res_spill; //Beam/BeamDAQ sprintf(query, "SELECT a.value,b.NM3ION,b.QIESum,b.inhibit_block_sum,b.trigger_sum_no_inhibit," "b.dutyFactor53MHz FROM Beam AS a,BeamDAQ AS b WHERE a.spillID=%d AND b.spillID=%d AND " "a.name='S:G2SEM'", spill.spillID, spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 1) { spill.log(Form("lacks Beam/BeamDAQ info %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 1 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.G2SEM = getFloat(row_spill->GetField(0)); spill.NM3ION = getFloat(row_spill->GetField(1)); spill.QIESum = getFloat(row_spill->GetField(2)); spill.inhibitSum = getFloat(row_spill->GetField(3)); spill.busySum = getFloat(row_spill->GetField(4)); spill.dutyFactor = getFloat(row_spill->GetField(5)); delete row_spill; delete res_spill; //Scalar table -- EOS sprintf(query, "SELECT value FROM Scaler WHERE spillType='EOS' AND spillID=%d AND scalerName " "in ('TSGo','AcceptedMatrix1','AfterInhMatrix1') ORDER BY scalerName", spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 3) { spill.log(Form("lacks scaler info %d", res_spill->GetRowCount())); res_spill->GetRowCount() > 3 ? ++nBadSpill_duplicate : ++nBadSpill_record; delete res_spill; continue; } row_spill = res_spill->Next(); spill.acceptedMatrix1 = getFloat(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.afterInhMatrix1 = getFloat(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.TSGo = getFloat(row_spill->GetField(0)); delete row_spill; delete res_spill; //Scalar table -- BOS sprintf(query, "SELECT value FROM Scaler WHERE spillType='BOS' AND spillID=%d AND scalerName " "in ('TSGo','AcceptedMatrix1','AfterInhMatrix1') ORDER BY scalerName", spill.spillID); res_spill = server->Query(query); if(res_spill->GetRowCount() != 3) { spill.log(Form("lacks scaler info %d", res_spill->GetRowCount())); spill.acceptedMatrix1BOS = -1; spill.afterInhMatrix1BOS = -1; spill.TSGoBOS = -1; } else { row_spill = res_spill->Next(); spill.acceptedMatrix1BOS = getFloat(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.afterInhMatrix1BOS = getFloat(row_spill->GetField(0)); delete row_spill; row_spill = res_spill->Next(); spill.TSGoBOS = getFloat(row_spill->GetField(0)); delete row_spill; } delete res_spill; if(!spill.goodSpill()) { ++nBadSpill_quality; spill.log("spill bad"); spill.print(); } //Save saveTree->Fill(); } delete res; cout << "sqlSpillReader finished successfully." << endl; cout << saveTree->GetEntries() << " good spills, " << nBadSpill_record << " spills have insufficient info in database, " << nBadSpill_duplicate << " spills have duplicate entries in database, " << nBadSpill_quality << " rejected because of bad quality." << endl; saveFile->cd(); saveTree->Write(); saveFile->Close(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>Breaking Example 1 on purpose - please comment this line to compile //Moose Includes #include "Moose.h" #include "KernelFactory.h" #include "BCFactory.h" #include "MaterialFactory.h" #include "AuxFactory.h" #include "ComputeResidual.h" #include "ComputeJacobian.h" // C++ include files that we need #include <iostream> #include <fstream> // libMesh includes #include "libmesh.h" #include "perf_log.h" #include "mesh.h" #include "boundary_info.h" #include "exodusII_io.h" #include "equation_systems.h" #include "nonlinear_solver.h" #include "nonlinear_implicit_system.h" #include "linear_implicit_system.h" #include "transient_system.h" // Initialize default Performance Logging PerfLog Moose::perf_log("Example1"); // Begin the main program. int main (int argc, char** argv) { { // Initialize Moose MooseInit init(argc, argv); // This registers a bunch of common objects that exist in Moose with the factories. // that includes several Kernels, BoundaryConditions, AuxKernels and Materials Moose::registerObjects(); // Create the mesh object Mesh mesh(2); // MUST set the global mesh! Moose::mesh = &mesh; // Read the mesh from an Exodus file and prepare it for use ExodusII_IO exreader(mesh); exreader.read("square.e"); /** * The "false" specifies _not_ to renumber nodes and elements * this could be a slight hit to performance, but it means that your * output file will have the same node and element numbering as the input */ mesh.prepare_for_use(false); /** * This builds nodesets from your sidesets * these autogenerated nodesets are used for Dirichlet boundary conditions * NEVER manually create nodesets... always let the code autogenerate them * note that if the mesh changes (such as after adaptivity) you have to */ mesh.boundary_info->build_node_list_from_side_list(); // Print some useful information about the mesh mesh.print_info(); // The equation_systems holds all the Systems we want to solve EquationSystems equation_systems (mesh); // MUST set the global equation_systems! Moose::equation_system = &equation_systems; // This is the actual Nonlinear System we are going to solve TransientNonlinearImplicitSystem& system = equation_systems.add_system<TransientNonlinearImplicitSystem> ("NonlinearSystem"); /** * Add a variable named "u" to solve for. * We are going to approximate it using First order Lagrange FEs */ system.add_variable("u", FIRST, LAGRANGE); // Set the residual and jacobian functions to the default ones provided by MOOSE system.nonlinear_solver->residual = Moose::compute_residual; system.nonlinear_solver->jacobian = Moose::compute_jacobian; /** * This is a NECESSARY auxiliary system for computing auxiliary variables * Even though we're not going to have any of those we MUST create this system. */ TransientExplicitSystem& aux_system = equation_systems.add_system<TransientExplicitSystem> ("AuxiliarySystem"); // Initialize the Systems and print some info out equation_systems.init(); equation_systems.print_info(); /** * Initialize common data structures for Kernels. * These MUST be called in this order... and at this point. */ Kernel::init(&equation_systems); BoundaryCondition::init(); AuxKernel::init(); // Blank params to use for Kernels that don't need params Parameters params; // Parameters for DirichletBC's Parameters left_bc_params; left_bc_params.set<Real>("value") = 0.0; Parameters right_bc_params; right_bc_params.set<Real>("value") = 1.0; // Add a Diffusion Kernel from MOOSE into the calculation. KernelFactory::instance()->add("Diffusion", "diff", params, "u"); // Add the two boundary conditions using the DirichletBC object from MOOSE BCFactory::instance()->add("DirichletBC", "left", left_bc_params, "u", 1); BCFactory::instance()->add("DirichletBC", "right", right_bc_params, "u", 2); // Every calculation MUST add at least one Material // Here we use the EmptyMaterial from MOOSE because we don't need material properties. MaterialFactory::instance()->add("EmptyMaterial", "empty", params, 1); // Solve the Nonlinear System system.solve(); // Write the solution out. ExodusII_IO(mesh).write_equation_systems("out.e", equation_systems); } return 0; } <commit_msg>Testing Bitten<commit_after>//Moose Includes #include "Moose.h" #include "KernelFactory.h" #include "BCFactory.h" #include "MaterialFactory.h" #include "AuxFactory.h" #include "ComputeResidual.h" #include "ComputeJacobian.h" // C++ include files that we need #include <iostream> #include <fstream> // libMesh includes #include "libmesh.h" #include "perf_log.h" #include "mesh.h" #include "boundary_info.h" #include "exodusII_io.h" #include "equation_systems.h" #include "nonlinear_solver.h" #include "nonlinear_implicit_system.h" #include "linear_implicit_system.h" #include "transient_system.h" // Initialize default Performance Logging PerfLog Moose::perf_log("Example1"); // Begin the main program. int main (int argc, char** argv) { { // Initialize Moose MooseInit init(argc, argv); // This registers a bunch of common objects that exist in Moose with the factories. // that includes several Kernels, BoundaryConditions, AuxKernels and Materials Moose::registerObjects(); // Create the mesh object Mesh mesh(2); // MUST set the global mesh! Moose::mesh = &mesh; // Read the mesh from an Exodus file and prepare it for use ExodusII_IO exreader(mesh); exreader.read("square.e"); /** * The "false" specifies _not_ to renumber nodes and elements * this could be a slight hit to performance, but it means that your * output file will have the same node and element numbering as the input */ mesh.prepare_for_use(false); /** * This builds nodesets from your sidesets * these autogenerated nodesets are used for Dirichlet boundary conditions * NEVER manually create nodesets... always let the code autogenerate them * note that if the mesh changes (such as after adaptivity) you have to */ mesh.boundary_info->build_node_list_from_side_list(); // Print some useful information about the mesh mesh.print_info(); // The equation_systems holds all the Systems we want to solve EquationSystems equation_systems (mesh); // MUST set the global equation_systems! Moose::equation_system = &equation_systems; // This is the actual Nonlinear System we are going to solve TransientNonlinearImplicitSystem& system = equation_systems.add_system<TransientNonlinearImplicitSystem> ("NonlinearSystem"); /** * Add a variable named "u" to solve for. * We are going to approximate it using First order Lagrange FEs */ system.add_variable("u", FIRST, LAGRANGE); // Set the residual and jacobian functions to the default ones provided by MOOSE system.nonlinear_solver->residual = Moose::compute_residual; system.nonlinear_solver->jacobian = Moose::compute_jacobian; /** * This is a NECESSARY auxiliary system for computing auxiliary variables * Even though we're not going to have any of those we MUST create this system. */ TransientExplicitSystem& aux_system = equation_systems.add_system<TransientExplicitSystem> ("AuxiliarySystem"); // Initialize the Systems and print some info out equation_systems.init(); equation_systems.print_info(); /** * Initialize common data structures for Kernels. * These MUST be called in this order... and at this point. */ Kernel::init(&equation_systems); BoundaryCondition::init(); AuxKernel::init(); // Blank params to use for Kernels that don't need params Parameters params; // Parameters for DirichletBC's Parameters left_bc_params; left_bc_params.set<Real>("value") = 0.0; Parameters right_bc_params; right_bc_params.set<Real>("value") = 1.0; // Add a Diffusion Kernel from MOOSE into the calculation. KernelFactory::instance()->add("Diffusion", "diff", params, "u"); // Add the two boundary conditions using the DirichletBC object from MOOSE BCFactory::instance()->add("DirichletBC", "left", left_bc_params, "u", 1); BCFactory::instance()->add("DirichletBC", "right", right_bc_params, "u", 2); // Every calculation MUST add at least one Material // Here we use the EmptyMaterial from MOOSE because we don't need material properties. MaterialFactory::instance()->add("EmptyMaterial", "empty", params, 1); // Solve the Nonlinear System system.solve(); // Write the solution out. ExodusII_IO(mesh).write_equation_systems("out.e", equation_systems); } return 0; } <|endoftext|>
<commit_before>#pragma once #include <initializer_list> #include "Print-lite.hpp" #include <algorithm> #include <stdexcept> #include <iterator> #include <memory> #include <string> #include <random> namespace evt { template <typename Type> class Array { // MARK: - Attributes std::unique_ptr<Type[]> values { nullptr }; size_t count_ { 0 }; size_t capacity_ { 0 }; // MARK: - Private functions template <typename Container> void assignNewElements(const Container& elements) { count_ = std::distance(std::begin(elements), std::end(elements)); capacity_ = count_; #if __cplusplus >= 201400 values = std::make_unique<Type[]>(count()); #elif __cplusplus >= 201100 values = std::unique_ptr<Type[]>(new Type[count()]); #endif size_t index = 0; for (const auto& element: elements) { values[index] = element; ++index; } } template <typename Container> Array& appendNewElements(const Container& newElements) { size_t countOfContainer = std::distance(std::begin(newElements), std::end(newElements)); if (capacity() >= (count() + countOfContainer)) { size_t index = count(); for (const auto& newElement: newElements) { values[index] = newElement; ++index; } count_ += countOfContainer; } else { size_t newCount = (this->isEmpty()) ? (countOfContainer) : (count() * 2); while (newCount < (count() + countOfContainer)) { newCount += 2; } #if __cplusplus >= 201400 auto newValues = std::make_unique<Type[]>(newCount); #elif __cplusplus >= 201100 std::unique_ptr<Type[]> newValues (new Type[newCount]); #endif if (count() > 0) { std::copy(this->begin(), this->end(), &newValues[0]); } size_t index = count(); for (const auto& element: newElements) { newValues[index] = element; ++index; } values = move(newValues); capacity_ = newCount; count_ = count() + countOfContainer; } return *this; } // TRUE if elements are the same template<typename Container> bool compareElements(const Container& elements) const { size_t index = 0; for (const auto& element: elements) { if (values[index] != element) { return false; } ++index; } return true; } void checkIfEmpty() const { if (count() == 0) { throw std::length_error("Array is empty (lenght == 0)"); } } void checkIfOutOfRange(const size_t index) const { if (index >= count()) { throw std::out_of_range("Index out of range"); } } public: // MARK: Constructors Array() {} template<typename Container> Array(const Container& elements) { assignNewElements(elements); } Array(const std::initializer_list<Type>& elements) { assignNewElements(elements); } explicit Array(const Array& otherArray) { (*this) = otherArray; } explicit Array(const int32_t capacity): capacity_(capacity) { // Type can't be size_t because it intefere with the other constructor size_t intialCapacity = (capacity < 0) ? (- capacity) : (capacity); #if __cplusplus >= 201400 values = std::make_unique<Type[]>(intialCapacity); #elif __cplusplus >= 201100 values = std::unique_ptr<Type[]>(new Type[intialCapacity]); #endif } size_t count() const { return count_; } size_t capacity() const { return capacity_; } // MARK: Manage elements void insert(const Type& newElement, const size_t index) { checkIfOutOfRange(index); std::unique_ptr<Type[]> newValues = nullptr; if (capacity() == count()) { size_t newCount = (this->isEmpty()) ? (2) : (count() * 2); #if __cplusplus >= 201400 newValues = std::make_unique<Type[]>(newCount); #elif __cplusplus >= 201100 newValues = std::unique_ptr<Type[]>(new Type[newCount]); #endif std::copy(this->begin(), this->end(), &newValues[0]); std::copy(&newValues[index], &newValues[count_ + 1], &newValues[index + 1]); capacity_ = newCount; } else { #if __cplusplus >= 201400 newValues = std::make_unique<Type[]>(count()); #elif __cplusplus >= 201100 newValues = std::unique_ptr<Type[]>(new Type[count()]); #endif std::copy(this->begin(), this->end(), &newValues[0]); std::copy(&newValues[index], &newValues[count()], &newValues[index + 1]); } newValues[index] = newElement; values = move(newValues); count_ += 1; } void append(const Type& newElement) { if (capacity() == count()) { size_t newCount = (this->isEmpty()) ? (2) : (count() * 2); #if __cplusplus >= 201400 auto newValues = std::make_unique<Type[]>(newCount); #elif __cplusplus >= 201100 std::unique_ptr<Type[]> newValues (new Type[newCount]); #endif if (count() > 0) { std::copy(this->begin(), this->end(), &newValues[0]); } newValues[count()] = newElement; values = move(newValues); capacity_ = newCount; } else if (count() < capacity()) { values[count()] = newElement; } count_ += 1; } template<typename Container> void appendElements(const Container& newElements) { (*this) += newElements; } void append(const std::initializer_list<Type>& newElements) { (*this) += newElements; } void resize(const size_t newSize) { if (newSize == 0 && count() > 0 && capacity() > 0 && values != nullptr) { removeAll(); } checkIfEmpty(); if (newSize < capacity()) { std::for_each(&values[newSize], this->end(), [](Type& value){ value = Type{}; }); count_ = newSize; } else if (newSize > capacity()) { #if __cplusplus >= 201400 auto newValues = std::make_unique<Type[]>(newSize); #elif __cplusplus >= 201100 std::unique_ptr<Type[]> newValues(new Type[newSize]); #endif std::copy(this->begin(), this->end(), &newValues[0]); values = move(newValues); capacity_ = newSize; } } bool shrink() { if (capacity() > count()) { #if __cplusplus >= 201400 auto newValues = std::make_unique<Type[]>(count()); #elif __cplusplus >= 201100 std::unique_ptr<Type[]> newValues (new Type[count()]); #endif if (count() > 0) { std::copy(this->begin(), this->end(), &newValues[0]); } values = move(newValues); capacity_ = count(); return true; } return false; } void clear() { removeAll(true); } void removeAll(const bool keepCapacity = false) { if (keepCapacity) { if (values != nullptr) { std::for_each(this->begin(), this->end(), [](Type& value){ value = Type{}; }); count_ = 0; } } else { #if __cplusplus >= 201400 values = std::make_unique<Type[]>(0); #elif __cplusplus >= 201100 values = std::unique_ptr<Type[]>(new Type[0]); #endif count_ = 0; capacity_ = 0; } } void removeAt(const size_t index, const bool shrinkIfEmpty = true) { if (count() == 1 && capacity() > 1 && values != nullptr && shrinkIfEmpty) { shrink(); } checkIfEmpty(); checkIfOutOfRange(index); std::copy(&values[index + 1], this->end(), &values[index]); values[count() - 1] = Type{}; count_ -= 1; } void removeLast(const bool shrinkIfEmpty = true) { if (count() == 1 && capacity() > 1 && values != nullptr && shrinkIfEmpty) { shrink(); } checkIfEmpty(); values[count()] = Type{}; count_ -= 1; } void removeFirst() { removeAt(0); } bool contains(const Type& element) const { checkIfEmpty(); return (std::find(this->begin(), this->end(), element)) != this->end(); } bool isEmpty() const { return (count() == 0); } std::string toString() const { if (this->isEmpty()) { return "[]"; } std::string output = "["; size_t position = 0; for (const auto& value: *this) { output += quotedString(value); if (position+1 < count()) { output += ", "; } ++position; } output += "]"; return output; } // MARK: Operators overload Type& operator[](const size_t index) { checkIfOutOfRange(index); return values[index]; } template<typename Container> Array& operator+=(const Container& newElements) { return appendNewElements(newElements); } Array& operator+=(const std::initializer_list<Type>& newElements) { return appendNewElements(newElements); } template<typename Container> bool operator==(const Container& elements) const { return compareElements(elements); } bool operator==(const std::initializer_list<Type>& elements) const { return compareElements(elements); } template<typename Container> bool operator!=(const Container& elements) const { return !( (*this) == elements ); } bool operator!=(const std::initializer_list<Type>& elements) const { return !( (*this) == elements ); } Array& operator=(const Array& otherArray) { count_ = otherArray.count(); capacity_ = otherArray.capacity(); #if __cplusplus >= 201400 values = std::make_unique<Type[]>(capacity()); #elif __cplusplus >= 201100 values = std::unique_ptr<Type[]> (new Type[capacity()]); #endif std::copy(otherArray.begin(), otherArray.end(), this->begin()); return *this; } Array& operator=(Array&& otherArray) { count_ = std::move(otherArray.count()); capacity_ = std::move(otherArray.capacity()); values = move(otherArray.values); otherArray.values = nullptr; otherArray.count_ = 0; otherArray.capacity_ = 0; return *this; } // MARK: Shuffle void shuffle() { checkIfEmpty(); #ifdef __APPLE__ std::mt19937_64 rng(arc4random()); #else random_device rd; mt19937_64 rng(rd()); #endif std::shuffle(this->begin(), this->end(), rng); } Array shuffled() const { checkIfEmpty(); Array otherArray(*this); otherArray.shuffle(); return otherArray; } // MARK: Sort void sort() { checkIfEmpty(); std::sort(this->begin(), this->end()); } template <typename Function> void sort(const Function& compareFunction) { checkIfEmpty(); std::sort(this->begin(), this->end(), compareFunction); } template <typename Function> Array sorted(const Function& compareFunction) const { checkIfEmpty(); Array otherArray(*this); otherArray.sort(compareFunction); return otherArray; } Array sorted() const { checkIfEmpty(); Array otherArray(*this); otherArray.sort(); return otherArray; } // MARK: Positions Type* begin() const { checkIfEmpty(); return &values[0]; } Type* end() const { checkIfEmpty(); return &values[count()]; } Type first() const { checkIfEmpty(); return values[0]; } Type last() const { checkIfEmpty(); return values[count() - 1]; } }; } <commit_msg>v1.2.1: - Added the namespace on random_device<commit_after>#pragma once #include <initializer_list> #include "Print-lite.hpp" #include <algorithm> #include <stdexcept> #include <iterator> #include <memory> #include <string> #include <random> namespace evt { template <typename Type> class Array { // MARK: - Attributes std::unique_ptr<Type[]> values { nullptr }; size_t count_ { 0 }; size_t capacity_ { 0 }; // MARK: - Private functions template <typename Container> void assignNewElements(const Container& elements) { count_ = std::distance(std::begin(elements), std::end(elements)); capacity_ = count_; #if __cplusplus >= 201400 values = std::make_unique<Type[]>(count()); #elif __cplusplus >= 201100 values = std::unique_ptr<Type[]>(new Type[count()]); #endif size_t index = 0; for (const auto& element: elements) { values[index] = element; ++index; } } template <typename Container> Array& appendNewElements(const Container& newElements) { size_t countOfContainer = std::distance(std::begin(newElements), std::end(newElements)); if (capacity() >= (count() + countOfContainer)) { size_t index = count(); for (const auto& newElement: newElements) { values[index] = newElement; ++index; } count_ += countOfContainer; } else { size_t newCount = (this->isEmpty()) ? (countOfContainer) : (count() * 2); while (newCount < (count() + countOfContainer)) { newCount += 2; } #if __cplusplus >= 201400 auto newValues = std::make_unique<Type[]>(newCount); #elif __cplusplus >= 201100 std::unique_ptr<Type[]> newValues (new Type[newCount]); #endif if (count() > 0) { std::copy(this->begin(), this->end(), &newValues[0]); } size_t index = count(); for (const auto& element: newElements) { newValues[index] = element; ++index; } values = move(newValues); capacity_ = newCount; count_ = count() + countOfContainer; } return *this; } // TRUE if elements are the same template<typename Container> bool compareElements(const Container& elements) const { size_t index = 0; for (const auto& element: elements) { if (values[index] != element) { return false; } ++index; } return true; } void checkIfEmpty() const { if (count() == 0) { throw std::length_error("Array is empty (lenght == 0)"); } } void checkIfOutOfRange(const size_t index) const { if (index >= count()) { throw std::out_of_range("Index out of range"); } } public: // MARK: Constructors Array() {} template<typename Container> Array(const Container& elements) { assignNewElements(elements); } Array(const std::initializer_list<Type>& elements) { assignNewElements(elements); } explicit Array(const Array& otherArray) { (*this) = otherArray; } explicit Array(const int32_t capacity): capacity_(capacity) { // Type can't be size_t because it intefere with the other constructor size_t intialCapacity = (capacity < 0) ? (- capacity) : (capacity); #if __cplusplus >= 201400 values = std::make_unique<Type[]>(intialCapacity); #elif __cplusplus >= 201100 values = std::unique_ptr<Type[]>(new Type[intialCapacity]); #endif } size_t count() const { return count_; } size_t capacity() const { return capacity_; } // MARK: Manage elements void insert(const Type& newElement, const size_t index) { checkIfOutOfRange(index); std::unique_ptr<Type[]> newValues = nullptr; if (capacity() == count()) { size_t newCount = (this->isEmpty()) ? (2) : (count() * 2); #if __cplusplus >= 201400 newValues = std::make_unique<Type[]>(newCount); #elif __cplusplus >= 201100 newValues = std::unique_ptr<Type[]>(new Type[newCount]); #endif std::copy(this->begin(), this->end(), &newValues[0]); std::copy(&newValues[index], &newValues[count_ + 1], &newValues[index + 1]); capacity_ = newCount; } else { #if __cplusplus >= 201400 newValues = std::make_unique<Type[]>(count()); #elif __cplusplus >= 201100 newValues = std::unique_ptr<Type[]>(new Type[count()]); #endif std::copy(this->begin(), this->end(), &newValues[0]); std::copy(&newValues[index], &newValues[count()], &newValues[index + 1]); } newValues[index] = newElement; values = move(newValues); count_ += 1; } void append(const Type& newElement) { if (capacity() == count()) { size_t newCount = (this->isEmpty()) ? (2) : (count() * 2); #if __cplusplus >= 201400 auto newValues = std::make_unique<Type[]>(newCount); #elif __cplusplus >= 201100 std::unique_ptr<Type[]> newValues (new Type[newCount]); #endif if (count() > 0) { std::copy(this->begin(), this->end(), &newValues[0]); } newValues[count()] = newElement; values = move(newValues); capacity_ = newCount; } else if (count() < capacity()) { values[count()] = newElement; } count_ += 1; } template<typename Container> void appendElements(const Container& newElements) { (*this) += newElements; } void append(const std::initializer_list<Type>& newElements) { (*this) += newElements; } void resize(const size_t newSize) { if (newSize == 0 && count() > 0 && capacity() > 0 && values != nullptr) { removeAll(); } checkIfEmpty(); if (newSize < capacity()) { std::for_each(&values[newSize], this->end(), [](Type& value){ value = Type{}; }); count_ = newSize; } else if (newSize > capacity()) { #if __cplusplus >= 201400 auto newValues = std::make_unique<Type[]>(newSize); #elif __cplusplus >= 201100 std::unique_ptr<Type[]> newValues(new Type[newSize]); #endif std::copy(this->begin(), this->end(), &newValues[0]); values = move(newValues); capacity_ = newSize; } } bool shrink() { if (capacity() > count()) { #if __cplusplus >= 201400 auto newValues = std::make_unique<Type[]>(count()); #elif __cplusplus >= 201100 std::unique_ptr<Type[]> newValues (new Type[count()]); #endif if (count() > 0) { std::copy(this->begin(), this->end(), &newValues[0]); } values = move(newValues); capacity_ = count(); return true; } return false; } void clear() { removeAll(true); } void removeAll(const bool keepCapacity = false) { if (keepCapacity) { if (values != nullptr) { std::for_each(this->begin(), this->end(), [](Type& value){ value = Type{}; }); count_ = 0; } } else { #if __cplusplus >= 201400 values = std::make_unique<Type[]>(0); #elif __cplusplus >= 201100 values = std::unique_ptr<Type[]>(new Type[0]); #endif count_ = 0; capacity_ = 0; } } void removeAt(const size_t index, const bool shrinkIfEmpty = true) { if (count() == 1 && capacity() > 1 && values != nullptr && shrinkIfEmpty) { shrink(); } checkIfEmpty(); checkIfOutOfRange(index); std::copy(&values[index + 1], this->end(), &values[index]); values[count() - 1] = Type{}; count_ -= 1; } void removeLast(const bool shrinkIfEmpty = true) { if (count() == 1 && capacity() > 1 && values != nullptr && shrinkIfEmpty) { shrink(); } checkIfEmpty(); values[count()] = Type{}; count_ -= 1; } void removeFirst() { removeAt(0); } bool contains(const Type& element) const { checkIfEmpty(); return (std::find(this->begin(), this->end(), element)) != this->end(); } bool isEmpty() const { return (count() == 0); } std::string toString() const { if (this->isEmpty()) { return "[]"; } std::string output = "["; size_t position = 0; for (const auto& value: *this) { output += quotedString(value); if (position+1 < count()) { output += ", "; } ++position; } output += "]"; return output; } // MARK: Operators overload Type& operator[](const size_t index) { checkIfOutOfRange(index); return values[index]; } template<typename Container> Array& operator+=(const Container& newElements) { return appendNewElements(newElements); } Array& operator+=(const std::initializer_list<Type>& newElements) { return appendNewElements(newElements); } template<typename Container> bool operator==(const Container& elements) const { return compareElements(elements); } bool operator==(const std::initializer_list<Type>& elements) const { return compareElements(elements); } template<typename Container> bool operator!=(const Container& elements) const { return !( (*this) == elements ); } bool operator!=(const std::initializer_list<Type>& elements) const { return !( (*this) == elements ); } Array& operator=(const Array& otherArray) { count_ = otherArray.count(); capacity_ = otherArray.capacity(); #if __cplusplus >= 201400 values = std::make_unique<Type[]>(capacity()); #elif __cplusplus >= 201100 values = std::unique_ptr<Type[]> (new Type[capacity()]); #endif std::copy(otherArray.begin(), otherArray.end(), this->begin()); return *this; } Array& operator=(Array&& otherArray) { count_ = std::move(otherArray.count()); capacity_ = std::move(otherArray.capacity()); values = move(otherArray.values); otherArray.values = nullptr; otherArray.count_ = 0; otherArray.capacity_ = 0; return *this; } // MARK: Shuffle void shuffle() { checkIfEmpty(); #ifdef __APPLE__ std::mt19937_64 rng(arc4random()); #else std::random_device rd; mt19937_64 rng(rd()); #endif std::shuffle(this->begin(), this->end(), rng); } Array shuffled() const { checkIfEmpty(); Array otherArray(*this); otherArray.shuffle(); return otherArray; } // MARK: Sort void sort() { checkIfEmpty(); std::sort(this->begin(), this->end()); } template <typename Function> void sort(const Function& compareFunction) { checkIfEmpty(); std::sort(this->begin(), this->end(), compareFunction); } template <typename Function> Array sorted(const Function& compareFunction) const { checkIfEmpty(); Array otherArray(*this); otherArray.sort(compareFunction); return otherArray; } Array sorted() const { checkIfEmpty(); Array otherArray(*this); otherArray.sort(); return otherArray; } // MARK: Positions Type* begin() const { checkIfEmpty(); return &values[0]; } Type* end() const { checkIfEmpty(); return &values[count()]; } Type first() const { checkIfEmpty(); return values[0]; } Type last() const { checkIfEmpty(); return values[count() - 1]; } }; } <|endoftext|>
<commit_before>/*---------------------------------------------------------------------\ | | | _ _ _ _ __ _ | | | | | | | \_/ | / \ | | | | | | | | | |_| | / /\ \ | | | | | |__ | | | | | | / ____ \ | |__ | | |____||_| |_| |_|/ / \ \|____| | | | | ca-mgm library | | | | (C) SUSE Linux Products GmbH | \----------------------------------------------------------------------/ File: CAConfig.hpp Author: <Michael Calmer> <mc@suse.de> Maintainer: <Michael Calmer> <mc@suse.de> Purpose: /-*/ /** * @file CAConfig.hpp * @brief This is a short description of the library. */ #ifndef LIMAL_CA_CONFIG_HPP #define LIMAL_CA_CONFIG_HPP #include <limal/ca-mgm/config.h> #include <limal/ca-mgm/CommonData.hpp> #include <limal/INIParser.hpp> namespace LIMAL_NAMESPACE { namespace CA_MGM_NAMESPACE { class CAConfig { public: CAConfig(const String &file); ~CAConfig(); void setValue(const String &section, const String &key, const String &value); void deleteValue(const String &section, const String &key); String getValue(const String &section, const String &key) const; bool exists(const String &section, const String &key) const; List<String> CAConfig::getKeylist(const String &section) const; CAConfig *clone(const String &file); void dump(); private: INI::INIParser *parser; String srcFilename; CAConfig(); CAConfig(const CAConfig&); CAConfig& operator=(const CAConfig&); void dumpTree(INI::Section *section, int level = 0); }; } } #endif //LIMAL_CA_CONFIG_HPP <commit_msg>fix typo<commit_after>/*---------------------------------------------------------------------\ | | | _ _ _ _ __ _ | | | | | | | \_/ | / \ | | | | | | | | | |_| | / /\ \ | | | | | |__ | | | | | | / ____ \ | |__ | | |____||_| |_| |_|/ / \ \|____| | | | | ca-mgm library | | | | (C) SUSE Linux Products GmbH | \----------------------------------------------------------------------/ File: CAConfig.hpp Author: <Michael Calmer> <mc@suse.de> Maintainer: <Michael Calmer> <mc@suse.de> Purpose: /-*/ /** * @file CAConfig.hpp * @brief This is a short description of the library. */ #ifndef LIMAL_CA_CONFIG_HPP #define LIMAL_CA_CONFIG_HPP #include <limal/ca-mgm/config.h> #include <limal/ca-mgm/CommonData.hpp> #include <limal/INIParser.hpp> namespace LIMAL_NAMESPACE { namespace CA_MGM_NAMESPACE { class CAConfig { public: CAConfig(const String &file); ~CAConfig(); void setValue(const String &section, const String &key, const String &value); void deleteValue(const String &section, const String &key); String getValue(const String &section, const String &key) const; bool exists(const String &section, const String &key) const; List<String> getKeylist(const String &section) const; CAConfig *clone(const String &file); void dump(); private: INI::INIParser *parser; String srcFilename; CAConfig(); CAConfig(const CAConfig&); CAConfig& operator=(const CAConfig&); void dumpTree(INI::Section *section, int level = 0); }; } } #endif //LIMAL_CA_CONFIG_HPP <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include <ports/ports.hpp> #include <ports/region_aware.hpp> using namespace fc; BOOST_AUTO_TEST_SUITE(test_parallle_region); BOOST_AUTO_TEST_CASE(test_region_aware_node) { typedef region_aware<event_in_port<int>> test_in_port; auto region = std::make_shared<parallel_region>(); int test_value = 0; auto write_param = [&](int i) {test_value = i;}; test_in_port test_in(region, write_param); BOOST_CHECK_EQUAL(test_value, 0); test_in.operator ()(1); BOOST_CHECK_EQUAL(test_value, 1); } BOOST_AUTO_TEST_CASE(test_same_region) { typedef region_aware<event_in_port<int>> test_in_port; typedef region_aware<event_out_port<int>> test_out_port; auto region = std::make_shared<parallel_region>(); int test_value = 0; auto write_param = [&](int i) {test_value = i;}; test_in_port test_in(region, write_param); test_out_port test_out(region); static_assert(is_passive_sink<test_in_port>::value, ""); static_assert(has_result<test_out_port>::value, "its an out port, that has result_type defined"); test_out >> test_in; BOOST_CHECK_EQUAL(test_value, 0); test_out.fire(1); BOOST_CHECK_EQUAL(test_value, 1); auto tmp = test_out >> [](int i ){ return ++i;}; tmp >> test_in; test_out.fire(1); BOOST_CHECK_EQUAL(test_value, 2); } BOOST_AUTO_TEST_CASE(test_different_region) { typedef region_aware<event_in_port<int>> test_in_port; typedef region_aware<event_out_port<int>> test_out_port; auto region_1 = std::make_shared<parallel_region>("r1"); auto region_2 = std::make_shared<parallel_region>("r2"); int test_value = 0; auto write_param = [&test_value](int i) {test_value = i;}; test_in_port test_in(region_2, write_param); test_out_port test_out(region_1); test_out >> test_in; BOOST_CHECK_EQUAL(test_value, 0); test_out.fire(1); //since we have a region transition, we need a switch tick BOOST_CHECK_EQUAL(test_value, 0); region_1->ticks.in_switch_buffers()(); BOOST_CHECK_EQUAL(test_value, 0); region_2->ticks.in_work()(); BOOST_CHECK_EQUAL(test_value, 1); } BOOST_AUTO_TEST_CASE(test_connectable_in_between) { typedef region_aware<event_in_port<int>> test_in_port; typedef region_aware<event_out_port<int>> test_out_port; auto region_1 = std::make_shared<parallel_region>("r1"); auto region_2 = std::make_shared<parallel_region>("r2"); int test_value = 0; auto write_param = [&test_value](int i) {test_value = i;}; test_in_port test_in(region_2, write_param); test_out_port test_out(region_1); test_out >> [](int i){ return i+1;} >> test_in; BOOST_CHECK_EQUAL(test_value, 0); test_out.fire(1); //since we have a region transition, we need a switch tick BOOST_CHECK_EQUAL(test_value, 0); region_1->ticks.in_switch_buffers()(); BOOST_CHECK_EQUAL(test_value, 0); region_2->ticks.in_work()(); BOOST_CHECK_EQUAL(test_value, 2); // test more than one lambda in between auto region_3 = std::make_shared<parallel_region>("r3"); test_in_port test_in_2(region_3, write_param); test_out >> [](int i){ return i+1;} >> [](int i){ return i+1;} >> test_in_2; test_out.fire(1); region_1->ticks.in_switch_buffers()(); region_2->ticks.in_work()(); //wrong region ticked, expect no change BOOST_CHECK_EQUAL(test_value, 2); region_3->ticks.in_work()(); BOOST_CHECK_EQUAL(test_value, 3); } BOOST_AUTO_TEST_CASE(test_state_transition) { typedef region_aware<state_sink<int>> test_in_port; typedef region_aware<state_source_with_setter<int>> test_out_port; auto region_1 = std::make_shared<parallel_region>("r1"); auto region_2 = std::make_shared<parallel_region>("r2"); test_out_port source(region_1,1); test_in_port sink(region_2); static_assert(is_instantiation_of<region_aware, test_in_port>::value, ""); static_assert(is_instantiation_of<region_aware, test_out_port>::value, ""); static_assert(is_active_sink<test_in_port>::value, ""); static_assert(is_passive_source<test_out_port>::value, ""); source >> sink; BOOST_CHECK_EQUAL(sink.get(), 0); region_1->ticks.in_work()(); BOOST_CHECK_EQUAL(sink.get(), 0); region_2->ticks.in_switch_buffers()(); BOOST_CHECK_EQUAL(sink.get(), 1); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>use sink buffer to test sequential generation output in test_node_aware.<commit_after>#include <boost/test/unit_test.hpp> #include <ports/ports.hpp> #include <ports/region_aware.hpp> using namespace fc; BOOST_AUTO_TEST_SUITE(test_parallle_region); BOOST_AUTO_TEST_CASE(test_region_aware_node) { typedef region_aware<event_in_port<int>> test_in_port; auto region = std::make_shared<parallel_region>(); int test_value = 0; auto write_param = [&](int i) {test_value = i;}; test_in_port test_in(region, write_param); BOOST_CHECK_EQUAL(test_value, 0); test_in(1); BOOST_CHECK_EQUAL(test_value, 1); } BOOST_AUTO_TEST_CASE(test_same_region) { typedef region_aware<event_in_port<int>> test_in_port; typedef region_aware<event_out_port<int>> test_out_port; auto region = std::make_shared<parallel_region>(); std::vector<int> test_sink; auto write_param = [&](int i) {test_sink.push_back(i);}; test_in_port test_in(region, write_param); test_out_port test_out(region); static_assert(is_passive_sink<test_in_port>::value, ""); static_assert(has_result<test_out_port>::value, "its an out port, that has result_type defined"); test_out >> test_in; BOOST_CHECK_EQUAL(test_sink.size(), 0); test_out.fire(1); BOOST_CHECK_EQUAL(test_sink.at(0), 1); auto tmp = test_out >> [](int i ){ return ++i;}; tmp >> test_in; test_out.fire(1); BOOST_CHECK_EQUAL(test_sink.at(1), 1); BOOST_CHECK_EQUAL(test_sink.at(2), 2); } BOOST_AUTO_TEST_CASE(test_different_region) { typedef region_aware<event_in_port<int>> test_in_port; typedef region_aware<event_out_port<int>> test_out_port; auto region_1 = std::make_shared<parallel_region>("r1"); auto region_2 = std::make_shared<parallel_region>("r2"); int test_value = 0; auto write_param = [&test_value](int i) {test_value = i;}; test_in_port test_in(region_2, write_param); test_out_port test_out(region_1); test_out >> test_in; BOOST_CHECK_EQUAL(test_value, 0); test_out.fire(1); //since we have a region transition, we need a switch tick BOOST_CHECK_EQUAL(test_value, 0); region_1->ticks.in_switch_buffers()(); BOOST_CHECK_EQUAL(test_value, 0); region_2->ticks.in_work()(); BOOST_CHECK_EQUAL(test_value, 1); } BOOST_AUTO_TEST_CASE(test_connectable_in_between) { typedef region_aware<event_in_port<int>> test_in_port; typedef region_aware<event_out_port<int>> test_out_port; auto region_1 = std::make_shared<parallel_region>("r1"); auto region_2 = std::make_shared<parallel_region>("r2"); int test_value = 0; auto write_param = [&test_value](int i) {test_value = i;}; test_in_port test_in(region_2, write_param); test_out_port test_out(region_1); test_out >> [](int i){ return i+1;} >> test_in; BOOST_CHECK_EQUAL(test_value, 0); test_out.fire(1); //since we have a region transition, we need a switch tick BOOST_CHECK_EQUAL(test_value, 0); region_1->ticks.in_switch_buffers()(); BOOST_CHECK_EQUAL(test_value, 0); region_2->ticks.in_work()(); BOOST_CHECK_EQUAL(test_value, 2); // test more than one lambda in between auto region_3 = std::make_shared<parallel_region>("r3"); test_in_port test_in_2(region_3, write_param); test_out >> [](int i){ return i+1;} >> [](int i){ return i*2;} >> test_in_2; test_out.fire(1); region_1->ticks.in_switch_buffers()(); region_2->ticks.in_work()(); //wrong region ticked, expect no change BOOST_CHECK_EQUAL(test_value, 2); region_3->ticks.in_work()(); BOOST_CHECK_EQUAL(test_value, 4); } BOOST_AUTO_TEST_CASE(test_state_transition) { typedef region_aware<state_sink<int>> test_in_port; typedef region_aware<state_source_with_setter<int>> test_out_port; auto region_1 = std::make_shared<parallel_region>("r1"); auto region_2 = std::make_shared<parallel_region>("r2"); test_out_port source(region_1,1); test_in_port sink(region_2); static_assert(is_instantiation_of<region_aware, test_in_port>::value, ""); static_assert(is_instantiation_of<region_aware, test_out_port>::value, ""); static_assert(is_active_sink<test_in_port>::value, ""); static_assert(is_passive_source<test_out_port>::value, ""); source >> sink; BOOST_CHECK_EQUAL(sink.get(), 0); region_1->ticks.in_work()(); BOOST_CHECK_EQUAL(sink.get(), 0); region_2->ticks.in_switch_buffers()(); BOOST_CHECK_EQUAL(sink.get(), 1); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>#include "sampler.hpp" #include "context.hpp" #include "texture.hpp" #include "internal/wrapper.hpp" #include "internal/modules.hpp" #include "internal/tools.hpp" #include "internal/glsl.hpp" /* MGLContext.sampler(texture) */ PyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) { if (nargs != 1) { // TODO: error return 0; } PyObject * texture = args[0]; MGLSampler * sampler = MGLContext_new_object(self, Sampler); const GLMethods & gl = self->gl; gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj); if (!sampler->sampler_obj) { PyErr_Format(moderngl_error, "cannot create sampler"); Py_DECREF(sampler); return 0; } gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST); SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture; return NEW_REF(sampler->wrapper); } /* MGLSampler.use(location) */ PyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) { PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture); MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo); int location = PyLong_AsLong(arg); self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj); Py_RETURN_NONE; } #if PY_VERSION_HEX >= 0x03070000 PyMethodDef MGLSampler_methods[] = { {"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0}, {0}, }; #else PyMethodDef MGLSampler_methods[] = { {"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0}, {0}, }; #endif PyType_Slot MGLSampler_slots[] = { {Py_tp_methods, MGLSampler_methods}, {0}, }; PyType_Spec MGLSampler_spec = { mgl_name ".Sampler", sizeof(MGLSampler), 0, Py_TPFLAGS_DEFAULT, MGLSampler_slots, }; <commit_msg>sampler properties<commit_after>#include "sampler.hpp" #include "context.hpp" #include "texture.hpp" #include "internal/wrapper.hpp" #include "internal/modules.hpp" #include "internal/tools.hpp" #include "internal/glsl.hpp" /* MGLContext.sampler(texture) */ PyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) { if (nargs != 1) { // TODO: error return 0; } PyObject * texture = args[0]; MGLSampler * sampler = MGLContext_new_object(self, Sampler); const GLMethods & gl = self->gl; gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj); if (!sampler->sampler_obj) { PyErr_Format(moderngl_error, "cannot create sampler"); Py_DECREF(sampler); return 0; } gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST); SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture; return NEW_REF(sampler->wrapper); } /* MGLSampler.use(location) */ PyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) { PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture); MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo); int location = PyLong_AsLong(arg); self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj); Py_RETURN_NONE; } int MGLSampler_set_filter(MGLSampler * self, PyObject * value) { return 0; } int MGLSampler_set_repeat_x(MGLSampler * self, PyObject * value) { if (PyObject_IsTrue(value)) { SLOT(self->wrapper, PyObject, Sampler_class_repeat_x) = NEW_REF(Py_True); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT); } else { SLOT(self->wrapper, PyObject, Sampler_class_repeat_x) = NEW_REF(Py_False); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); } return 0; } int MGLSampler_set_repeat_y(MGLSampler * self, PyObject * value) { if (PyObject_IsTrue(value)) { SLOT(self->wrapper, PyObject, Sampler_class_repeat_y) = NEW_REF(Py_True); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT); } else { SLOT(self->wrapper, PyObject, Sampler_class_repeat_y) = NEW_REF(Py_False); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } return 0; } int MGLSampler_set_repeat_z(MGLSampler * self, PyObject * value) { if (PyObject_IsTrue(value)) { SLOT(self->wrapper, PyObject, Sampler_class_repeat_z) = NEW_REF(Py_True); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT); } else { SLOT(self->wrapper, PyObject, Sampler_class_repeat_z) = NEW_REF(Py_False); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); } return 0; } int MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) { return 0; } int MGLSampler_set_min_lod(MGLSampler * self, PyObject * value) { int min_lod = PyLong_AsLong(value); SLOT(self->wrapper, PyObject, Sampler_class_min_lod) = NEW_REF(value); self->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod); return 0; } int MGLSampler_set_max_lod(MGLSampler * self, PyObject * value) { int max_lod = PyLong_AsLong(value); SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = NEW_REF(value); self->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MAX_LOD, max_lod); return 0; } #if PY_VERSION_HEX >= 0x03070000 PyMethodDef MGLSampler_methods[] = { {"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0}, {0}, }; #else PyMethodDef MGLSampler_methods[] = { {"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0}, {0}, }; #endif PyGetSetDef MGLSampler_getset[] = { {"filter", 0, (setter)MGLSampler_set_filter, 0, 0}, {"repeat_x", 0, (setter)MGLSampler_set_repeat_x, 0, 0}, {"repeat_y", 0, (setter)MGLSampler_set_repeat_y, 0, 0}, {"repeat_z", 0, (setter)MGLSampler_set_repeat_z, 0, 0}, {"anisotropy", 0, (setter)MGLSampler_set_anisotropy, 0, 0}, {"min_lod", 0, (setter)MGLSampler_set_min_lod, 0, 0}, {"max_lod", 0, (setter)MGLSampler_set_max_lod, 0, 0}, {0}, }; PyType_Slot MGLSampler_slots[] = { {Py_tp_methods, MGLSampler_methods}, {Py_tp_getset, MGLSampler_getset}, {0}, }; PyType_Spec MGLSampler_spec = { mgl_name ".Sampler", sizeof(MGLSampler), 0, Py_TPFLAGS_DEFAULT, MGLSampler_slots, }; <|endoftext|>
<commit_before>/* Basic Server code for CMPT 276, Spring 2016. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "TableCache.h" #include "config.h" #include "make_unique.h" #include "azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using web::http::http_headers; using web::http::http_request; using web::http::methods; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; constexpr const char* def_url = "http://localhost:34568"; const string create_table {"CreateTable"}; const string delete_table {"DeleteTable"}; const string update_entity {"UpdateEntity"}; const string delete_entity {"DeleteEntity"}; /* Cache of opened tables */ TableCache table_cache {}; /* Convert properties represented in Azure Storage type to prop_vals_t type. */ prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) { for (const auto v : properties) { if (v.second.property_type() == edm_type::string) { values.push_back(make_pair(v.first, value::string(v.second.string_value()))); } else if (v.second.property_type() == edm_type::datetime) { values.push_back(make_pair(v.first, value::string(v.second.str()))); } else if(v.second.property_type() == edm_type::int32) { values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); } else if(v.second.property_type() == edm_type::int64) { values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); } else if(v.second.property_type() == edm_type::double_floating_point) { values.push_back(make_pair(v.first, value::number(v.second.double_value()))); } else if(v.second.property_type() == edm_type::boolean) { values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); } else { values.push_back(make_pair(v.first, value::string(v.second.str()))); } } return values; } /* Return true if an HTTP request has a JSON body */ bool has_json_body (http_request message) { return message.headers()["Content-type"] == "application/json"; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. If the message has no JSON body, return an empty map. Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } /* Top-level routine for processing all HTTP GET requests. GET is the only request that has no command. All operands specify the value(s) to be retrieved. */ void handle_get(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** GET " << path << endl; auto paths = uri::split_path(path); // Need at least a table name if (paths.size() < 1) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[0])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } // GET all entries in table if (paths.size() == 1) { table_query query {}; table_query_iterator end; table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } message.reply(status_codes::OK, value::array(key_vec)); return; } if (paths.size() != 3) { message.reply (status_codes::BadRequest); return; } // GET specific entry: Partition == paths[1], Row == paths[2] table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])}; table_result retrieve_result {table.execute(retrieve_operation)}; cout << "HTTP code: " << retrieve_result.http_status_code() << endl; if (retrieve_result.http_status_code() == status_codes::NotFound) { message.reply(status_codes::NotFound); return; } table_entity entity {retrieve_result.entity()}; table_entity::properties_type properties {entity.properties()}; // If the entity has any properties, return them as JSON prop_vals_t values (get_properties(properties)); if (values.size() > 0) message.reply(status_codes::OK, value::object(values)); else message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP POST requests. */ void handle_post(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and a table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } // [0] refers to the operation name // Evaluated after size() to ensure legitimate access else if (paths[0] != create_table) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Create table (idempotent if table exists) cout << "Create " << table_name << endl; bool created {table.create_if_not_exists()}; cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl; if (created) message.reply(status_codes::Created); else message.reply(status_codes::Accepted); } /* Top-level routine for processing all HTTP PUT requests. */ void handle_put(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** PUT " << path << endl; auto paths = uri::split_path(path); // Need at least an operation, table name, partition, and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } // [0] refers to the operation name // Evaluated after size() to ensure legitimate access else if (paths[0] != update_entity) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[1])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } table_entity entity {paths[2], paths[3]}; // Update entity cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl; table_entity::properties_type& properties = entity.properties(); for (const auto v : get_json_body(message)) { properties[v.first] = entity_property {v.second}; } table_operation operation {table_operation::insert_or_merge_entity(entity)}; table_result op_result {table.execute(operation)}; message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP DELETE requests. */ void handle_delete(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** DELETE " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Delete table if (paths[0] == delete_table) { cout << "Delete " << table_name << endl; if ( ! table.exists()) { message.reply(status_codes::NotFound); } table.delete_table(); table_cache.delete_entry(table_name); message.reply(status_codes::OK); } // Delete entity else if (paths[0] == delete_entity) { // For delete entity, also need partition and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } table_entity entity {paths[2], paths[3]}; cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl; table_operation operation {table_operation::delete_entity(entity)}; table_result op_result {table.execute(operation)}; int code {op_result.http_status_code()}; if (code == status_codes::OK || code == status_codes::NoContent) message.reply(status_codes::OK); else message.reply(code); } else { message.reply(status_codes::BadRequest); } } /* Main server routine Install handlers for the HTTP requests and open the listener, which processes each request asynchronously. Wait for a carriage return, then shut the server down. */ int main (int argc, char const * argv[]) { cout << "Parsing connection string" << endl; table_cache.init (storage_connection_string); cout << "Opening listener" << endl; http_listener listener {def_url}; listener.support(methods::GET, &handle_get); listener.support(methods::POST, &handle_post); listener.support(methods::PUT, &handle_put); listener.support(methods::DEL, &handle_delete); listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <commit_msg>Add get_json_bourne as alias for get_json_body<commit_after>/* Basic Server code for CMPT 276, Spring 2016. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "TableCache.h" #include "config.h" #include "make_unique.h" #include "azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using web::http::http_headers; using web::http::http_request; using web::http::methods; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; constexpr const char* def_url = "http://localhost:34568"; const string create_table {"CreateTable"}; const string delete_table {"DeleteTable"}; const string update_entity {"UpdateEntity"}; const string delete_entity {"DeleteEntity"}; /* Cache of opened tables */ TableCache table_cache {}; /* Convert properties represented in Azure Storage type to prop_vals_t type. */ prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) { for (const auto v : properties) { if (v.second.property_type() == edm_type::string) { values.push_back(make_pair(v.first, value::string(v.second.string_value()))); } else if (v.second.property_type() == edm_type::datetime) { values.push_back(make_pair(v.first, value::string(v.second.str()))); } else if(v.second.property_type() == edm_type::int32) { values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); } else if(v.second.property_type() == edm_type::int64) { values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); } else if(v.second.property_type() == edm_type::double_floating_point) { values.push_back(make_pair(v.first, value::number(v.second.double_value()))); } else if(v.second.property_type() == edm_type::boolean) { values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); } else { values.push_back(make_pair(v.first, value::string(v.second.str()))); } } return values; } /* Return true if an HTTP request has a JSON body */ bool has_json_body (http_request message) { return message.headers()["Content-type"] == "application/json"; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. get_json_body and get_json_bourne are valid and identical function calls. If the message has no JSON body, return an empty map. Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } unordered_map<string,string> get_json_bourne(http_request message) { return get_json_body(message); } /* Top-level routine for processing all HTTP GET requests. GET is the only request that has no command. All operands specify the value(s) to be retrieved. */ void handle_get(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** GET " << path << endl; auto paths = uri::split_path(path); // Need at least a table name if (paths.size() < 1) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[0])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } // GET all entries in table if (paths.size() == 1) { table_query query {}; table_query_iterator end; table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } message.reply(status_codes::OK, value::array(key_vec)); return; } if (paths.size() != 3) { message.reply (status_codes::BadRequest); return; } // GET specific entry: Partition == paths[1], Row == paths[2] table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])}; table_result retrieve_result {table.execute(retrieve_operation)}; cout << "HTTP code: " << retrieve_result.http_status_code() << endl; if (retrieve_result.http_status_code() == status_codes::NotFound) { message.reply(status_codes::NotFound); return; } table_entity entity {retrieve_result.entity()}; table_entity::properties_type properties {entity.properties()}; // If the entity has any properties, return them as JSON prop_vals_t values (get_properties(properties)); if (values.size() > 0) message.reply(status_codes::OK, value::object(values)); else message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP POST requests. */ void handle_post(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and a table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } // [0] refers to the operation name // Evaluated after size() to ensure legitimate access else if (paths[0] != create_table) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Create table (idempotent if table exists) cout << "Create " << table_name << endl; bool created {table.create_if_not_exists()}; cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl; if (created) message.reply(status_codes::Created); else message.reply(status_codes::Accepted); } /* Top-level routine for processing all HTTP PUT requests. */ void handle_put(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** PUT " << path << endl; auto paths = uri::split_path(path); // Need at least an operation, table name, partition, and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } // [0] refers to the operation name // Evaluated after size() to ensure legitimate access else if (paths[0] != update_entity) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[1])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } table_entity entity {paths[2], paths[3]}; // Update entity cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl; table_entity::properties_type& properties = entity.properties(); for (const auto v : get_json_bourne(message)) { properties[v.first] = entity_property {v.second}; } table_operation operation {table_operation::insert_or_merge_entity(entity)}; table_result op_result {table.execute(operation)}; message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP DELETE requests. */ void handle_delete(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** DELETE " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Delete table if (paths[0] == delete_table) { cout << "Delete " << table_name << endl; if ( ! table.exists()) { message.reply(status_codes::NotFound); } table.delete_table(); table_cache.delete_entry(table_name); message.reply(status_codes::OK); } // Delete entity else if (paths[0] == delete_entity) { // For delete entity, also need partition and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } table_entity entity {paths[2], paths[3]}; cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl; table_operation operation {table_operation::delete_entity(entity)}; table_result op_result {table.execute(operation)}; int code {op_result.http_status_code()}; if (code == status_codes::OK || code == status_codes::NoContent) message.reply(status_codes::OK); else message.reply(code); } else { message.reply(status_codes::BadRequest); } } /* Main server routine Install handlers for the HTTP requests and open the listener, which processes each request asynchronously. Wait for a carriage return, then shut the server down. */ int main (int argc, char const * argv[]) { cout << "Parsing connection string" << endl; table_cache.init (storage_connection_string); cout << "Opening listener" << endl; http_listener listener {def_url}; listener.support(methods::GET, &handle_get); listener.support(methods::POST, &handle_post); listener.support(methods::PUT, &handle_put); listener.support(methods::DEL, &handle_delete); listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "rbfvectorfieldgenerator2d.h" #include <inviwo/core/datastructures/volume/volumeram.h> #include <inviwo/core/datastructures/image/image.h> #include <inviwo/core/datastructures/image/layerram.h> #include <inviwo/core/datastructures/geometry/basicmesh.h> #include <warn/push> #include <warn/ignore/all> #include <Eigen/Dense> #include <warn/pop> namespace inviwo { const ProcessorInfo RBFVectorFieldGenerator2D::processorInfo_{ "org.inviwo.RBFVectorFieldGenerator2D", // Class identifier "RBF Based 2D Vector Field Generator", // Display name "Data Creation", // Category CodeState::Experimental, // Code state Tags::CPU, // Tags }; const ProcessorInfo RBFVectorFieldGenerator2D::getProcessorInfo() const { return processorInfo_; } RBFVectorFieldGenerator2D::RBFVectorFieldGenerator2D() : Processor() , vectorField_("vectorField", DataVec4Float32::get(), false) , size_("size", "Volume size", ivec2(700, 700), ivec2(1, 1), ivec2(1024, 1024)) , seeds_("seeds", "Number of seeds", 9, 1, 100) , shape_("shape", "Shape Parameter", 1.2f, 0.0001f, 10.0f, 0.0001f) , gaussian_("gaussian", "Gaussian") , randomness_("randomness", "Randomness") , useSameSeed_("useSameSeed", "Use same seed", true) , seed_("seed", "Seed", 1, 0, std::numeric_limits<int>::max()) , rd_() , mt_(rd_()) , theta_(0, 2 * M_PI) , x_(-1.0, 1.0) { addPort(vectorField_); addProperty(size_); addProperty(seeds_); addProperty(shape_); addProperty(gaussian_); addProperty(randomness_); randomness_.addProperty(useSameSeed_); randomness_.addProperty(seed_); useSameSeed_.onChange([&]() { seed_.setVisible(useSameSeed_.get()); samples_.clear(); }); seed_.onChange([&]() { samples_.clear(); }); } RBFVectorFieldGenerator2D::~RBFVectorFieldGenerator2D() {} void RBFVectorFieldGenerator2D::process() { if (samples_.size() != seeds_.get()) { createSamples(); } Eigen::MatrixXd A(seeds_.get(), seeds_.get()); Eigen::VectorXd bx(seeds_.get()), by(seeds_.get()); Eigen::VectorXd xx(seeds_.get()), xy(seeds_.get()); int row = 0; for (auto &a : samples_) { int col = 0; for (auto &b : samples_) { auto r = glm::distance(a.first, b.first); A(row, col++) = shape_.get() + gaussian_.evaluate(r); } bx(row) = a.second.x; by(row++) = a.second.y; } auto solverX = A.llt(); auto solverY = A.llt(); xx = solverX.solve(bx); xy = solverY.solve(by); auto img = std::make_shared<Image>(size_.get(), DataVec4Float32::get()); vec4 *data = static_cast<vec4 *>(img->getColorLayer()->getEditableRepresentation<LayerRAM>()->getData()); int i = 0; for (int y = 0; y < size_.get().y; y++) { for (int x = 0; x < size_.get().x; x++) { dvec2 p(x, y); p /= size_.get(); p *= 2; p -= 1; vec3 v(0, 0, 0); int s = 0; for (; s < seeds_.get(); s++) { double r = glm::distance(p, samples_[s].first); auto w = gaussian_.evaluate(r); v.x += static_cast<float>(xx(s) * w); v.y += static_cast<float>(xy(s) * w); } data[i++] = vec4(v, 1.0f); } } vectorField_.setData(img); } dvec2 RBFVectorFieldGenerator2D::randomVector() { dvec2 v(1, 0); auto d = theta_(mt_); auto c = std::cos(d); auto s = std::sin(d); return (mat2(c, s, -s, c) * v) * static_cast<float>((x_(mt_) * 2 - 1)); } void RBFVectorFieldGenerator2D::createSamples() { samples_.clear(); if (useSameSeed_.get()) { mt_.seed(seed_.get()); } samples_.resize(seeds_.get()); std::generate(samples_.begin(), samples_.end(), [&]() { return std::make_pair(dvec2(x_(mt_), x_(mt_)), randomVector()); }); } void RBFVectorFieldGenerator2D::serialize(Serializer& s) const { std::vector<dvec2> sx; std::vector<dvec2> sy; for (auto s : samples_) { sx.push_back(s.first); sy.push_back(s.second); } s.serialize("samplesx", sx, "samplex"); s.serialize("samplesy", sy, "sampley"); Processor::serialize(s); } void RBFVectorFieldGenerator2D::deserialize(Deserializer& d) { std::vector<dvec2> sx; std::vector<dvec2> sy; d.deserialize("samplesx", sx, "samplex"); d.deserialize("samplesy", sy, "sampley"); for (size_t i = 0; i < sx.size(); i++) { samples_.emplace_back(sx[i], sy[i]); } Processor::deserialize(d); } } // namespace <commit_msg>VectorFieldVisualization: RBF2D VF Generator: Changed serialization order to actually use the serialized samples.<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "rbfvectorfieldgenerator2d.h" #include <inviwo/core/datastructures/volume/volumeram.h> #include <inviwo/core/datastructures/image/image.h> #include <inviwo/core/datastructures/image/layerram.h> #include <inviwo/core/datastructures/geometry/basicmesh.h> #include <warn/push> #include <warn/ignore/all> #include <Eigen/Dense> #include <warn/pop> namespace inviwo { const ProcessorInfo RBFVectorFieldGenerator2D::processorInfo_{ "org.inviwo.RBFVectorFieldGenerator2D", // Class identifier "RBF Based 2D Vector Field Generator", // Display name "Data Creation", // Category CodeState::Experimental, // Code state Tags::CPU, // Tags }; const ProcessorInfo RBFVectorFieldGenerator2D::getProcessorInfo() const { return processorInfo_; } RBFVectorFieldGenerator2D::RBFVectorFieldGenerator2D() : Processor() , vectorField_("vectorField", DataVec4Float32::get(), false) , size_("size", "Volume size", ivec2(700, 700), ivec2(1, 1), ivec2(1024, 1024)) , seeds_("seeds", "Number of seeds", 9, 1, 100) , shape_("shape", "Shape Parameter", 1.2f, 0.0001f, 10.0f, 0.0001f) , gaussian_("gaussian", "Gaussian") , randomness_("randomness", "Randomness") , useSameSeed_("useSameSeed", "Use same seed", true) , seed_("seed", "Seed", 1, 0, std::numeric_limits<int>::max()) , rd_() , mt_(rd_()) , theta_(0, 2 * M_PI) , x_(-1.0, 1.0) { addPort(vectorField_); addProperty(size_); addProperty(seeds_); addProperty(shape_); addProperty(gaussian_); addProperty(randomness_); randomness_.addProperty(useSameSeed_); randomness_.addProperty(seed_); useSameSeed_.onChange([&]() { seed_.setVisible(useSameSeed_.get()); samples_.clear(); }); seed_.onChange([&]() { samples_.clear(); }); } RBFVectorFieldGenerator2D::~RBFVectorFieldGenerator2D() {} void RBFVectorFieldGenerator2D::process() { if (samples_.size() != seeds_.get()) { createSamples(); } Eigen::MatrixXd A(seeds_.get(), seeds_.get()); Eigen::VectorXd bx(seeds_.get()), by(seeds_.get()); Eigen::VectorXd xx(seeds_.get()), xy(seeds_.get()); int row = 0; for (auto &a : samples_) { int col = 0; for (auto &b : samples_) { auto r = glm::distance(a.first, b.first); A(row, col++) = shape_.get() + gaussian_.evaluate(r); } bx(row) = a.second.x; by(row++) = a.second.y; } auto solverX = A.llt(); auto solverY = A.llt(); xx = solverX.solve(bx); xy = solverY.solve(by); auto img = std::make_shared<Image>(size_.get(), DataVec4Float32::get()); vec4 *data = static_cast<vec4 *>(img->getColorLayer()->getEditableRepresentation<LayerRAM>()->getData()); int i = 0; for (int y = 0; y < size_.get().y; y++) { for (int x = 0; x < size_.get().x; x++) { dvec2 p(x, y); p /= size_.get(); p *= 2; p -= 1; vec3 v(0, 0, 0); int s = 0; for (; s < seeds_.get(); s++) { double r = glm::distance(p, samples_[s].first); auto w = gaussian_.evaluate(r); v.x += static_cast<float>(xx(s) * w); v.y += static_cast<float>(xy(s) * w); } data[i++] = vec4(v, 1.0f); } } vectorField_.setData(img); } dvec2 RBFVectorFieldGenerator2D::randomVector() { dvec2 v(1, 0); auto d = theta_(mt_); auto c = std::cos(d); auto s = std::sin(d); return (mat2(c, s, -s, c) * v) * static_cast<float>((x_(mt_) * 2 - 1)); } void RBFVectorFieldGenerator2D::createSamples() { samples_.clear(); if (useSameSeed_.get()) { mt_.seed(seed_.get()); } samples_.resize(seeds_.get()); std::generate(samples_.begin(), samples_.end(), [&]() { return std::make_pair(dvec2(x_(mt_), x_(mt_)), randomVector()); }); } void RBFVectorFieldGenerator2D::serialize(Serializer& s) const { std::vector<dvec2> sx; std::vector<dvec2> sy; for (auto s : samples_) { sx.push_back(s.first); sy.push_back(s.second); } s.serialize("samplesx", sx, "samplex"); s.serialize("samplesy", sy, "sampley"); Processor::serialize(s); } void RBFVectorFieldGenerator2D::deserialize(Deserializer& d) { std::vector<dvec2> sx; std::vector<dvec2> sy; d.deserialize("samplesx", sx, "samplex"); d.deserialize("samplesy", sy, "sampley"); Processor::deserialize(d); for (size_t i = 0; i < sx.size(); i++) { samples_.emplace_back(sx[i], sy[i]); } } } // namespace <|endoftext|>
<commit_before> #include "stdafx.h" #include "SerialAsync.h" using namespace common; cSerialAsync::cSerialAsync() : m_isConnect(false) , m_isSendData(false) , m_sleepMillis(10) , m_threadLoop(true) { } cSerialAsync::~cSerialAsync() { Close(); } bool cSerialAsync::Open(const int portNum, const int baudRate) { RETV(m_serial.IsOpened(), true); if (!m_serial.Open(portNum, baudRate)) return false; m_isConnect = true; m_threadLoop = true; m_thread = std::thread(SerialThreadFunction, this); return true; } bool cSerialAsync::IsOpen() { return m_isConnect; } int cSerialAsync::SendData(BYTE *buffer, const int bufferLen) { if (BUFLEN > bufferLen) { AutoCSLock cs(m_cs); m_bufferLen = bufferLen; memcpy(m_buffer, buffer, bufferLen); m_isSendData = true; // ؾ Ѵ. return bufferLen; } return 0; } void cSerialAsync::Close() { m_isConnect = false; m_threadLoop = false; if (m_thread.joinable()) m_thread.join(); } unsigned cSerialAsync::SerialThreadFunction(cSerialAsync * serial) { char buffer[cSerialAsync::BUFLEN]; int bufferLen = 0; while (serial->m_threadLoop && serial->m_isConnect) { if (serial->m_isSendData) { AutoCSLock cs(serial->m_cs); bufferLen = serial->m_bufferLen; memcpy(buffer, serial->m_buffer, serial->m_bufferLen); serial->m_isSendData = false; } else { bufferLen = 0; } if (bufferLen > 0) serial->m_serial.SendData(buffer, bufferLen); Sleep(serial->m_sleepMillis); } serial->m_serial.Close(); return 0; } <commit_msg>update refactoring, seria<commit_after> #include "stdafx.h" #include "SerialAsync.h" using namespace common; cSerialAsync::cSerialAsync() : m_isConnect(false) , m_isSendData(false) , m_sleepMillis(10) , m_threadLoop(true) { } cSerialAsync::~cSerialAsync() { Close(); } bool cSerialAsync::Open(const int portNum, const int baudRate) { RETV(m_serial.IsOpened(), true); if (!m_serial.Open(portNum, baudRate)) return false; m_isConnect = true; m_threadLoop = true; m_thread = std::thread(SerialThreadFunction, this); return true; } bool cSerialAsync::IsOpen() { return m_isConnect; } int cSerialAsync::SendData(BYTE *buffer, const int bufferLen) { if (BUFLEN > bufferLen) { AutoCSLock cs(m_cs); m_bufferLen = bufferLen; memcpy(m_buffer, buffer, bufferLen); m_isSendData = true; // ؾ Ѵ. return bufferLen; } return 0; } void cSerialAsync::Close() { m_isConnect = false; m_threadLoop = false; if (m_thread.joinable()) m_thread.join(); } unsigned cSerialAsync::SerialThreadFunction(cSerialAsync * serial) { char buffer[cSerialAsync::BUFLEN]; int bufferLen = 0; while (serial->m_threadLoop && serial->m_isConnect) { if (serial->m_isSendData) { AutoCSLock cs(serial->m_cs); bufferLen = serial->m_bufferLen; memcpy(buffer, serial->m_buffer, serial->m_bufferLen); serial->m_isSendData = false; } else { bufferLen = 0; } if (bufferLen > 0) serial->m_serial.SendData(buffer, bufferLen); Sleep(serial->m_sleepMillis); } serial->m_serial.Close(); return 0; } <|endoftext|>
<commit_before>namespace mant { namespace bbob { class CompositeGriewankRosenbrockFunctionF8F2 : public BlackBoxOptimisationBenchmark { public: inline explicit CompositeGriewankRosenbrockFunctionF8F2( const unsigned int numberOfDimensions) noexcept; inline std::string toString() const noexcept override; protected: const double max_; inline double getObjectiveValueImplementation( const arma::Col<double>& parameter) const noexcept override; #if defined(MANTELLA_USE_PARALLEL) friend class cereal::access; template <typename Archive> void serialize( Archive& archive) noexcept { archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(this))); archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_)); } template <typename Archive> static void load_and_construct( Archive& archive, cereal::construct<CompositeGriewankRosenbrockFunctionF8F2>& construct) noexcept { unsigned int numberOfDimensions; archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions)); construct(numberOfDimensions); archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(construct.ptr()))); } #endif }; // // Implementation // inline CompositeGriewankRosenbrockFunctionF8F2::CompositeGriewankRosenbrockFunctionF8F2( const unsigned int numberOfDimensions) noexcept : BlackBoxOptimisationBenchmark2009(numberOfDimensions) { // A vector with all elements set to max(1, numberOfDimensions / 8). setParameterScaling(arma::zeros<arma::Col<double>>(numberOfDimensions_) + std::max(1.0, std::sqrt(static_cast<double>(numberOfDimensions_)) / 8.0)); // A vector with all elements set to 0.5. setParameterTranslation(arma::zeros<arma::Col<double>>(numberOfDimensions_) + 0.5); max_(std::max(1.0, std::sqrt(static_cast<double>(numberOfDimensions_)) / 8.0)){ setParameterRotation(getRandomRotationMatrix(numberOfDimensions_)); } inline double CompositeGriewankRosenbrockFunctionF8F2::getObjectiveValueImplementation( const arma::Col<double>& parameter) const noexcept { const arma::Col<double>& z = 100.0 * arma::square(arma::square(parameter.head(parameter.n_elem - 1)) - parameter.tail(parameter.n_elem - 1)) + arma::square(1.0 - parameter.head(parameter.n_elem - 1)); return 10.0 * (arma::mean(z / 4000.0 - arma::cos(z)) + 1); } inline std::string CompositeGriewankRosenbrockFunctionF8F2::toString() const noexcept { return "bbob_composite_griewank_rosenbrock_function_f8f2"; } } } #if defined(MANTELLA_USE_PARALLEL) CEREAL_REGISTER_TYPE(mant::bbob::CompositeGriewankRosenbrockFunctionF8F2); #endif <commit_msg>Fixed objective value calculation<commit_after>namespace mant { namespace bbob { class CompositeGriewankRosenbrockFunctionF8F2 : public BlackBoxOptimisationBenchmark { public: inline explicit CompositeGriewankRosenbrockFunctionF8F2( const unsigned int numberOfDimensions) noexcept; inline std::string toString() const noexcept override; protected: const double max_; inline double getObjectiveValueImplementation( const arma::Col<double>& parameter) const noexcept override; #if defined(MANTELLA_USE_PARALLEL) friend class cereal::access; template <typename Archive> void serialize( Archive& archive) noexcept { archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(this))); archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_)); } template <typename Archive> static void load_and_construct( Archive& archive, cereal::construct<CompositeGriewankRosenbrockFunctionF8F2>& construct) noexcept { unsigned int numberOfDimensions; archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions)); construct(numberOfDimensions); archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(construct.ptr()))); } #endif }; // // Implementation // inline CompositeGriewankRosenbrockFunctionF8F2::CompositeGriewankRosenbrockFunctionF8F2( const unsigned int numberOfDimensions) noexcept : BlackBoxOptimisationBenchmark(numberOfDimensions), max_(std::max(1.0, std::sqrt(static_cast<double>(numberOfDimensions_)) / 8.0)){ setParameterRotation(getRandomRotationMatrix(numberOfDimensions_)); } inline double CompositeGriewankRosenbrockFunctionF8F2::getObjectiveValueImplementation( const arma::Col<double>& parameter) const noexcept { const arma::Col<double>& s = max_ * parameter + 0.5; const arma::Col<double>& z = 100.0 * arma::square(arma::square(s.head(s.n_elem - 1)) - s.tail(s.n_elem - 1)) + arma::square(s.head(s.n_elem - 1) - 1.0); return 10.0 * (arma::mean(z / 4000.0 - arma::cos(z)) + 1); } inline std::string CompositeGriewankRosenbrockFunctionF8F2::toString() const noexcept { return "bbob_composite_griewank_rosenbrock_function_f8f2"; } } } #if defined(MANTELLA_USE_PARALLEL) CEREAL_REGISTER_TYPE(mant::bbob::CompositeGriewankRosenbrockFunctionF8F2); #endif <|endoftext|>
<commit_before>#include <SCD/CD/CD_Pair.h> #include <SCD/CD/CD_Simplex.h> #include <SCD/CD/CD_SimplexEnhanced.h> #include <iostream> //#ifndef NOGLUT //#define SHOW_LAST_SIMLPEX //#endif //#define CD_SAFE_VERSION //use when the scalar has a perfect precision #define PENETRATION_DEPTH //#define CD_PAIR_VERBOUS_MODE //#define CD_ITERATION_LIMIT 50 //use when the real-time constraints are too high fo current performances while keeping the same global precision. //no theoretical guarantee on the precision nor the collision-safeness when used - Default value is 20 #define _EPSILON_ 1e-24 #define _PRECISION_ 1e-6 using namespace SCD; inline Vector3 LinearSystem(Matrix3x3& A, Vector3& y) { Matrix3x3 B; A.Inversion(B); return (B*y); } CD_Pair::CD_Pair(S_Object *obj1, S_Object *obj2):sObj1_(obj1),sObj2_(obj2),lastDirection_(1.0,0.0,0.0), lastFeature1_(-1),lastFeature2_(-1),distance_(0),stamp1_(sObj1_->checkStamp()),stamp2_(sObj2_->checkStamp()), precision_(_PRECISION_),epsilon_(_EPSILON_),witPointsAreComputed_(false),s1_(Point3()),s2_(Point3()),s_(Point3()),sp_(Point3()),depthPair(obj1,obj2) { --stamp1_; --stamp2_; depthPair.setRelativePrecision(_PRECISION_); depthPair.setEpsilon(_EPSILON_); } CD_Pair::~CD_Pair(void) { } Scalar CD_Pair::getDistance() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { return distance_; } else { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); return distance_; } } Scalar CD_Pair::getDistanceWithoutPenetrationDepth() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { if (distance_ > 0) return distance_; return 0; } else { GJK(); if (collision_) return 0; return distance_; } } Scalar CD_Pair::reComputeClosestPoints(Point3& p1,Point3& p2) { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); witPoints(p1,p2); return distance_; } void CD_Pair::setRelativePrecision(Scalar s) { precision_=s*s; depthPair.setRelativePrecision(s); } void CD_Pair::setEpsilon(Scalar s) { epsilon_=s; depthPair.setEpsilon(s); } Scalar CD_Pair::getClosestPoints(Point3 &p1, Point3 &p2) { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { if (!witPointsAreComputed_) { witPointsAreComputed_=true; witPoints(p1,p2); } p1=p1_; p2=p2_; return distance_; } else { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); witPoints(p1,p2); witPointsAreComputed_=true; return distance_; } } Scalar CD_Pair::penetrationDepth() { #ifdef PENETRATION_DEPTH if (collision_)//Objects are in collision { distance_=-depthPair.getPenetrationDepth(lastDirection_,p1_,p2_,sp_,s1_,s2_); if (distance_<0) { lastDirection_.Set(0,1,0); } return distance_; } else { return distance_; } #else return distance_; #endif } Scalar CD_Pair::GJK() { Vector3& v=lastDirection_; #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"#####GJK START######"<<std::endl; #endif witPointsAreComputed_=false; int& lf1=lastFeature1_; int& lf2=lastFeature2_; Point3 sup1=sObj1_->support(v,lf1); Point3 sup2=sObj2_->support(-v,lf2); #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"Last features"<<lf1<<" "<<lf2<<std::endl; #endif Point3 sup(sup1); sup-=sup2; s1_=sup1; s2_=sup2; s_=sup; sp_=sup; CD_SimplexKeptPoints k; projectionComputed_=false; bool cont=true; Point3 proj; Vector3 S01; Vector3 S02; Scalar a1,a2,a3,a4,a5,a6; distance_=infinity; #ifdef CD_ITERATION_LIMIT int cnt=0; #endif while (cont) { #ifdef CD_ITERATION_LIMIT if (++cnt>CD_ITERATION_LIMIT) break; //the iterations number limit has been reached #endif switch (s_.getType()) { case CD_Triangle: { S01=s_[1]; S01-=s_[2]; S02=s_[0]; S02-=s_[2]; a1=S01*s_[0],a2=S01*s_[1],a3=S01*s_[2],a4=S02*s_[0],a5=S02*s_[1],a6=S02*s_[2]; lambda0_=a2*a6-a3*a5; lambda1_=a3*a4-a1*a6; lambda2_=a1*a5-a2*a4; det_=1/(lambda0_+lambda1_+lambda2_); lambda0_*=det_; lambda1_*=det_; lambda2_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_+s_[2]*lambda2_; v=-proj; break; } case CD_Segment: { S01=s_[1]; S01-=s_[0]; lambda0_=S01*s_[1]; lambda1_=-(S01*s_[0]); det_=1/(lambda0_+lambda1_); lambda0_*=det_; lambda1_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_; v=-proj; break; } default: { proj=s_[0]; v=-proj; } } Scalar newdist=v.normsquared(); if (distance_ <= newdist) //the distance is not monotonous { cont=false; } else if ( (distance_= newdist)<=sp_.farthestPointDistance()*epsilon_)//v is considered zero { collision_=true; cont=false; } else { sup1=sObj1_->support(v,lf1); sup2=sObj2_->support(-v,lf2); #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"Last features"<<lf1<<" "<<lf2<<std::endl; std::cout<<"supports"<<sup1<<" "<<sup2<<std::endl; # ifdef CD_ITERATION_LIMIT std::cout<<"Iterations"<<cnt<<std::endl; # endif #endif sup=sup1; sup-=sup2; if ((distance_-proj*sup)<(precision_*distance_))//precision reached { collision_=false; cont=false; projectionComputed_=true; } else { sp_+=sup; sp_.updateVectors(); #ifndef SAFE_VERSION if (sp_.isAffinelyDependent()) { cont=false; collision_=false; projectionComputed_=true; } else #endif { sp_.getClosestSubSimplexGJK(k); sp_.filter(k); s1_+=sup1; s2_+=sup2; if (sp_.getType()==CD_Tetrahedron) { cont=false; s1_+=sup1; s2_+=sup2; collision_=true; } else { s_=sp_; s1_.filter(k); s2_.filter(k); } } } } } #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"#####GJK END######"<<std::endl; #endif return distance_; } void CD_Pair::setVector(const Vector3 &v) { lastDirection_=v; } void CD_Pair::witPoints(Point3 &p1, Point3 &p2) { Point3 proj; Vector3& v=lastDirection_; if (collision_) { p1=p1_; p2=p2_; return; } switch (s_.getType()) { case CD_Triangle: { { if (!projectionComputed_) { Vector3 S01(s_[1]-s_[2]), S02(s_[0]-s_[2]); Scalar a1=S01*s_[0],a2=S01*s_[1],a3=S01*s_[2],a4=S02*s_[0],a5=S02*s_[1],a6=S02*s_[2]; lambda0_=a2*a6-a3*a5; lambda1_=a3*a4-a1*a6; lambda2_=a1*a5-a2*a4; det_=1/(lambda0_+lambda1_+lambda2_); lambda0_*=det_; lambda1_*=det_; lambda2_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_+s_[2]*lambda2_; v=-proj; } p1_=p1=s1_[0]*lambda0_+s1_[1]*lambda1_+s1_[2]*lambda2_; p2_=p2=s2_[0]*lambda0_+s2_[1]*lambda1_+s2_[2]*lambda2_; } #ifdef SHOW_LAST_SIMLPEX glDisable(GL_DEPTH_TEST); glColor4d(0,0.5,1,0.5); glBegin(GL_TRIANGLES); glVertex3d(s1_[0][0],s1_[0][1],s1_[0][2]); glVertex3d(s1_[1][0],s1_[1][1],s1_[1][2]); glVertex3d(s1_[2][0],s1_[2][1],s1_[2][2]); glVertex3d(s2_[0][0],s2_[0][1],s2_[0][2]); glVertex3d(s2_[1][0],s2_[1][1],s2_[1][2]); glVertex3d(s2_[2][0],s2_[2][1],s2_[2][2]); glEnd(); glEnable(GL_DEPTH_TEST); #endif return; } case CD_Segment: { if (!projectionComputed_) { Vector3 S01(s_[1]-s_[0]); lambda1_=-(S01*s_[0]); lambda0_=S01*s_[1]; det_=1/(lambda0_+lambda1_); lambda0_*=det_; lambda1_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_; v=-proj; } p1_=p1=s1_[0]*lambda0_+s1_[1]*lambda1_; p2_=p2=s2_[0]*lambda0_+s2_[1]*lambda1_; #ifdef SHOW_LAST_SIMLPEX glDisable(GL_DEPTH_TEST); glColor4d(0,0.5,1,0.5); glBegin(GL_LINES); glVertex3d(s1_[0][0],s1_[0][1],s1_[0][2]); glVertex3d(s1_[1][0],s1_[1][1],s1_[1][2]); glVertex3d(s2_[0][0],s2_[0][1],s2_[0][2]); glVertex3d(s2_[1][0],s2_[1][1],s2_[1][2]); glEnd(); glEnable(GL_DEPTH_TEST); #endif return ; } default: { p1_=p1=s1_[0]; p2_=p2=s2_[0]; return ; } } } bool CD_Pair::isInCollision() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { return collision_; } else { Scalar prec=precision_; precision_=1; GJK(); precision_=prec; return collision_; } } <commit_msg>Improve indentation.<commit_after>#include <SCD/CD/CD_Pair.h> #include <SCD/CD/CD_Simplex.h> #include <SCD/CD/CD_SimplexEnhanced.h> #include <iostream> //#ifndef NOGLUT //#define SHOW_LAST_SIMLPEX //#endif //#define CD_SAFE_VERSION //use when the scalar has a perfect precision #define PENETRATION_DEPTH //#define CD_PAIR_VERBOUS_MODE //#define CD_ITERATION_LIMIT 50 //use when the real-time constraints are too high fo current performances while keeping the same global precision. //no theoretical guarantee on the precision nor the collision-safeness when used - Default value is 20 #define _EPSILON_ 1e-24 #define _PRECISION_ 1e-6 using namespace SCD; inline Vector3 LinearSystem(Matrix3x3& A, Vector3& y) { Matrix3x3 B; A.Inversion(B); return (B*y); } CD_Pair::CD_Pair(S_Object *obj1, S_Object *obj2):sObj1_(obj1),sObj2_(obj2),lastDirection_(1.0,0.0,0.0), lastFeature1_(-1),lastFeature2_(-1),distance_(0),stamp1_(sObj1_->checkStamp()),stamp2_(sObj2_->checkStamp()), precision_(_PRECISION_),epsilon_(_EPSILON_),witPointsAreComputed_(false),s1_(Point3()),s2_(Point3()),s_(Point3()),sp_(Point3()),depthPair(obj1,obj2) { --stamp1_; --stamp2_; depthPair.setRelativePrecision(_PRECISION_); depthPair.setEpsilon(_EPSILON_); } CD_Pair::~CD_Pair(void) { } Scalar CD_Pair::getDistance() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { return distance_; } else { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); return distance_; } } Scalar CD_Pair::getDistanceWithoutPenetrationDepth() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { if (distance_ > 0) return distance_; return 0; } else { GJK(); if (collision_) return 0; return distance_; } } Scalar CD_Pair::reComputeClosestPoints(Point3& p1,Point3& p2) { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); witPoints(p1,p2); return distance_; } void CD_Pair::setRelativePrecision(Scalar s) { precision_=s*s; depthPair.setRelativePrecision(s); } void CD_Pair::setEpsilon(Scalar s) { epsilon_=s; depthPair.setEpsilon(s); } Scalar CD_Pair::getClosestPoints(Point3 &p1, Point3 &p2) { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { if (!witPointsAreComputed_) { witPointsAreComputed_=true; witPoints(p1,p2); } p1=p1_; p2=p2_; return distance_; } else { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); witPoints(p1,p2); witPointsAreComputed_=true; return distance_; } } Scalar CD_Pair::penetrationDepth() { #ifdef PENETRATION_DEPTH if (collision_)//Objects are in collision { distance_=-depthPair.getPenetrationDepth(lastDirection_,p1_,p2_,sp_,s1_,s2_); if (distance_<0) { lastDirection_.Set(0,1,0); } return distance_; } else { return distance_; } #else return distance_; #endif } Scalar CD_Pair::GJK() { Vector3& v=lastDirection_; #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"#####GJK START######"<<std::endl; #endif witPointsAreComputed_=false; int& lf1=lastFeature1_; int& lf2=lastFeature2_; Point3 sup1=sObj1_->support(v,lf1); Point3 sup2=sObj2_->support(-v,lf2); #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"Last features"<<lf1<<" "<<lf2<<std::endl; #endif Point3 sup(sup1); sup-=sup2; s1_=sup1; s2_=sup2; s_=sup; sp_=sup; CD_SimplexKeptPoints k; projectionComputed_=false; bool cont=true; Point3 proj; Vector3 S01; Vector3 S02; Scalar a1,a2,a3,a4,a5,a6; distance_=infinity; #ifdef CD_ITERATION_LIMIT int cnt=0; #endif while (cont) { #ifdef CD_ITERATION_LIMIT if (++cnt>CD_ITERATION_LIMIT) break; //the iterations number limit has been reached #endif switch (s_.getType()) { case CD_Triangle: { S01=s_[1]; S01-=s_[2]; S02=s_[0]; S02-=s_[2]; a1=S01*s_[0],a2=S01*s_[1],a3=S01*s_[2],a4=S02*s_[0],a5=S02*s_[1],a6=S02*s_[2]; lambda0_=a2*a6-a3*a5; lambda1_=a3*a4-a1*a6; lambda2_=a1*a5-a2*a4; det_=1/(lambda0_+lambda1_+lambda2_); lambda0_*=det_; lambda1_*=det_; lambda2_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_+s_[2]*lambda2_; v=-proj; break; } case CD_Segment: { S01=s_[1]; S01-=s_[0]; lambda0_=S01*s_[1]; lambda1_=-(S01*s_[0]); det_=1/(lambda0_+lambda1_); lambda0_*=det_; lambda1_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_; v=-proj; break; } default: { proj=s_[0]; v=-proj; } } Scalar newdist=v.normsquared(); if (distance_ <= newdist) //the distance is not monotonous { cont=false; } else { if ( (distance_= newdist)<=sp_.farthestPointDistance()*epsilon_)//v is considered zero { collision_=true; cont=false; } else { sup1=sObj1_->support(v,lf1); sup2=sObj2_->support(-v,lf2); #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"Last features"<<lf1<<" "<<lf2<<std::endl; std::cout<<"supports"<<sup1<<" "<<sup2<<std::endl; # ifdef CD_ITERATION_LIMIT std::cout<<"Iterations"<<cnt<<std::endl; # endif #endif sup=sup1; sup-=sup2; if ((distance_-proj*sup)<(precision_*distance_))//precision reached { collision_=false; cont=false; projectionComputed_=true; } else { sp_+=sup; sp_.updateVectors(); #ifndef SAFE_VERSION if (sp_.isAffinelyDependent()) { cont=false; collision_=false; projectionComputed_=true; } else #endif { sp_.getClosestSubSimplexGJK(k); sp_.filter(k); s1_+=sup1; s2_+=sup2; if (sp_.getType()==CD_Tetrahedron) { cont=false; s1_+=sup1; s2_+=sup2; collision_=true; } else { s_=sp_; s1_.filter(k); s2_.filter(k); } } } } } } #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"#####GJK END######"<<std::endl; #endif return distance_; } void CD_Pair::setVector(const Vector3 &v) { lastDirection_=v; } void CD_Pair::witPoints(Point3 &p1, Point3 &p2) { Point3 proj; Vector3& v=lastDirection_; if (collision_) { p1=p1_; p2=p2_; return; } switch (s_.getType()) { case CD_Triangle: { { if (!projectionComputed_) { Vector3 S01(s_[1]-s_[2]), S02(s_[0]-s_[2]); Scalar a1=S01*s_[0],a2=S01*s_[1],a3=S01*s_[2],a4=S02*s_[0],a5=S02*s_[1],a6=S02*s_[2]; lambda0_=a2*a6-a3*a5; lambda1_=a3*a4-a1*a6; lambda2_=a1*a5-a2*a4; det_=1/(lambda0_+lambda1_+lambda2_); lambda0_*=det_; lambda1_*=det_; lambda2_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_+s_[2]*lambda2_; v=-proj; } p1_=p1=s1_[0]*lambda0_+s1_[1]*lambda1_+s1_[2]*lambda2_; p2_=p2=s2_[0]*lambda0_+s2_[1]*lambda1_+s2_[2]*lambda2_; } #ifdef SHOW_LAST_SIMLPEX glDisable(GL_DEPTH_TEST); glColor4d(0,0.5,1,0.5); glBegin(GL_TRIANGLES); glVertex3d(s1_[0][0],s1_[0][1],s1_[0][2]); glVertex3d(s1_[1][0],s1_[1][1],s1_[1][2]); glVertex3d(s1_[2][0],s1_[2][1],s1_[2][2]); glVertex3d(s2_[0][0],s2_[0][1],s2_[0][2]); glVertex3d(s2_[1][0],s2_[1][1],s2_[1][2]); glVertex3d(s2_[2][0],s2_[2][1],s2_[2][2]); glEnd(); glEnable(GL_DEPTH_TEST); #endif return; } case CD_Segment: { if (!projectionComputed_) { Vector3 S01(s_[1]-s_[0]); lambda1_=-(S01*s_[0]); lambda0_=S01*s_[1]; det_=1/(lambda0_+lambda1_); lambda0_*=det_; lambda1_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_; v=-proj; } p1_=p1=s1_[0]*lambda0_+s1_[1]*lambda1_; p2_=p2=s2_[0]*lambda0_+s2_[1]*lambda1_; #ifdef SHOW_LAST_SIMLPEX glDisable(GL_DEPTH_TEST); glColor4d(0,0.5,1,0.5); glBegin(GL_LINES); glVertex3d(s1_[0][0],s1_[0][1],s1_[0][2]); glVertex3d(s1_[1][0],s1_[1][1],s1_[1][2]); glVertex3d(s2_[0][0],s2_[0][1],s2_[0][2]); glVertex3d(s2_[1][0],s2_[1][1],s2_[1][2]); glEnd(); glEnable(GL_DEPTH_TEST); #endif return ; } default: { p1_=p1=s1_[0]; p2_=p2=s2_[0]; return ; } } } bool CD_Pair::isInCollision() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { return collision_; } else { Scalar prec=precision_; precision_=1; GJK(); precision_=prec; return collision_; } } <|endoftext|>
<commit_before>/* * File: main_voctreeLocalizer.cpp * Author: sgaspari * * Created on September 12, 2015, 3:16 PM */ #include <openMVG/localization/VoctreeLocalizer.hpp> #include <openMVG/localization/LocalizationResult.hpp> #include <openMVG/localization/optimization.hpp> #include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/features/image_describer.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/program_options.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/min.hpp> #include <boost/accumulators/statistics/max.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <iostream> #include <string> #include <chrono> #if HAVE_ALEMBIC #include <openMVG/dataio/AlembicExporter.hpp> #endif // HAVE_ALEMBIC #define POPART_COUT(x) std::cout << x << std::endl #define POPART_CERR(x) std::cerr << x << std::endl namespace bfs = boost::filesystem; namespace bacc = boost::accumulators; namespace po = boost::program_options; using namespace openMVG; std::string myToString(std::size_t i, std::size_t zeroPadding) { std::stringstream ss; ss << std::setw(zeroPadding) << std::setfill('0') << i; return ss.str(); } int main(int argc, char** argv) { std::string calibFile; //< the calibration file std::string sfmFilePath; //< the OpenMVG .json data file std::string descriptorsFolder; //< the OpenMVG .json data file std::string vocTreeFilepath; //< the vocabulary tree file std::string weightsFilepath; //< the vocabulary tree weights file std::string mediaFilepath; //< the media file to localize localization::VoctreeLocalizer::Parameters param = localization::VoctreeLocalizer::Parameters(); std::string preset = features::describerPreset_enumToString(param._featurePreset); //< the preset for the feature extractor #if HAVE_ALEMBIC std::string exportFile = "trackedcameras.abc"; //!< the export file #endif #if HAVE_CCTAG bool useSIFT_CCTAG = false; #endif std::string algostring = "FirstBest"; bool globalBundle = false; ///< If !param._refineIntrinsics it can run a final global budndle to refine the scene po::options_description desc( "This program takes as input a media (image, image sequence, video) and a database (voctree, 3D structure data) \n" "and returns for each frame a pose estimation for the camera."); desc.add_options() ("help,h", "Print this message") ("results,r", po::value<size_t>(&param._numResults)->default_value(param._numResults), "Number of images to retrieve in database") ("maxResults", po::value<size_t>(&param._maxResults)->default_value(param._maxResults), "For algorithm AllResults, it stops the image matching when this number of matched images is reached. If 0 it is ignored.") ("commonviews", po::value<size_t>(&param._numCommonViews)->default_value(param._numCommonViews), "Number of minimum images in which a point must be seen to be used in cluster tracking") ("preset", po::value<std::string>(&preset)->default_value(preset), "Preset for the feature extractor when localizing a new image {LOW,NORMAL,HIGH,ULTRA}") ("calibration,c", po::value<std::string>(&calibFile)/*->required( )*/, "Calibration file") ("voctree,t", po::value<std::string>(&vocTreeFilepath)->required(), "Filename for the vocabulary tree") ("weights,w", po::value<std::string>(&weightsFilepath), "Filename for the vocabulary tree weights") ("sfmdata,d", po::value<std::string>(&sfmFilePath)->required(), "The sfm_data.json kind of file generated by OpenMVG [it could be also a bundle.out to use an older version of OpenMVG]") ("siftPath,s", po::value<std::string>(&descriptorsFolder)->required(), "Folder containing the .desc [for the older version of openMVG it is the list.txt].") ("algorithm", po::value<std::string>(&algostring)->default_value(algostring), "Algorithm type: FirstBest=0, BestResult=1, AllResults=2, Cluster=3" ) ("mediafile,m", po::value<std::string>(&mediaFilepath)->required(), "The folder path or the filename for the media to track") ("refineIntrinsics", po::bool_switch(&param._refineIntrinsics), "Enable/Disable camera intrinsics refinement for each localized image") ("globalBundle", po::bool_switch(&globalBundle), "If --refineIntrinsics is not set, this option allows to run a final global budndle adjustment to refine the scene") ("visualDebug", po::value<std::string>(&param._visualDebug), "If a directory is provided it enables visual debug and saves all the debugging info in that directory") #if HAVE_ALEMBIC ("export,e", po::value<std::string>(&exportFile)->default_value(exportFile), "Filename for the SfM_Data export file (where camera poses will be stored). Default : trackedcameras.json If Alambic is enable it will also export an .abc file of the scene with the same name") #endif #if HAVE_CCTAG ("useSIFT_CCTAG", po::bool_switch(&useSIFT_CCTAG), "If provided, for each image it will extract both SIFT and the CCTAG.") #endif ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("help") || (argc == 1)) { POPART_COUT(desc); return EXIT_SUCCESS; } po::notify(vm); } catch(boost::program_options::required_option& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } catch(boost::program_options::error& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } if(vm.count("algorithm")) { param._algorithm = localization::VoctreeLocalizer::initFromString(algostring); } if(vm.count("preset")) { param._featurePreset = features::describerPreset_stringToEnum(preset); } { // the bundle adjustment can be run for now only if the refine intrinsics option is not set globalBundle = (globalBundle && !param._refineIntrinsics); POPART_COUT("Program called with the following parameters:"); POPART_COUT("\tvoctree: " << vocTreeFilepath); POPART_COUT("\tweights: " << weightsFilepath); POPART_COUT("\tcalibration: " << calibFile); POPART_COUT("\tsfmdata: " << sfmFilePath); POPART_COUT("\tmediafile: " << mediaFilepath); POPART_COUT("\tsiftPath: " << descriptorsFolder); POPART_COUT("\tresults: " << param._numResults); POPART_COUT("\tcommon views: " << param._numCommonViews); POPART_COUT("\trefineIntrinsics: " << param._refineIntrinsics); POPART_COUT("\tpreset: " << features::describerPreset_enumToString(param._featurePreset)); POPART_COUT("\tglobalBundle: " << globalBundle); POPART_COUT("\tvisualDebug: " << param._visualDebug); POPART_COUT("\talgorithm: " << param._algorithm); #if HAVE_CCTAG POPART_COUT("\tuseSIFT_CCTAG: " << useSIFT_CCTAG); #endif } if((!param._visualDebug.empty()) && (!bfs::exists(param._visualDebug))) { bfs::create_directories(param._visualDebug); } // init the localizer localization::VoctreeLocalizer localizer(sfmFilePath, descriptorsFolder, vocTreeFilepath, weightsFilepath #if HAVE_CCTAG , useSIFT_CCTAG #endif ); bool isInit = localizer.isInit(); if(!isInit) { POPART_CERR("ERROR while initializing the localizer!"); return EXIT_FAILURE; } // create the feedProvider dataio::FeedProvider feed(mediaFilepath, calibFile); if(!feed.isInit()) { POPART_CERR("ERROR while initializing the FeedProvider!"); return EXIT_FAILURE; } #if HAVE_ALEMBIC dataio::AlembicExporter exporter( exportFile ); exporter.addPoints(localizer.getSfMData().GetLandmarks()); #endif image::Image<unsigned char> imageGrey; cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; bool hasIntrinsics = false; size_t frameCounter = 0; size_t goodFrameCounter = 0; vector<string> goodFrameList; std::string currentImgName; // Define an accumulator set for computing the mean and the // standard deviation of the time taken for localization bacc::accumulator_set<double, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::sum > > stats; std::vector<localization::LocalizationResult> vec_localizationResults; while(feed.next(imageGrey, queryIntrinsics, currentImgName, hasIntrinsics)) { POPART_COUT("******************************"); POPART_COUT("FRAME " << myToString(frameCounter,4)); POPART_COUT("******************************"); localization::LocalizationResult localizationResult; auto detect_start = std::chrono::steady_clock::now(); localizer.localize(imageGrey, &param, hasIntrinsics /*useInputIntrinsics*/, queryIntrinsics, localizationResult, currentImgName); auto detect_end = std::chrono::steady_clock::now(); auto detect_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(detect_end - detect_start); POPART_COUT("\nLocalization took " << detect_elapsed.count() << " [ms]"); stats(detect_elapsed.count()); // save data if(localizationResult.isValid()) { #if HAVE_ALEMBIC exporter.appendCamera("camera."+myToString(frameCounter,4), localizationResult.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif if(globalBundle) { vec_localizationResults.emplace_back(localizationResult); } goodFrameCounter++; goodFrameList.push_back(currentImgName + " : " + std::to_string(localizationResult.getIndMatch3D2D().size()) ); } else { #if HAVE_ALEMBIC // @fixme for now just add a fake camera so that it still can be see in MAYA exporter.appendCamera("camera.V."+myToString(frameCounter,4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif POPART_CERR("Unable to localize frame " << frameCounter); } ++frameCounter; } if(globalBundle) { POPART_COUT("\n\n\n***********************************************"); POPART_COUT("Bundle Adjustment - Refining the whole sequence"); POPART_COUT("***********************************************\n\n"); // run a bundle adjustment const bool BAresult = localization::refineSequence(vec_localizationResults, true, true); if(!BAresult) { POPART_CERR("Bundle Adjustment failed!"); } else { #if HAVE_ALEMBIC // now copy back in a new abc with the same name file and BUNDLE appended at the end dataio::AlembicExporter exporterBA( bfs::path(exportFile).stem().string()+".BUNDLE.abc" ); size_t idx = 0; for(const localization::LocalizationResult &res : vec_localizationResults) { if(res.isValid()) { assert(idx < vec_localizationResults.size()); // exporterBA.appendCamera("camera."+myToString(idx,4), res.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); exporterBA.appendCamera("camera."+myToString(idx,4), res.getPose(), &res.getIntrinsics(), mediaFilepath, frameCounter, frameCounter); } else { exporterBA.appendCamera("camera.V."+myToString(idx,4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } idx++; } exporterBA.addPoints(localizer.getSfMData().GetLandmarks()); #endif } } // print out some time stats POPART_COUT("\n\n******************************"); POPART_COUT("Localized " << goodFrameCounter << "/" << frameCounter << " images"); POPART_COUT("Images localized with the number of 2D/3D matches during localization :"); for(int i = 0; i < goodFrameList.size(); i++) POPART_COUT(goodFrameList[i]); POPART_COUT("Processing took " << bacc::sum(stats)/1000 << " [s] overall"); POPART_COUT("Mean time for localization: " << bacc::mean(stats) << " [ms]"); POPART_COUT("Max time for localization: " << bacc::max(stats) << " [ms]"); POPART_COUT("Min time for localization: " << bacc::min(stats) << " [ms]"); } <commit_msg>[localization] saving the current image path in alembic<commit_after>/* * File: main_voctreeLocalizer.cpp * Author: sgaspari * * Created on September 12, 2015, 3:16 PM */ #include <openMVG/localization/VoctreeLocalizer.hpp> #include <openMVG/localization/LocalizationResult.hpp> #include <openMVG/localization/optimization.hpp> #include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/features/image_describer.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/program_options.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/min.hpp> #include <boost/accumulators/statistics/max.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <iostream> #include <string> #include <chrono> #if HAVE_ALEMBIC #include <openMVG/dataio/AlembicExporter.hpp> #endif // HAVE_ALEMBIC #define POPART_COUT(x) std::cout << x << std::endl #define POPART_CERR(x) std::cerr << x << std::endl namespace bfs = boost::filesystem; namespace bacc = boost::accumulators; namespace po = boost::program_options; using namespace openMVG; std::string myToString(std::size_t i, std::size_t zeroPadding) { std::stringstream ss; ss << std::setw(zeroPadding) << std::setfill('0') << i; return ss.str(); } int main(int argc, char** argv) { std::string calibFile; //< the calibration file std::string sfmFilePath; //< the OpenMVG .json data file std::string descriptorsFolder; //< the OpenMVG .json data file std::string vocTreeFilepath; //< the vocabulary tree file std::string weightsFilepath; //< the vocabulary tree weights file std::string mediaFilepath; //< the media file to localize localization::VoctreeLocalizer::Parameters param = localization::VoctreeLocalizer::Parameters(); std::string preset = features::describerPreset_enumToString(param._featurePreset); //< the preset for the feature extractor #if HAVE_ALEMBIC std::string exportFile = "trackedcameras.abc"; //!< the export file #endif #if HAVE_CCTAG bool useSIFT_CCTAG = false; #endif std::string algostring = "FirstBest"; bool globalBundle = false; ///< If !param._refineIntrinsics it can run a final global budndle to refine the scene po::options_description desc( "This program takes as input a media (image, image sequence, video) and a database (voctree, 3D structure data) \n" "and returns for each frame a pose estimation for the camera."); desc.add_options() ("help,h", "Print this message") ("results,r", po::value<size_t>(&param._numResults)->default_value(param._numResults), "Number of images to retrieve in database") ("maxResults", po::value<size_t>(&param._maxResults)->default_value(param._maxResults), "For algorithm AllResults, it stops the image matching when this number of matched images is reached. If 0 it is ignored.") ("commonviews", po::value<size_t>(&param._numCommonViews)->default_value(param._numCommonViews), "Number of minimum images in which a point must be seen to be used in cluster tracking") ("preset", po::value<std::string>(&preset)->default_value(preset), "Preset for the feature extractor when localizing a new image {LOW,NORMAL,HIGH,ULTRA}") ("calibration,c", po::value<std::string>(&calibFile)/*->required( )*/, "Calibration file") ("voctree,t", po::value<std::string>(&vocTreeFilepath)->required(), "Filename for the vocabulary tree") ("weights,w", po::value<std::string>(&weightsFilepath), "Filename for the vocabulary tree weights") ("sfmdata,d", po::value<std::string>(&sfmFilePath)->required(), "The sfm_data.json kind of file generated by OpenMVG [it could be also a bundle.out to use an older version of OpenMVG]") ("siftPath,s", po::value<std::string>(&descriptorsFolder)->required(), "Folder containing the .desc [for the older version of openMVG it is the list.txt].") ("algorithm", po::value<std::string>(&algostring)->default_value(algostring), "Algorithm type: FirstBest=0, BestResult=1, AllResults=2, Cluster=3" ) ("mediafile,m", po::value<std::string>(&mediaFilepath)->required(), "The folder path or the filename for the media to track") ("refineIntrinsics", po::bool_switch(&param._refineIntrinsics), "Enable/Disable camera intrinsics refinement for each localized image") ("globalBundle", po::bool_switch(&globalBundle), "If --refineIntrinsics is not set, this option allows to run a final global budndle adjustment to refine the scene") ("visualDebug", po::value<std::string>(&param._visualDebug), "If a directory is provided it enables visual debug and saves all the debugging info in that directory") #if HAVE_ALEMBIC ("export,e", po::value<std::string>(&exportFile)->default_value(exportFile), "Filename for the SfM_Data export file (where camera poses will be stored). Default : trackedcameras.json If Alambic is enable it will also export an .abc file of the scene with the same name") #endif #if HAVE_CCTAG ("useSIFT_CCTAG", po::bool_switch(&useSIFT_CCTAG), "If provided, for each image it will extract both SIFT and the CCTAG.") #endif ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("help") || (argc == 1)) { POPART_COUT(desc); return EXIT_SUCCESS; } po::notify(vm); } catch(boost::program_options::required_option& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } catch(boost::program_options::error& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } if(vm.count("algorithm")) { param._algorithm = localization::VoctreeLocalizer::initFromString(algostring); } if(vm.count("preset")) { param._featurePreset = features::describerPreset_stringToEnum(preset); } { // the bundle adjustment can be run for now only if the refine intrinsics option is not set globalBundle = (globalBundle && !param._refineIntrinsics); POPART_COUT("Program called with the following parameters:"); POPART_COUT("\tvoctree: " << vocTreeFilepath); POPART_COUT("\tweights: " << weightsFilepath); POPART_COUT("\tcalibration: " << calibFile); POPART_COUT("\tsfmdata: " << sfmFilePath); POPART_COUT("\tmediafile: " << mediaFilepath); POPART_COUT("\tsiftPath: " << descriptorsFolder); POPART_COUT("\tresults: " << param._numResults); POPART_COUT("\tcommon views: " << param._numCommonViews); POPART_COUT("\trefineIntrinsics: " << param._refineIntrinsics); POPART_COUT("\tpreset: " << features::describerPreset_enumToString(param._featurePreset)); POPART_COUT("\tglobalBundle: " << globalBundle); POPART_COUT("\tvisualDebug: " << param._visualDebug); POPART_COUT("\talgorithm: " << param._algorithm); #if HAVE_CCTAG POPART_COUT("\tuseSIFT_CCTAG: " << useSIFT_CCTAG); #endif } if((!param._visualDebug.empty()) && (!bfs::exists(param._visualDebug))) { bfs::create_directories(param._visualDebug); } // init the localizer localization::VoctreeLocalizer localizer(sfmFilePath, descriptorsFolder, vocTreeFilepath, weightsFilepath #if HAVE_CCTAG , useSIFT_CCTAG #endif ); bool isInit = localizer.isInit(); if(!isInit) { POPART_CERR("ERROR while initializing the localizer!"); return EXIT_FAILURE; } // create the feedProvider dataio::FeedProvider feed(mediaFilepath, calibFile); if(!feed.isInit()) { POPART_CERR("ERROR while initializing the FeedProvider!"); return EXIT_FAILURE; } #if HAVE_ALEMBIC dataio::AlembicExporter exporter( exportFile ); exporter.addPoints(localizer.getSfMData().GetLandmarks()); #endif image::Image<unsigned char> imageGrey; cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; bool hasIntrinsics = false; size_t frameCounter = 0; size_t goodFrameCounter = 0; vector<string> goodFrameList; std::string currentImgName; // Define an accumulator set for computing the mean and the // standard deviation of the time taken for localization bacc::accumulator_set<double, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::sum > > stats; std::vector<localization::LocalizationResult> vec_localizationResults; while(feed.next(imageGrey, queryIntrinsics, currentImgName, hasIntrinsics)) { POPART_COUT("******************************"); POPART_COUT("FRAME " << myToString(frameCounter,4)); POPART_COUT("******************************"); localization::LocalizationResult localizationResult; auto detect_start = std::chrono::steady_clock::now(); localizer.localize(imageGrey, &param, hasIntrinsics /*useInputIntrinsics*/, queryIntrinsics, localizationResult, currentImgName); auto detect_end = std::chrono::steady_clock::now(); auto detect_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(detect_end - detect_start); POPART_COUT("\nLocalization took " << detect_elapsed.count() << " [ms]"); stats(detect_elapsed.count()); // save data if(localizationResult.isValid()) { #if HAVE_ALEMBIC exporter.appendCamera("camera."+myToString(frameCounter,4), localizationResult.getPose(), &queryIntrinsics, currentImgName, frameCounter, frameCounter); #endif if(globalBundle) { vec_localizationResults.emplace_back(localizationResult); } goodFrameCounter++; goodFrameList.push_back(currentImgName + " : " + std::to_string(localizationResult.getIndMatch3D2D().size()) ); } else { #if HAVE_ALEMBIC // @fixme for now just add a fake camera so that it still can be see in MAYA exporter.appendCamera("camera.V."+myToString(frameCounter,4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif POPART_CERR("Unable to localize frame " << frameCounter); } ++frameCounter; } if(globalBundle) { POPART_COUT("\n\n\n***********************************************"); POPART_COUT("Bundle Adjustment - Refining the whole sequence"); POPART_COUT("***********************************************\n\n"); // run a bundle adjustment const bool BAresult = localization::refineSequence(vec_localizationResults, true, true); if(!BAresult) { POPART_CERR("Bundle Adjustment failed!"); } else { #if HAVE_ALEMBIC // now copy back in a new abc with the same name file and BUNDLE appended at the end dataio::AlembicExporter exporterBA( bfs::path(exportFile).stem().string()+".BUNDLE.abc" ); size_t idx = 0; for(const localization::LocalizationResult &res : vec_localizationResults) { if(res.isValid()) { assert(idx < vec_localizationResults.size()); // exporterBA.appendCamera("camera."+myToString(idx,4), res.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); exporterBA.appendCamera("camera."+myToString(idx,4), res.getPose(), &res.getIntrinsics(), mediaFilepath, frameCounter, frameCounter); } else { exporterBA.appendCamera("camera.V."+myToString(idx,4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } idx++; } exporterBA.addPoints(localizer.getSfMData().GetLandmarks()); #endif } } // print out some time stats POPART_COUT("\n\n******************************"); POPART_COUT("Localized " << goodFrameCounter << "/" << frameCounter << " images"); POPART_COUT("Images localized with the number of 2D/3D matches during localization :"); for(int i = 0; i < goodFrameList.size(); i++) POPART_COUT(goodFrameList[i]); POPART_COUT("Processing took " << bacc::sum(stats)/1000 << " [s] overall"); POPART_COUT("Mean time for localization: " << bacc::mean(stats) << " [ms]"); POPART_COUT("Max time for localization: " << bacc::max(stats) << " [ms]"); POPART_COUT("Min time for localization: " << bacc::min(stats) << " [ms]"); } <|endoftext|>
<commit_before>/* Copyright (c) 2008 Pradeepto K. Bhattacharya <pradeepto@kde.org> ( adapted from kdepim/kmail/kmfolderseldlg.cpp and simplefoldertree.h ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "treebase.h" #include "kmfolder.h" #include "kmfoldertree.h" #include "simplefoldertree.h" #include <kdebug.h> #include <klistview.h> using namespace KMail; TreeBase::TreeBase( QWidget *parent, KMFolderTree *folderTree, const QString &preSelection, bool mustBeReadWrite ) : KListView( parent ), mFolderTree( folderTree ) { kdDebug(5006) << k_funcinfo << endl; connect(this, SIGNAL(collapsed(QListViewItem*)), SLOT(recolorRows())); connect(this, SIGNAL(expanded(QListViewItem*)), SLOT(recolorRows())); connect( this, SIGNAL( contextMenuRequested( QListViewItem*, const QPoint &, int ) ), this, SLOT( slotContextMenuRequested( QListViewItem*, const QPoint & ) ) ); } const KMFolder * TreeBase::folder() const { QListViewItem * item = currentItem(); if( item ) { TreeItemBase *base = dynamic_cast<TreeItemBase*>( item ); assert(base); const KMFolder * folder = base->folder(); return folder; } return 0; } void TreeBase::setFolder( KMFolder *folder ) { for ( QListViewItemIterator it( this ) ; it.current() ; ++it ) { const KMFolder *fld = dynamic_cast<TreeItemBase*>( it.current() )->folder(); if ( fld == folder ) { setSelected( it.current(), true ); ensureItemVisible( it.current() ); } } } void TreeBase::addChildFolder() { kdDebug(5006) << k_funcinfo << endl; const KMFolder *fld = folder(); if ( fld ) { mFolderTree->addChildFolder( (KMFolder *) fld, parentWidget() ); reload( mLastMustBeReadWrite, mLastShowOutbox, mLastShowImapFolders ); setFolder( (KMFolder *) fld ); } } void TreeBase::slotContextMenuRequested( QListViewItem *lvi, const QPoint &p ) { kdDebug(5006) << k_funcinfo << endl; if (!lvi) return; setCurrentItem( lvi ); setSelected( lvi, TRUE ); const KMFolder * folder = dynamic_cast<TreeItemBase*>( lvi )->folder(); if ( !folder || folder->noContent() || folder->noChildren() ) return; KPopupMenu *folderMenu = new KPopupMenu; folderMenu->insertTitle( folder->label() ); folderMenu->insertSeparator(); folderMenu->insertItem(SmallIconSet("folder_new"), i18n("&New Subfolder..."), this, SLOT(addChildFolder())); kmkernel->setContextMenuShown( true ); folderMenu->exec (p, 0); kmkernel->setContextMenuShown( false ); delete folderMenu; folderMenu = 0; } void TreeBase::recolorRows() { kdDebug(5006) << k_funcinfo << endl; // Iterate through the list to set the alternate row flags. int alt = 0; QListViewItemIterator it ( this ); while ( it.current() ) { QListViewItem * item = it.current() ; if ( item->isVisible() ) { bool visible = true; QListViewItem * parent = item->parent(); while ( parent ) { if (!parent->isOpen()) { visible = false; break; } parent = parent->parent(); } if ( visible ) { TreeItemBase * treeItemBase = dynamic_cast<TreeItemBase*>( item ); treeItemBase->setAlternate( alt ); alt = !alt; } } ++it; } } void TreeBase::reload( bool mustBeReadWrite, bool showOutbox, bool showImapFolders, const QString& preSelection ) { clear(); mLastMustBeReadWrite = mustBeReadWrite; mLastShowOutbox = showOutbox; mLastShowImapFolders = showImapFolders; QListViewItem * lastItem = 0; QListViewItem * lastTopItem = 0; QListViewItem * selectedItem = 0; int lastDepth = 0; mFilter = ""; QString path; for ( QListViewItemIterator it( mFolderTree ) ; it.current() ; ++it ) { KMFolderTreeItem * fti = dynamic_cast<KMFolderTreeItem *>( it.current() ); if ( !fti || fti->protocol() == KFolderTreeItem::Search ) continue; int depth = fti->depth();// - 1; //kdDebug( 5006 ) << "LastDepth=" << lastDepth << "\tdepth=" << depth // << "\tname=" << fti->text( 0 ) << endl; QListViewItem * item = 0; if ( depth <= 0 ) { // top level - first top level item or after last existing top level item if ( lastTopItem ) item = createItem( this, lastTopItem ); else item = createItem( this ); lastTopItem = item; depth = 0; path = ""; } else { if ( depth > lastDepth ) { // next lower level - parent node will get opened item = createItem( lastItem ); lastItem->setOpen( true ); } else { path = path.section( '/', 0, -2 - (lastDepth-depth) ); if ( depth == lastDepth ) // same level - behind previous item item = createItem( lastItem->parent(), lastItem ); else if ( depth < lastDepth ) { // above previous level - might be more than one level difference // but highest possibility is top level while ( ( depth <= --lastDepth ) && lastItem->parent() ) { lastItem = static_cast<QListViewItem *>( lastItem->parent() ); } if ( lastItem->parent() ) item = createItem( lastItem->parent(), lastItem ); else { // chain somehow broken - what does cause this ??? kdDebug( 5006 ) << "You shouldn't get here: depth=" << depth << "folder name=" << fti->text( 0 ) << endl; item = createItem( this ); lastTopItem = item; } } } } if ( depth > 0 ) path += "/"; path += fti->text( 0 ); item->setText( mFolderColumn, fti->text( 0 ) ); item->setText( mPathColumn, path ); // Make items without folders and top level items unselectable // (i.e. root item Local Folders and IMAP accounts) if ( !fti->folder() || depth == 0 || ( mustBeReadWrite && fti->folder()->isReadOnly() ) ) { item->setSelectable( false ); } else { TreeItemBase * treeItemBase = dynamic_cast<TreeItemBase*>( item ); assert(treeItemBase); treeItemBase->setFolder( fti->folder() ); if ( preSelection == treeItemBase->folder()->idString() ) selectedItem = item; } lastItem = item; lastDepth = depth; } if ( selectedItem ) { setSelected( selectedItem, true ); ensureItemVisible( selectedItem ); } } #include "treebase.moc" <commit_msg>not necessary here<commit_after>/* Copyright (c) 2008 Pradeepto K. Bhattacharya <pradeepto@kde.org> ( adapted from kdepim/kmail/kmfolderseldlg.cpp and simplefoldertree.h ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "treebase.h" #include "kmfolder.h" #include "kmfoldertree.h" #include "simplefoldertree.h" #include <kdebug.h> #include <klistview.h> using namespace KMail; TreeBase::TreeBase( QWidget *parent, KMFolderTree *folderTree, const QString &preSelection, bool mustBeReadWrite ) : KListView( parent ), mFolderTree( folderTree ) { kdDebug(5006) << k_funcinfo << endl; connect(this, SIGNAL(collapsed(QListViewItem*)), SLOT(recolorRows())); connect(this, SIGNAL(expanded(QListViewItem*)), SLOT(recolorRows())); connect( this, SIGNAL( contextMenuRequested( QListViewItem*, const QPoint &, int ) ), this, SLOT( slotContextMenuRequested( QListViewItem*, const QPoint & ) ) ); } const KMFolder * TreeBase::folder() const { QListViewItem * item = currentItem(); if( item ) { TreeItemBase *base = dynamic_cast<TreeItemBase*>( item ); assert(base); const KMFolder * folder = base->folder(); return folder; } return 0; } void TreeBase::setFolder( KMFolder *folder ) { for ( QListViewItemIterator it( this ) ; it.current() ; ++it ) { const KMFolder *fld = dynamic_cast<TreeItemBase*>( it.current() )->folder(); if ( fld == folder ) { setSelected( it.current(), true ); ensureItemVisible( it.current() ); } } } void TreeBase::addChildFolder() { kdDebug(5006) << k_funcinfo << endl; const KMFolder *fld = folder(); if ( fld ) { mFolderTree->addChildFolder( (KMFolder *) fld, parentWidget() ); reload( mLastMustBeReadWrite, mLastShowOutbox, mLastShowImapFolders ); setFolder( (KMFolder *) fld ); } } void TreeBase::slotContextMenuRequested( QListViewItem *lvi, const QPoint &p ) { kdDebug(5006) << k_funcinfo << endl; if (!lvi) return; setCurrentItem( lvi ); setSelected( lvi, TRUE ); const KMFolder * folder = dynamic_cast<TreeItemBase*>( lvi )->folder(); if ( !folder || folder->noContent() || folder->noChildren() ) return; KPopupMenu *folderMenu = new KPopupMenu; folderMenu->insertTitle( folder->label() ); folderMenu->insertSeparator(); folderMenu->insertItem(SmallIconSet("folder_new"), i18n("&New Subfolder..."), this, SLOT(addChildFolder())); kmkernel->setContextMenuShown( true ); folderMenu->exec (p, 0); kmkernel->setContextMenuShown( false ); delete folderMenu; } void TreeBase::recolorRows() { kdDebug(5006) << k_funcinfo << endl; // Iterate through the list to set the alternate row flags. int alt = 0; QListViewItemIterator it ( this ); while ( it.current() ) { QListViewItem * item = it.current() ; if ( item->isVisible() ) { bool visible = true; QListViewItem * parent = item->parent(); while ( parent ) { if (!parent->isOpen()) { visible = false; break; } parent = parent->parent(); } if ( visible ) { TreeItemBase * treeItemBase = dynamic_cast<TreeItemBase*>( item ); treeItemBase->setAlternate( alt ); alt = !alt; } } ++it; } } void TreeBase::reload( bool mustBeReadWrite, bool showOutbox, bool showImapFolders, const QString& preSelection ) { clear(); mLastMustBeReadWrite = mustBeReadWrite; mLastShowOutbox = showOutbox; mLastShowImapFolders = showImapFolders; QListViewItem * lastItem = 0; QListViewItem * lastTopItem = 0; QListViewItem * selectedItem = 0; int lastDepth = 0; mFilter = ""; QString path; for ( QListViewItemIterator it( mFolderTree ) ; it.current() ; ++it ) { KMFolderTreeItem * fti = dynamic_cast<KMFolderTreeItem *>( it.current() ); if ( !fti || fti->protocol() == KFolderTreeItem::Search ) continue; int depth = fti->depth();// - 1; //kdDebug( 5006 ) << "LastDepth=" << lastDepth << "\tdepth=" << depth // << "\tname=" << fti->text( 0 ) << endl; QListViewItem * item = 0; if ( depth <= 0 ) { // top level - first top level item or after last existing top level item if ( lastTopItem ) item = createItem( this, lastTopItem ); else item = createItem( this ); lastTopItem = item; depth = 0; path = ""; } else { if ( depth > lastDepth ) { // next lower level - parent node will get opened item = createItem( lastItem ); lastItem->setOpen( true ); } else { path = path.section( '/', 0, -2 - (lastDepth-depth) ); if ( depth == lastDepth ) // same level - behind previous item item = createItem( lastItem->parent(), lastItem ); else if ( depth < lastDepth ) { // above previous level - might be more than one level difference // but highest possibility is top level while ( ( depth <= --lastDepth ) && lastItem->parent() ) { lastItem = static_cast<QListViewItem *>( lastItem->parent() ); } if ( lastItem->parent() ) item = createItem( lastItem->parent(), lastItem ); else { // chain somehow broken - what does cause this ??? kdDebug( 5006 ) << "You shouldn't get here: depth=" << depth << "folder name=" << fti->text( 0 ) << endl; item = createItem( this ); lastTopItem = item; } } } } if ( depth > 0 ) path += "/"; path += fti->text( 0 ); item->setText( mFolderColumn, fti->text( 0 ) ); item->setText( mPathColumn, path ); // Make items without folders and top level items unselectable // (i.e. root item Local Folders and IMAP accounts) if ( !fti->folder() || depth == 0 || ( mustBeReadWrite && fti->folder()->isReadOnly() ) ) { item->setSelectable( false ); } else { TreeItemBase * treeItemBase = dynamic_cast<TreeItemBase*>( item ); assert(treeItemBase); treeItemBase->setFolder( fti->folder() ); if ( preSelection == treeItemBase->folder()->idString() ) selectedItem = item; } lastItem = item; lastDepth = depth; } if ( selectedItem ) { setSelected( selectedItem, true ); ensureItemVisible( selectedItem ); } } #include "treebase.moc" <|endoftext|>
<commit_before>/*************************************************************************** * The Kernel-Machine Library * * Copyright (C) 2004, 2005 by Rutger W. ter Borg * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 * ***************************************************************************/ #ifndef POLYNOMIAL_HPP #define POLYNOMIAL_HPP #include <boost/call_traits.hpp> #include <boost/type_traits.hpp> #include <kml/linear.hpp> namespace kml { template<typename Range, int N=0> class polynomial: public std::binary_function<Range, Range, typename kml::power_return_type<Range,N>::type> { public: typedef polynomial<Range,N> type; typedef typename boost::range_value<Range>::type scalar_type; typedef typename mpl::int_<N>::type derivative_order; /*! Construct an uninitialised polynomial kernel */ polynomial() {} /*! Construct a polynomial kernel \param gamma the scale of the inner product \param lambda the bias of the inner product \param d the order of the polynomial kernel */ polynomial( typename boost::call_traits<scalar_type>::param_type gamma, typename boost::call_traits<scalar_type>::param_type lambda, typename boost::call_traits<scalar_type>::param_type d): scale(gamma), bias(lambda), order(d) {} scalar_type operator()( Range const &u, Range const &v ) const { return std::pow( scale * linear<Range,N>()(u,v) + bias, order ); } friend std::ostream& operator<<(std::ostream &os, type const &k) { os << "Polynomial kernel (" << k.scale << "<u,v>+" << k.bias << ")^" << k.order << std::endl; return os; } private: scalar_type scale; scalar_type bias; scalar_type order; }; } #endif <commit_msg>Polynomial kernel calls linear kernel at the moment<commit_after>/*************************************************************************** * The Kernel-Machine Library * * Copyright (C) 2004, 2005 by Rutger W. ter Borg * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 * ***************************************************************************/ #ifndef POLYNOMIAL_HPP #define POLYNOMIAL_HPP #include <boost/call_traits.hpp> #include <boost/type_traits.hpp> #include <kml/linear.hpp> namespace kml { template<typename T, int N=0> class polynomial: public std::binary_function<T, T, typename kml::power_return_type<T,N>::type> { public: typedef polynomial<T,N> type; typedef typename boost::range_value<T>::type scalar_type; typedef typename mpl::int_<N>::type derivative_order; /*! Construct an uninitialised polynomial kernel */ polynomial() {} /*! Construct a polynomial kernel \param gamma the scale of the inner product \param lambda the bias of the inner product \param d the order of the polynomial kernel */ polynomial( typename boost::call_traits<scalar_type>::param_type gamma, typename boost::call_traits<scalar_type>::param_type lambda, typename boost::call_traits<scalar_type>::param_type d): scale(gamma), bias(lambda), order(d) {} scalar_type operator()( T const &u, T const &v ) const { return std::pow( scale * linear<T>()(u,v) + bias, order ); } friend std::ostream& operator<<(std::ostream &os, type const &k) { os << "Polynomial kernel (" << k.scale << "<u,v>+" << k.bias << ")^" << k.order << std::endl; return os; } private: scalar_type scale; scalar_type bias; scalar_type order; }; } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2005 by Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US */ #include "nntpjobs.h" #include "kngroup.h" #include "kngroupmanager.h" #include "knserverinfo.h" #include <kdebug.h> #include <klocale.h> #include <QDir> KNode::GroupListJob::GroupListJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool incremental ) : KNJobData( KNJobData::JTFetchGroups, c, a, i ), mIncremental( incremental ) { } void KNode::GroupListJob::execute() { mGroupList.clear(); KNGroupListData *target = static_cast<KNGroupListData *>( data() ); KUrl destination = baseUrl(); QStringList query; if ( target->getDescriptions ) query << "desc=true"; if ( mIncremental ) query << QString( "since=%1%2%3+000000" ) .arg( target->fetchSince.year() % 100, 2, 10, QChar( '0' ) ) .arg( target->fetchSince.month(), 2, 10, QChar( '0' ) ) .arg( target->fetchSince.day(), 2, 10, QChar( '0' ) ); destination.setQuery( query.join( "&" ) ); KIO::Job* job = KIO::listDir( destination, KIO::HideProgressInfo, true ); connect( job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)), SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&)) ); connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) ); setupKIOJob( job ); } void KNode::GroupListJob::slotEntries( KIO::Job * job, const KIO::UDSEntryList & list ) { Q_UNUSED( job ); KNGroupListData *target = static_cast<KNGroupListData *>( data() ); QString name, desc; bool subscribed; KNGroup::Status access; for( KIO::UDSEntryList::ConstIterator it = list.begin(); it != list.end(); ++it ) { access = KNGroup::unknown; name = (*it).stringValue( KIO::UDSEntry::UDS_NAME ); desc = (*it).stringValue( KIO::UDSEntry::UDS_EXTRA ); int value = (*it).numberValue( KIO::UDSEntry::UDS_ACCESS, -1 ); if ( value != -1 ) { if( value & S_IWOTH ) access = KNGroup::postingAllowed; else if ( value & S_IWGRP ) access = KNGroup::moderated; else access = KNGroup::readOnly; } if ( name.isEmpty() ) continue; if ( target->subscribed.contains( name ) ) { target->subscribed.removeAll( name ); // group names are unique, we wont find it again anyway... subscribed = true; } else { subscribed = false; } kDebug() << "Found group " << name; if ( mIncremental ) mGroupList.append(KNGroupInfo( name, desc, true, subscribed, access ) ); else target->groups->append(KNGroupInfo( name, desc, false, subscribed, access ) ); } } void KNode::GroupListJob::slotResult( KJob * job ) { if ( job->error() ) setError( job->error(), job->errorString() ); else { KNGroupListData *target = static_cast<KNGroupListData *>( data() ); // TODO: use thread weaver here? if ( mIncremental ) { setStatus( i18n("Loading group list from disk...") ); if ( !target->readIn( this ) ) { setError( KIO::ERR_COULD_NOT_READ, i18n("Unable to read the group list file") ); emitFinished(); return; } target->merge( &mGroupList ); } setStatus( i18n("Writing group list to disk...") ); if ( !target->writeOut() ) setError( KIO::ERR_COULD_NOT_WRITE, i18n("Unable to write the group list file") ); } emitFinished(); } KNode::GroupLoadJob::GroupLoadJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i ) : KNJobData( KNJobData::JTLoadGroups, c, a, i ) { } void KNode::GroupLoadJob::execute( ) { KNGroupListData *target = static_cast<KNGroupListData *>( data() ); setStatus( i18n("Loading group list from disk...") ); // TODO: use the thread weaver here if ( !target->readIn( this ) ) setError( KIO::ERR_COULD_NOT_READ, i18n("Unable to read the group list file") ); emitFinished(); } KNode::ArticleListJob::ArticleListJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool silent ) : KNJobData( JTfetchNewHeaders, c, a, i ), mSilent( silent ) { } void KNode::ArticleListJob::execute() { mArticleList.clear(); KNGroup* target = static_cast<KNGroup*>( data() ); KUrl destination = baseUrl(); destination.setPath( target->groupname() ); QStringList query; query << "first=" + QString::number( target->lastNr() + 1 ); if ( target->lastNr() <= 0 ) // first fetch query << "max=" + QString::number( target->maxFetch() ); destination.setQuery( query.join( "&" ) ); KIO::Job* job = KIO::listDir( destination, KIO::HideProgressInfo, true ); connect( job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)), SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&)) ); connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) ); setupKIOJob( job ); } void KNode::ArticleListJob::slotEntries( KIO::Job * job, const KIO::UDSEntryList & list ) { Q_UNUSED( job ); mArticleList += list; } void KNode::ArticleListJob::slotResult( KJob * _job ) { Q_ASSERT( mJob == _job ); KIO::Job *job = static_cast<KIO::Job*>( _job ); if ( job->error() ) setError( job->error(), job->errorString() ); else { createProgressItem(); KNGroup* target = static_cast<KNGroup*>( data() ); target->setLastFetchCount( 0 ); setStatus( i18n("Sorting...") ); if ( job->metaData().contains( "FirstSerialNumber" ) ) { int firstSerNum = job->metaData()["FirstSerialNumber"].toInt(); target->setFirstNr( firstSerNum ); } target->insortNewHeaders( mArticleList, this ); if ( job->metaData().contains( "LastSerialNumber" ) ) { int lastSerNum = job->metaData()["LastSerialNumber"].toInt(); target->setLastNr( lastSerNum ); } } setComplete(); emitFinished(); } KNode::ArticleFetchJob::ArticleFetchJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool parse ) : KNJobData( JTfetchArticle, c, a, i ), mParseArticle( parse ) { } void KNode::ArticleFetchJob::execute() { KNRemoteArticle *target = static_cast<KNRemoteArticle*>( data() ); QString path = static_cast<KNGroup*>( target->collection() )->groupname(); KUrl url = baseUrl(); path += QDir::separator(); path += target->messageID()->as7BitString( false ); url.setPath( path ); KIO::Job* job = KIO::storedGet( url, KIO::NoReload, KIO::HideProgressInfo ); connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) ); setupKIOJob( job ); } void KNode::ArticleFetchJob::slotResult( KJob * job ) { if ( job->error() ) setError( job->error(), job->errorString() ); else { KNRemoteArticle *target = static_cast<KNRemoteArticle*>( data() ); KIO::StoredTransferJob *j = static_cast<KIO::StoredTransferJob*>( job ); QByteArray buffer = j->data(); buffer.replace( "\r\n", "\n" ); // TODO: do this in the io-slave? target->setContent( buffer ); if ( mParseArticle ) target->parse(); } emitFinished(); } KNode::ArticlePostJob::ArticlePostJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i ) : KNJobData( JTpostArticle, c, a, i ) { } void KNode::ArticlePostJob::execute( ) { KNLocalArticle *target = static_cast<KNLocalArticle*>( data() ); KUrl url = baseUrl(); KIO::Job* job = KIO::storedPut( target->encodedContent( true ), url, -1, KIO::Overwrite | KIO::HideProgressInfo ); connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) ); setupKIOJob( job ); } void KNode::ArticlePostJob::slotResult( KJob * job ) { if ( job->error() ) setError( job->error(), job->errorString() ); emitFinished(); } #include "nntpjobs.moc" <commit_msg>By default, fetch articles using their server-side Id instead of their msg-id.<commit_after>/* Copyright (c) 2005 by Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US */ #include "nntpjobs.h" #include "kngroup.h" #include "kngroupmanager.h" #include "knserverinfo.h" #include <kdebug.h> #include <klocale.h> #include <QDir> KNode::GroupListJob::GroupListJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool incremental ) : KNJobData( KNJobData::JTFetchGroups, c, a, i ), mIncremental( incremental ) { } void KNode::GroupListJob::execute() { mGroupList.clear(); KNGroupListData *target = static_cast<KNGroupListData *>( data() ); KUrl destination = baseUrl(); QStringList query; if ( target->getDescriptions ) query << "desc=true"; if ( mIncremental ) query << QString( "since=%1%2%3+000000" ) .arg( target->fetchSince.year() % 100, 2, 10, QChar( '0' ) ) .arg( target->fetchSince.month(), 2, 10, QChar( '0' ) ) .arg( target->fetchSince.day(), 2, 10, QChar( '0' ) ); destination.setQuery( query.join( "&" ) ); KIO::Job* job = KIO::listDir( destination, KIO::HideProgressInfo, true ); connect( job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)), SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&)) ); connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) ); setupKIOJob( job ); } void KNode::GroupListJob::slotEntries( KIO::Job * job, const KIO::UDSEntryList & list ) { Q_UNUSED( job ); KNGroupListData *target = static_cast<KNGroupListData *>( data() ); QString name, desc; bool subscribed; KNGroup::Status access; for( KIO::UDSEntryList::ConstIterator it = list.begin(); it != list.end(); ++it ) { access = KNGroup::unknown; name = (*it).stringValue( KIO::UDSEntry::UDS_NAME ); desc = (*it).stringValue( KIO::UDSEntry::UDS_EXTRA ); int value = (*it).numberValue( KIO::UDSEntry::UDS_ACCESS, -1 ); if ( value != -1 ) { if( value & S_IWOTH ) access = KNGroup::postingAllowed; else if ( value & S_IWGRP ) access = KNGroup::moderated; else access = KNGroup::readOnly; } if ( name.isEmpty() ) continue; if ( target->subscribed.contains( name ) ) { target->subscribed.removeAll( name ); // group names are unique, we wont find it again anyway... subscribed = true; } else { subscribed = false; } kDebug() << "Found group " << name; if ( mIncremental ) mGroupList.append(KNGroupInfo( name, desc, true, subscribed, access ) ); else target->groups->append(KNGroupInfo( name, desc, false, subscribed, access ) ); } } void KNode::GroupListJob::slotResult( KJob * job ) { if ( job->error() ) setError( job->error(), job->errorString() ); else { KNGroupListData *target = static_cast<KNGroupListData *>( data() ); // TODO: use thread weaver here? if ( mIncremental ) { setStatus( i18n("Loading group list from disk...") ); if ( !target->readIn( this ) ) { setError( KIO::ERR_COULD_NOT_READ, i18n("Unable to read the group list file") ); emitFinished(); return; } target->merge( &mGroupList ); } setStatus( i18n("Writing group list to disk...") ); if ( !target->writeOut() ) setError( KIO::ERR_COULD_NOT_WRITE, i18n("Unable to write the group list file") ); } emitFinished(); } KNode::GroupLoadJob::GroupLoadJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i ) : KNJobData( KNJobData::JTLoadGroups, c, a, i ) { } void KNode::GroupLoadJob::execute( ) { KNGroupListData *target = static_cast<KNGroupListData *>( data() ); setStatus( i18n("Loading group list from disk...") ); // TODO: use the thread weaver here if ( !target->readIn( this ) ) setError( KIO::ERR_COULD_NOT_READ, i18n("Unable to read the group list file") ); emitFinished(); } KNode::ArticleListJob::ArticleListJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool silent ) : KNJobData( JTfetchNewHeaders, c, a, i ), mSilent( silent ) { } void KNode::ArticleListJob::execute() { mArticleList.clear(); KNGroup* target = static_cast<KNGroup*>( data() ); KUrl destination = baseUrl(); destination.setPath( target->groupname() ); QStringList query; query << "first=" + QString::number( target->lastNr() + 1 ); if ( target->lastNr() <= 0 ) // first fetch query << "max=" + QString::number( target->maxFetch() ); destination.setQuery( query.join( "&" ) ); KIO::Job* job = KIO::listDir( destination, KIO::HideProgressInfo, true ); connect( job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)), SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&)) ); connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) ); setupKIOJob( job ); } void KNode::ArticleListJob::slotEntries( KIO::Job * job, const KIO::UDSEntryList & list ) { Q_UNUSED( job ); mArticleList += list; } void KNode::ArticleListJob::slotResult( KJob * _job ) { Q_ASSERT( mJob == _job ); KIO::Job *job = static_cast<KIO::Job*>( _job ); if ( job->error() ) setError( job->error(), job->errorString() ); else { createProgressItem(); KNGroup* target = static_cast<KNGroup*>( data() ); target->setLastFetchCount( 0 ); setStatus( i18n("Sorting...") ); if ( job->metaData().contains( "FirstSerialNumber" ) ) { int firstSerNum = job->metaData()["FirstSerialNumber"].toInt(); target->setFirstNr( firstSerNum ); } target->insortNewHeaders( mArticleList, this ); if ( job->metaData().contains( "LastSerialNumber" ) ) { int lastSerNum = job->metaData()["LastSerialNumber"].toInt(); target->setLastNr( lastSerNum ); } } setComplete(); emitFinished(); } KNode::ArticleFetchJob::ArticleFetchJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i, bool parse ) : KNJobData( JTfetchArticle, c, a, i ), mParseArticle( parse ) { } void KNode::ArticleFetchJob::execute() { KNRemoteArticle *target = static_cast<KNRemoteArticle*>( data() ); QString path = static_cast<KNGroup*>( target->collection() )->groupname(); KUrl url = baseUrl(); path += QDir::separator(); // By default, fetch articles by their server-side Id. // (some server does not understand the "ARTICLE <msg-id>" command correctly (bug #193550)) if ( target->articleNumber() != -1 ) { path += QString::number( target->articleNumber() ); } else { // User asked to fetch a message by its msg-id path += target->messageID()->as7BitString( false ); } url.setPath( path ); KIO::Job* job = KIO::storedGet( url, KIO::NoReload, KIO::HideProgressInfo ); connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) ); setupKIOJob( job ); } void KNode::ArticleFetchJob::slotResult( KJob * job ) { if ( job->error() ) setError( job->error(), job->errorString() ); else { KNRemoteArticle *target = static_cast<KNRemoteArticle*>( data() ); KIO::StoredTransferJob *j = static_cast<KIO::StoredTransferJob*>( job ); QByteArray buffer = j->data(); buffer.replace( "\r\n", "\n" ); // TODO: do this in the io-slave? target->setContent( buffer ); if ( mParseArticle ) target->parse(); } emitFinished(); } KNode::ArticlePostJob::ArticlePostJob( KNJobConsumer * c, KNServerInfo * a, KNJobItem * i ) : KNJobData( JTpostArticle, c, a, i ) { } void KNode::ArticlePostJob::execute( ) { KNLocalArticle *target = static_cast<KNLocalArticle*>( data() ); KUrl url = baseUrl(); KIO::Job* job = KIO::storedPut( target->encodedContent( true ), url, -1, KIO::Overwrite | KIO::HideProgressInfo ); connect( job, SIGNAL( result(KJob*) ), SLOT( slotResult(KJob*) ) ); setupKIOJob( job ); } void KNode::ArticlePostJob::slotResult( KJob * job ) { if ( job->error() ) setError( job->error(), job->errorString() ); emitFinished(); } #include "nntpjobs.moc" <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreLog.h" #include "OgreLogManager.h" #include "OgreString.h" #if OGRE_PLATFORM == OGRE_PLATFORM_NACL # include "ppapi/cpp/var.h" # include "ppapi/cpp/instance.h" #endif namespace Ogre { #if OGRE_PLATFORM == OGRE_PLATFORM_NACL pp::Instance* Log::mInstance = NULL; #endif //----------------------------------------------------------------------- Log::Log( const String& name, bool debuggerOuput, bool suppressFile ) : mLogLevel(LL_NORMAL), mDebugOut(debuggerOuput), mSuppressFile(suppressFile), mTimeStamp(true), mLogName(name) { if (!mSuppressFile) { mLog.open(name.c_str()); } } //----------------------------------------------------------------------- Log::~Log() { OGRE_LOCK_AUTO_MUTEX; if (!mSuppressFile) { mLog.close(); } } //----------------------------------------------------------------------- void Log::logMessage( const String& message, LogMessageLevel lml, bool maskDebug ) { OGRE_LOCK_AUTO_MUTEX; if ((mLogLevel + lml) >= OGRE_LOG_THRESHOLD) { bool skipThisMessage = false; for( mtLogListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i ) (*i)->messageLogged( message, lml, maskDebug, mLogName, skipThisMessage); if (!skipThisMessage) { #if OGRE_PLATFORM == OGRE_PLATFORM_NACL if(mInstance != NULL) { mInstance->PostMessage(message.c_str()); } #else if (mDebugOut && !maskDebug) # if _DEBUG && (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) { String logMessageString(message); logMessageString.append( "\n" ); Ogre_OutputCString( logMessageString.c_str()); } # else std::cerr << message << std::endl; # endif #endif // Write time into log if (!mSuppressFile) { if (mTimeStamp) { struct tm *pTime; time_t ctTime; time(&ctTime); pTime = localtime( &ctTime ); mLog << std::setw(2) << std::setfill('0') << pTime->tm_hour << ":" << std::setw(2) << std::setfill('0') << pTime->tm_min << ":" << std::setw(2) << std::setfill('0') << pTime->tm_sec << ": "; } mLog << message << std::endl; // Flush stcmdream to ensure it is written (incase of a crash, we need log to be up to date) mLog.flush(); } } } } //----------------------------------------------------------------------- void Log::setTimeStampEnabled(bool timeStamp) { OGRE_LOCK_AUTO_MUTEX; mTimeStamp = timeStamp; } //----------------------------------------------------------------------- void Log::setDebugOutputEnabled(bool debugOutput) { OGRE_LOCK_AUTO_MUTEX; mDebugOut = debugOutput; } //----------------------------------------------------------------------- void Log::setLogDetail(LoggingLevel ll) { OGRE_LOCK_AUTO_MUTEX; mLogLevel = ll; } //----------------------------------------------------------------------- void Log::addListener(LogListener* listener) { OGRE_LOCK_AUTO_MUTEX; mListeners.push_back(listener); } //----------------------------------------------------------------------- void Log::removeListener(LogListener* listener) { OGRE_LOCK_AUTO_MUTEX; mListeners.erase(std::find(mListeners.begin(), mListeners.end(), listener)); } //--------------------------------------------------------------------- Log::Stream Log::stream(LogMessageLevel lml, bool maskDebug) { return Stream(this, lml, maskDebug); } } <commit_msg>Log non-critical messages to cout instead of cerr. Many IDEs (and possibly terminals) use red color for cerr output, so don't use cerr unless it's an error.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreLog.h" #include "OgreLogManager.h" #include "OgreString.h" #if OGRE_PLATFORM == OGRE_PLATFORM_NACL # include "ppapi/cpp/var.h" # include "ppapi/cpp/instance.h" #endif namespace Ogre { #if OGRE_PLATFORM == OGRE_PLATFORM_NACL pp::Instance* Log::mInstance = NULL; #endif //----------------------------------------------------------------------- Log::Log( const String& name, bool debuggerOuput, bool suppressFile ) : mLogLevel(LL_NORMAL), mDebugOut(debuggerOuput), mSuppressFile(suppressFile), mTimeStamp(true), mLogName(name) { if (!mSuppressFile) { mLog.open(name.c_str()); } } //----------------------------------------------------------------------- Log::~Log() { OGRE_LOCK_AUTO_MUTEX; if (!mSuppressFile) { mLog.close(); } } //----------------------------------------------------------------------- void Log::logMessage( const String& message, LogMessageLevel lml, bool maskDebug ) { OGRE_LOCK_AUTO_MUTEX; if ((mLogLevel + lml) >= OGRE_LOG_THRESHOLD) { bool skipThisMessage = false; for( mtLogListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i ) (*i)->messageLogged( message, lml, maskDebug, mLogName, skipThisMessage); if (!skipThisMessage) { #if OGRE_PLATFORM == OGRE_PLATFORM_NACL if(mInstance != NULL) { mInstance->PostMessage(message.c_str()); } #else if (mDebugOut && !maskDebug) { # if _DEBUG && (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) String logMessageString(message); logMessageString.append( "\n" ); Ogre_OutputCString( logMessageString.c_str()); # else if (lml == LML_CRITICAL) std::cerr << message << std::endl; else std::cout << message << std::endl; } # endif #endif // Write time into log if (!mSuppressFile) { if (mTimeStamp) { struct tm *pTime; time_t ctTime; time(&ctTime); pTime = localtime( &ctTime ); mLog << std::setw(2) << std::setfill('0') << pTime->tm_hour << ":" << std::setw(2) << std::setfill('0') << pTime->tm_min << ":" << std::setw(2) << std::setfill('0') << pTime->tm_sec << ": "; } mLog << message << std::endl; // Flush stcmdream to ensure it is written (incase of a crash, we need log to be up to date) mLog.flush(); } } } } //----------------------------------------------------------------------- void Log::setTimeStampEnabled(bool timeStamp) { OGRE_LOCK_AUTO_MUTEX; mTimeStamp = timeStamp; } //----------------------------------------------------------------------- void Log::setDebugOutputEnabled(bool debugOutput) { OGRE_LOCK_AUTO_MUTEX; mDebugOut = debugOutput; } //----------------------------------------------------------------------- void Log::setLogDetail(LoggingLevel ll) { OGRE_LOCK_AUTO_MUTEX; mLogLevel = ll; } //----------------------------------------------------------------------- void Log::addListener(LogListener* listener) { OGRE_LOCK_AUTO_MUTEX; mListeners.push_back(listener); } //----------------------------------------------------------------------- void Log::removeListener(LogListener* listener) { OGRE_LOCK_AUTO_MUTEX; mListeners.erase(std::find(mListeners.begin(), mListeners.end(), listener)); } //--------------------------------------------------------------------- Log::Stream Log::stream(LogMessageLevel lml, bool maskDebug) { return Stream(this, lml, maskDebug); } } <|endoftext|>
<commit_before>/******************************************************************************* GPU OPTIMIZED MONTE CARLO (GOMC) 2.70 Copyright (C) 2018 GOMC Group A copy of the GNU General Public License can be found in the COPYRIGHT.txt along with this program, also can be found at <http://www.gnu.org/licenses/>. ********************************************************************************/ #include <Checkpoint.h> Checkpoint::Checkpoint(const ulong & step, const ulong & trueStep, MoveSettings & movSetRef, PRNG & prngRef, const Molecules & molRef, MoleculeLookup & molLookupRef, MolSetup & molSetupRef, pdb_setup::Atoms const& pdbSetupAtomsRef){ GatherStep(step); GatherTrueStep(trueStep); GatherMoveSettings(movSetRef); GatherRandomNumbers(prngRef); GatherRestartMoleculeIndices(molLookupRef, molRef); GatherMoleculeLookup(molLookupRef); // Not sure if these need to be gathered.. GatherMolSetup(molSetupRef); GatherPDBSetupAtoms(pdbSetupAtomsRef); // Not sure if these need to be gathered.. GatherRestartMoleculeStartVec(molLookupRef, molRef); GatherOriginalMoleculeStartVec(molRef); } #if GOMC_LIB_MPI Checkpoint::Checkpoint(const ulong & step, const ulong & trueStep, MoveSettings & movSetRef, PRNG & prngRef, const Molecules & molRef, MoleculeLookup & molLookupRef, bool & parallelTemperingIsEnabled, PRNG & prngPTRef){ GatherStep(step); GatherTrueStep(trueStep); GatherMoveSettings(movSetRef); GatherRandomNumbers(prngRef); GatherRestartMoleculeIndices(molLookupRef); // Not sure if these need to be gathered.. GatherMolSetup(molSetupRef); GatherPDBSetupAtoms(pdbSetupAtomsRef); // Not sure if these need to be gathered.. GatherRestartMoleculeStartVec(molLookupRef, molRef); GatherOriginalMoleculeStartVec(molRef); GatherParallelTemperingBoolean(parallelTemperingIsEnabled); if(parallelTemperingIsEnabled) GatherRandomNumbersParallelTempering(prngPTRef); } #endif Checkpoint::Checkpoint(){} Checkpoint::~Checkpoint(){} void Checkpoint::GatherGOMCVersion() { sprintf(gomc_version, "%d.%02d", GOMC_VERSION_MAJOR, GOMC_VERSION_MINOR % 100); } void Checkpoint::GatherStep(const ulong & step){ stepNumber = step; } void Checkpoint::GatherTrueStep(const ulong & trueStep){ trueStepNumber = trueStep; } void Checkpoint::GatherRandomNumbers(PRNG & prngRef){ prngRef.GetGenerator()->save(saveArray); seedLocation = prngRef.GetGenerator()->pNext - prngRef.GetGenerator()->state; // save the "left" value so we can restore it later seedLeft = (prngRef.GetGenerator()->left); // let's save seedValue just in case // not sure if that is used or not, or how important it is seedValue = prngRef.GetGenerator()->seedValue; } /* After the first run, the molecules are sorted, so we need to use the same sorting process seen below, to reinitialize the originalMolInds every checkpoint */ void Checkpoint::GatherMoveSettings(MoveSettings & movSetRef){ // Move Settings Vectors scaleVec = movSetRef.scale; acceptPercentVec = movSetRef.acceptPercent; acceptedVec = movSetRef.accepted; triesVec = movSetRef.tries; tempAcceptedVec = movSetRef.tempAccepted; tempTriesVec = movSetRef.tempTries; mp_acceptedVec = movSetRef.mp_accepted; mp_interval_acceptedVec = movSetRef.mp_interval_accepted; mp_interval_triesVec = movSetRef.mp_interval_tries; mp_triesVec = movSetRef.mp_tries; mp_r_maxVec = movSetRef.mp_r_max; mp_t_maxVec = movSetRef.mp_t_max; for (int b = 0; b < BOXES_WITH_U_NB; ++b) isSingleMoveAccepted[b] = movSetRef.isSingleMoveAccepted[b]; } /* Got rid of the if condition of whether this was a restFromChk or not since the new method for restart from chk should believe it is always NOT restarting from chk. */ void Checkpoint::GatherRestartMoleculeIndices(MoleculeLookup & molLookupRef, const Molecules & molRef){ molLookupRef.restartMoleculeIndices.clear(); molLookupRef.restartMoleculeIndices.resize(molLookupRef.molLookupCount); uint molCounter = 0, b, k, kI, countByKind, sizeOfKind, molI; for (b = 0; b < BOX_TOTAL; ++b) { molLookupRef.restartedNumAtomsInBox[b] = 0; for (k = 0; k < molLookupRef.numKinds; ++k) { countByKind = molLookupRef.NumKindInBox(k, b); sizeOfKind = molRef.kinds[k].NumAtoms(); molLookupRef.restartedNumAtomsInBox[b] += sizeOfKind * countByKind; } for (k = 0; k < molLookupRef.numKinds; ++k) { countByKind = molLookupRef.NumKindInBox(k, b); for (kI = 0; kI < countByKind; ++kI) { molI = molLookupRef.GetMolNum(kI, k, b); molLookupRef.restartMoleculeIndices[molCounter] = molI; ++molCounter; } } } } void Checkpoint::GatherMoleculeLookup(MoleculeLookup & molLookupRef){ originalMoleculeLookup = molLookupRef; } /* After the first run, we don't parse PSF files. We simply load the original molecule map from file. Therefore, the new simulation doesn't have molecule ranges for the PDB data. We generate the molecule ranges of the reordered PDB Restart files in this method. */ void Checkpoint::GatherRestartMoleculeStartVec(MoleculeLookup & molLookupRef, const Molecules & molRef){ restartedStartVec.clear(); uint len = 0, sum = 0, start = 0; //Start particle numbering @ 1 restartedStartVec.push_back(0); for (uint box = 0; box < BOX_TOTAL; ++box) { MoleculeLookup::box_iterator m = molLookupRef.BoxBegin(box), end = molLookupRef.BoxEnd(box); while (m != end) { start = 0; len = 0; molRef.GetRangeStartLength(start, len, *m); sum += len; restartedStartVec.push_back(sum); ++m; } } } void Checkpoint::GatherOriginalMoleculeStartVec(const Molecules & molRef){ for (int i = 0; i <= molRef.count; ++i) originalStartVec.push_back(molRef.start[i]); } void Checkpoint::GatherMolSetup(MolSetup & molSetupRef){ originalMolSetup = molSetupRef; } void Checkpoint::GatherPDBSetupAtoms(pdb_setup::Atoms const& pdbSetupAtomsRef){ originalAtoms = pdbSetupAtomsRef; } #if GOMC_LIB_MPI void Checkpoint::GatherParallelTemperingBoolean(bool & parallelTemperingIsEnabled){ parallelTemperingEnabled = parallelTemperingIsEnabled; } void Checkpoint::GatherRandomNumbersParallelTempering(PRNG & prngPTRef) { // First let's save the state array inside prng // the length of the array is 624 // there is a save function inside MersenneTwister.h file // to read back we can use the load function // The MT::save function also appends the "left" variable, // so need to allocate one more array element prngPTRef.GetGenerator()->save(saveArrayPT); // Save the location of pointer in state locationPT = prngPTRef.GetGenerator()->pNext - prngPTRef.GetGenerator()->state; // save the "left" value so we can restore it later leftPT = (prngPTRef.GetGenerator()->left); // let's save seedValue just in case // not sure if that is used or not, or how important it is seedPT = prngPTRef.GetGenerator()->seedValue; } #endif<commit_msg>Problem with restartedStartVec<commit_after>/******************************************************************************* GPU OPTIMIZED MONTE CARLO (GOMC) 2.70 Copyright (C) 2018 GOMC Group A copy of the GNU General Public License can be found in the COPYRIGHT.txt along with this program, also can be found at <http://www.gnu.org/licenses/>. ********************************************************************************/ #include <Checkpoint.h> Checkpoint::Checkpoint(const ulong & step, const ulong & trueStep, MoveSettings & movSetRef, PRNG & prngRef, const Molecules & molRef, MoleculeLookup & molLookupRef, MolSetup & molSetupRef, pdb_setup::Atoms const& pdbSetupAtomsRef){ GatherStep(step); GatherTrueStep(trueStep); GatherMoveSettings(movSetRef); GatherRandomNumbers(prngRef); GatherRestartMoleculeIndices(molLookupRef, molRef); GatherMoleculeLookup(molLookupRef); // Not sure if these need to be gathered.. GatherMolSetup(molSetupRef); GatherPDBSetupAtoms(pdbSetupAtomsRef); // Not sure if these need to be gathered.. GatherRestartMoleculeStartVec(molLookupRef, molRef); GatherOriginalMoleculeStartVec(molRef); } #if GOMC_LIB_MPI Checkpoint::Checkpoint(const ulong & step, const ulong & trueStep, MoveSettings & movSetRef, PRNG & prngRef, const Molecules & molRef, MoleculeLookup & molLookupRef, bool & parallelTemperingIsEnabled, PRNG & prngPTRef){ GatherStep(step); GatherTrueStep(trueStep); GatherMoveSettings(movSetRef); GatherRandomNumbers(prngRef); GatherRestartMoleculeIndices(molLookupRef); GatherMoleculeLookup(molLookupRef); // Not sure if these need to be gathered.. GatherMolSetup(molSetupRef); GatherPDBSetupAtoms(pdbSetupAtomsRef); // Not sure if these need to be gathered.. GatherRestartMoleculeStartVec(molLookupRef, molRef); GatherOriginalMoleculeStartVec(molRef); GatherParallelTemperingBoolean(parallelTemperingIsEnabled); if(parallelTemperingIsEnabled) GatherRandomNumbersParallelTempering(prngPTRef); } #endif Checkpoint::Checkpoint(){} Checkpoint::~Checkpoint(){} void Checkpoint::GatherGOMCVersion() { sprintf(gomc_version, "%d.%02d", GOMC_VERSION_MAJOR, GOMC_VERSION_MINOR % 100); } void Checkpoint::GatherStep(const ulong & step){ stepNumber = step; } void Checkpoint::GatherTrueStep(const ulong & trueStep){ trueStepNumber = trueStep; } void Checkpoint::GatherRandomNumbers(PRNG & prngRef){ prngRef.GetGenerator()->save(saveArray); seedLocation = prngRef.GetGenerator()->pNext - prngRef.GetGenerator()->state; // save the "left" value so we can restore it later seedLeft = (prngRef.GetGenerator()->left); // let's save seedValue just in case // not sure if that is used or not, or how important it is seedValue = prngRef.GetGenerator()->seedValue; } /* After the first run, the molecules are sorted, so we need to use the same sorting process seen below, to reinitialize the originalMolInds every checkpoint */ void Checkpoint::GatherMoveSettings(MoveSettings & movSetRef){ // Move Settings Vectors scaleVec = movSetRef.scale; acceptPercentVec = movSetRef.acceptPercent; acceptedVec = movSetRef.accepted; triesVec = movSetRef.tries; tempAcceptedVec = movSetRef.tempAccepted; tempTriesVec = movSetRef.tempTries; mp_acceptedVec = movSetRef.mp_accepted; mp_interval_acceptedVec = movSetRef.mp_interval_accepted; mp_interval_triesVec = movSetRef.mp_interval_tries; mp_triesVec = movSetRef.mp_tries; mp_r_maxVec = movSetRef.mp_r_max; mp_t_maxVec = movSetRef.mp_t_max; for (int b = 0; b < BOXES_WITH_U_NB; ++b) isSingleMoveAccepted[b] = movSetRef.isSingleMoveAccepted[b]; } /* Got rid of the if condition of whether this was a restFromChk or not since the new method for restart from chk should believe it is always NOT restarting from chk. */ void Checkpoint::GatherRestartMoleculeIndices(MoleculeLookup & molLookupRef, const Molecules & molRef){ molLookupRef.restartMoleculeIndices.clear(); molLookupRef.restartMoleculeIndices.resize(molLookupRef.molLookupCount); uint molCounter = 0, b, k, kI, countByKind, sizeOfKind, molI; for (b = 0; b < BOX_TOTAL; ++b) { molLookupRef.restartedNumAtomsInBox[b] = 0; for (k = 0; k < molLookupRef.numKinds; ++k) { countByKind = molLookupRef.NumKindInBox(k, b); sizeOfKind = molRef.kinds[k].NumAtoms(); molLookupRef.restartedNumAtomsInBox[b] += sizeOfKind * countByKind; } for (k = 0; k < molLookupRef.numKinds; ++k) { countByKind = molLookupRef.NumKindInBox(k, b); for (kI = 0; kI < countByKind; ++kI) { molI = molLookupRef.GetMolNum(kI, k, b); molLookupRef.restartMoleculeIndices[molCounter] = molI; ++molCounter; } } } } void Checkpoint::GatherMoleculeLookup(MoleculeLookup & molLookupRef){ originalMoleculeLookup = molLookupRef; } /* After the first run, we don't parse PSF files. We simply load the original molecule map from file. Therefore, the new simulation doesn't have molecule ranges for the PDB data. We generate the molecule ranges of the reordered PDB Restart files in this method. */ void Checkpoint::GatherRestartMoleculeStartVec(MoleculeLookup & molLookupRef, const Molecules & molRef){ restartedStartVec.clear(); uint len = 0, sum = 0, start = 0; //Start particle numbering @ 1 restartedStartVec.push_back(0); for (uint box = 0; box < BOX_TOTAL; ++box) { MoleculeLookup::box_iterator m = molLookupRef.BoxBegin(box), end = molLookupRef.BoxEnd(box); while (m != end) { start = 0; len = 0; molRef.GetRangeStartLength(start, len, *m); sum += len; restartedStartVec.push_back(sum); ++m; } } } void Checkpoint::GatherOriginalMoleculeStartVec(const Molecules & molRef){ for (int i = 0; i <= molRef.count; ++i) originalStartVec.push_back(molRef.start[i]); } void Checkpoint::GatherMolSetup(MolSetup & molSetupRef){ originalMolSetup = molSetupRef; } void Checkpoint::GatherPDBSetupAtoms(pdb_setup::Atoms const& pdbSetupAtomsRef){ originalAtoms = pdbSetupAtomsRef; } #if GOMC_LIB_MPI void Checkpoint::GatherParallelTemperingBoolean(bool & parallelTemperingIsEnabled){ parallelTemperingEnabled = parallelTemperingIsEnabled; } void Checkpoint::GatherRandomNumbersParallelTempering(PRNG & prngPTRef) { // First let's save the state array inside prng // the length of the array is 624 // there is a save function inside MersenneTwister.h file // to read back we can use the load function // The MT::save function also appends the "left" variable, // so need to allocate one more array element prngPTRef.GetGenerator()->save(saveArrayPT); // Save the location of pointer in state locationPT = prngPTRef.GetGenerator()->pNext - prngPTRef.GetGenerator()->state; // save the "left" value so we can restore it later leftPT = (prngPTRef.GetGenerator()->left); // let's save seedValue just in case // not sure if that is used or not, or how important it is seedPT = prngPTRef.GetGenerator()->seedValue; } #endif<|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "test_precomp.hpp" #include <string> #include <iostream> using namespace std; using namespace cv; class CV_GrabcutTest : public cvtest::BaseTest { public: CV_GrabcutTest(); ~CV_GrabcutTest(); protected: bool verify(const Mat& mask, const Mat& exp); void run(int); }; CV_GrabcutTest::CV_GrabcutTest() {} CV_GrabcutTest::~CV_GrabcutTest() {} bool CV_GrabcutTest::verify(const Mat& mask, const Mat& exp) { const float maxDiffRatio = 0.005f; int expArea = countNonZero( exp ); int nonIntersectArea = countNonZero( mask != exp ); float curRatio = (float)nonIntersectArea / (float)expArea; ts->printf( cvtest::TS::LOG, "nonIntersectArea/expArea = %f\n", curRatio ); return curRatio < maxDiffRatio; } void CV_GrabcutTest::run( int /* start_from */) { cvtest::DefaultRngAuto defRng; Mat img = imread(string(ts->get_data_path()) + "shared/airplane.jpg"); Mat mask_prob = imread(string(ts->get_data_path()) + "grabcut/mask_prob.png", 0); Mat exp_mask1 = imread(string(ts->get_data_path()) + "grabcut/exp_mask1.png", 0); Mat exp_mask2 = imread(string(ts->get_data_path()) + "grabcut/exp_mask2.png", 0); if (img.empty() || (!mask_prob.empty() && img.size() != mask_prob.size()) || (!exp_mask1.empty() && img.size() != exp_mask1.size()) || (!exp_mask2.empty() && img.size() != exp_mask2.size()) ) { ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA); return; } Rect rect(Point(24, 126), Point(483, 294)); Mat exp_bgdModel, exp_fgdModel; Mat mask; mask = Scalar(0); Mat bgdModel, fgdModel; grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT ); grabCut( img, mask, rect, bgdModel, fgdModel, 2, GC_EVAL ); // Multiply images by 255 for more visuality of test data. if( mask_prob.empty() ) { mask.copyTo( mask_prob ); imwrite(string(ts->get_data_path()) + "grabcut/mask_prob.png", mask_prob); } if( exp_mask1.empty() ) { exp_mask1 = (mask & 1) * 255; imwrite(string(ts->get_data_path()) + "grabcut/exp_mask1.png", exp_mask1); } if (!verify((mask & 1) * 255, exp_mask1)) { ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); return; } mask = mask_prob; bgdModel.release(); fgdModel.release(); rect = Rect(); grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_MASK ); grabCut( img, mask, rect, bgdModel, fgdModel, 1, GC_EVAL ); if( exp_mask2.empty() ) { exp_mask2 = (mask & 1) * 255; imwrite(string(ts->get_data_path()) + "grabcut/exp_mask2.png", exp_mask2); } if (!verify((mask & 1) * 255, exp_mask2)) { ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); return; } ts->set_failed_test_info(cvtest::TS::OK); } TEST(Imgproc_GrabCut, regression) { CV_GrabcutTest test; test.safe_run(); } TEST(Imgproc_GrabCut, repeatability) { cvtest::TS& ts = *cvtest::TS::ptr(); Mat image_1 = imread(ts.get_data_path() + "grabcut/image1652.ppm", CV_LOAD_IMAGE_COLOR); Mat mask_1 = imread(ts.get_data_path() + "grabcut/mask1652.ppm", CV_LOAD_IMAGE_GRAYSCALE); Rect roi_1(0, 0, 150, 150); Mat image_2 = image_1.clone(); Mat mask_2 = mask_1.clone(); Rect roi_2 = roi_1; Mat image_3 = image_1.clone(); Mat mask_3 = mask_1.clone(); Rect roi_3 = roi_1; Mat bgdModel_1, fgdModel_1; Mat bgdModel_2, fgdModel_2; Mat bgdModel_3, fgdModel_3; theRNG().state = 12378213; grabCut(image_1, mask_1, roi_1, bgdModel_1, fgdModel_1, 1, GC_INIT_WITH_MASK); theRNG().state = 12378213; grabCut(image_2, mask_2, roi_2, bgdModel_2, fgdModel_2, 1, GC_INIT_WITH_MASK); theRNG().state = 12378213; grabCut(image_3, mask_3, roi_3, bgdModel_3, fgdModel_3, 1, GC_INIT_WITH_MASK); EXPECT_EQ(0, countNonZero(mask_1 != mask_2)); EXPECT_EQ(0, countNonZero(mask_1 != mask_3)); EXPECT_EQ(0, countNonZero(mask_2 != mask_3)); } <commit_msg>Fixed the path to the testdata.<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "test_precomp.hpp" #include <string> #include <iostream> using namespace std; using namespace cv; class CV_GrabcutTest : public cvtest::BaseTest { public: CV_GrabcutTest(); ~CV_GrabcutTest(); protected: bool verify(const Mat& mask, const Mat& exp); void run(int); }; CV_GrabcutTest::CV_GrabcutTest() {} CV_GrabcutTest::~CV_GrabcutTest() {} bool CV_GrabcutTest::verify(const Mat& mask, const Mat& exp) { const float maxDiffRatio = 0.005f; int expArea = countNonZero( exp ); int nonIntersectArea = countNonZero( mask != exp ); float curRatio = (float)nonIntersectArea / (float)expArea; ts->printf( cvtest::TS::LOG, "nonIntersectArea/expArea = %f\n", curRatio ); return curRatio < maxDiffRatio; } void CV_GrabcutTest::run( int /* start_from */) { cvtest::DefaultRngAuto defRng; Mat img = imread(string(ts->get_data_path()) + "shared/airplane.jpg"); Mat mask_prob = imread(string(ts->get_data_path()) + "grabcut/mask_prob.png", 0); Mat exp_mask1 = imread(string(ts->get_data_path()) + "grabcut/exp_mask1.png", 0); Mat exp_mask2 = imread(string(ts->get_data_path()) + "grabcut/exp_mask2.png", 0); if (img.empty() || (!mask_prob.empty() && img.size() != mask_prob.size()) || (!exp_mask1.empty() && img.size() != exp_mask1.size()) || (!exp_mask2.empty() && img.size() != exp_mask2.size()) ) { ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA); return; } Rect rect(Point(24, 126), Point(483, 294)); Mat exp_bgdModel, exp_fgdModel; Mat mask; mask = Scalar(0); Mat bgdModel, fgdModel; grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT ); grabCut( img, mask, rect, bgdModel, fgdModel, 2, GC_EVAL ); // Multiply images by 255 for more visuality of test data. if( mask_prob.empty() ) { mask.copyTo( mask_prob ); imwrite(string(ts->get_data_path()) + "grabcut/mask_prob.png", mask_prob); } if( exp_mask1.empty() ) { exp_mask1 = (mask & 1) * 255; imwrite(string(ts->get_data_path()) + "grabcut/exp_mask1.png", exp_mask1); } if (!verify((mask & 1) * 255, exp_mask1)) { ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); return; } mask = mask_prob; bgdModel.release(); fgdModel.release(); rect = Rect(); grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_MASK ); grabCut( img, mask, rect, bgdModel, fgdModel, 1, GC_EVAL ); if( exp_mask2.empty() ) { exp_mask2 = (mask & 1) * 255; imwrite(string(ts->get_data_path()) + "grabcut/exp_mask2.png", exp_mask2); } if (!verify((mask & 1) * 255, exp_mask2)) { ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); return; } ts->set_failed_test_info(cvtest::TS::OK); } TEST(Imgproc_GrabCut, regression) { CV_GrabcutTest test; test.safe_run(); } TEST(Imgproc_GrabCut, repeatability) { cvtest::TS& ts = *cvtest::TS::ptr(); Mat image_1 = imread(string(ts.get_data_path()) + "grabcut/image1652.ppm", CV_LOAD_IMAGE_COLOR); Mat mask_1 = imread(string(ts.get_data_path()) + "grabcut/mask1652.ppm", CV_LOAD_IMAGE_GRAYSCALE); Rect roi_1(0, 0, 150, 150); Mat image_2 = image_1.clone(); Mat mask_2 = mask_1.clone(); Rect roi_2 = roi_1; Mat image_3 = image_1.clone(); Mat mask_3 = mask_1.clone(); Rect roi_3 = roi_1; Mat bgdModel_1, fgdModel_1; Mat bgdModel_2, fgdModel_2; Mat bgdModel_3, fgdModel_3; theRNG().state = 12378213; grabCut(image_1, mask_1, roi_1, bgdModel_1, fgdModel_1, 1, GC_INIT_WITH_MASK); theRNG().state = 12378213; grabCut(image_2, mask_2, roi_2, bgdModel_2, fgdModel_2, 1, GC_INIT_WITH_MASK); theRNG().state = 12378213; grabCut(image_3, mask_3, roi_3, bgdModel_3, fgdModel_3, 1, GC_INIT_WITH_MASK); EXPECT_EQ(0, countNonZero(mask_1 != mask_2)); EXPECT_EQ(0, countNonZero(mask_1 != mask_3)); EXPECT_EQ(0, countNonZero(mask_2 != mask_3)); } <|endoftext|>
<commit_before>#include "objLoader.hpp" #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <numeric> #include <map> #include <set> using namespace std; using glm::vec3; //string split helper vector<string> split(string s, char delim) { vector<string> ret; ret.reserve(10u); auto idx0 = 0u; auto idx1 = s.find(delim); while (idx1 != string::npos) { ret.push_back(s.substr(idx0, idx1 - idx0)); idx0 = idx1 + 1; idx1 = s.find(delim, idx0); } ret.push_back(s.substr(idx0)); return ret; } // Function to read input data values bool readvals(string &s, const unsigned int numvals, GLfloat* values) { auto parts = split(s, ' '); if (parts.size() > numvals) { cout << "More values requested than available! will skip...\n"; return false; } for (auto i = 0u; i < numvals; i++) { auto& str = parts[i]; try { auto v = std::stof(str); values[i] = v; } catch (std::exception) { cout << "Failed reading value " << i << " will skip\n"; return false; } } return true; } bool readvals(string &s, const unsigned int numvals, int* values) { auto parts = split(s, ' '); if (parts.size() > numvals) { cout << "More values requested than available! will skip...\n"; return false; } for (auto i = 0u; i < numvals; i++) { auto& str = parts[i]; try { auto v = std::stoi(str); values[i] = v; } catch (std::exception) { cout << "Failed reading value " << i << " will skip\n"; return false; } } return true; } // helper to push float members of a vec3 to a vector void addToVec(std::vector<const GLfloat> &c, const glm::vec3 &v) { c.push_back(v.x); c.push_back(v.y); c.push_back(v.z); } // helper to calculate averaged vertex normal void addToVec(std::vector<const GLfloat> &c, const set<Face*> &s) { vec3 average_normal; for (auto f : s) average_normal += f->normal; average_normal = glm::normalize(average_normal); c.push_back(average_normal.x); c.push_back(average_normal.y); c.push_back(average_normal.z); } void loadObj(string obj_file, Obj &obj) { // disable syncing with c stdio functions, we only need c++ streams! // improves performance of streams a lot! std::ios::sync_with_stdio(false); ifstream file(obj_file); if (file.is_open()) { auto& faces = obj.faces; auto& vertices = obj.vertices; // count lines in file auto count = static_cast<unsigned int>(std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n')); // jump back to beginning of file file.clear(); file.seekg(0, ios::beg); // reserve enough space to make sure that the container won't ever resize! // a resize would invalidate all references and pointer to its objects and i // have these! faces.clear(); faces.reserve(count); vertices.clear(); vertices.reserve(count); // for averaging vertex normals map<vec3*, set<Face*>> vtx_triangle_map; // read file line by line as long as it's good while (file.good()) { // read line string line; getline(file, line); if (line.empty()) continue; // extract mode (v, f, vn, ...) auto mode = split(line, ' ')[0]; // erase mode from input line line = line.substr(mode.length()+1); // interpret mode if (mode == "#") continue; else if (mode == "v") { // read vertex data vector<float> coords(3, 0.0f); if (readvals(line, 3, &coords[0])) { vertices.push_back(vec3(coords[0], coords[1], coords[2])); } } else if (mode == "f") { // read triangle face, vertices are indexed beginning from 1 // strip out any normals or texture specification if (line.find("/") != string::npos) { auto vertex_indices = split(line, ' '); auto stripped_indices = accumulate(begin(vertex_indices), end(vertex_indices), string(), [](string &left, string right) -> string { auto spl = split(right, '/'); return left + " " + spl[0]; }); line = stripped_indices.substr(1); // remove leading whitespace } vector<int> idx(3, 0); if (readvals(line, 3, &idx[0])) { std::transform(begin(idx), end(idx), begin(idx), [](int i) -> int { return i-1; }); auto& v1 = vertices[idx[0]]; auto& v2 = vertices[idx[1]]; auto& v3 = vertices[idx[2]]; auto face = Face(v1, v2, v3); faces.emplace_back(face); // save the triangle for each vertex for averaging normals vtx_triangle_map[&v1].insert(&faces.back()); vtx_triangle_map[&v2].insert(&faces.back()); vtx_triangle_map[&v3].insert(&faces.back()); } } } file.close(); // generate vertex and normal array for fast opengl rendering auto& gl_vertices = obj.gl_vertices; auto& gl_normals = obj.gl_normals; auto& gl_normals_average = obj.gl_normals_average; gl_vertices.clear(); gl_vertices.reserve(vertices.size()); gl_normals.clear(); gl_normals.reserve(vertices.size()); gl_normals_average.clear(); gl_normals_average.reserve(vertices.size()); for (auto& face : faces) { addToVec(gl_vertices, face.v0); addToVec(gl_vertices, face.v1); addToVec(gl_vertices, face.v2); addToVec(gl_normals, face.normal); addToVec(gl_normals, face.normal); addToVec(gl_normals, face.normal); // generate averaged vertex normals addToVec(gl_normals_average, vtx_triangle_map[&face.v0]); addToVec(gl_normals_average, vtx_triangle_map[&face.v1]); addToVec(gl_normals_average, vtx_triangle_map[&face.v2]); } } else { throw std::exception((string("Unable to open file ") + obj_file).c_str()); } }<commit_msg>refactoring for more performance improvements<commit_after>#include "objLoader.hpp" #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <numeric> #include <map> #include <set> using namespace std; using glm::vec3; //string split helper vector<string> split(const string &s, char delim) { vector<string> ret; ret.reserve(10u); auto idx0 = 0u; auto idx1 = s.find(delim); while (idx1 != string::npos) { ret.push_back(s.substr(idx0, idx1 - idx0)); idx0 = idx1 + 1; idx1 = s.find(delim, idx0); } ret.push_back(s.substr(idx0)); return ret; } // Function to read input data values bool readvals(const string &s, const unsigned int numvals, GLfloat* values) { auto parts = split(s, ' '); if (parts.size() > numvals) { cout << "More values requested than available! will skip...\n"; return false; } for (auto i = 0u; i < numvals; i++) { auto& str = parts[i]; try { auto v = std::stof(str); values[i] = v; } catch (std::exception) { cout << "Failed reading value " << i << " will skip\n"; return false; } } return true; } bool readvals(string &s, const unsigned int numvals, int* values) { auto parts = split(s, ' '); if (parts.size() > numvals) { cout << "More values requested than available! will skip...\n"; return false; } for (auto i = 0u; i < numvals; i++) { auto& str = parts[i]; try { auto v = std::stoi(str); values[i] = v; } catch (std::exception) { cout << "Failed reading value " << i << " will skip\n"; return false; } } return true; } // helper to push float members of a vec3 to a vector void addToVec(std::vector<const GLfloat> &c, const glm::vec3 &v) { c.push_back(v.x); c.push_back(v.y); c.push_back(v.z); } // helper to calculate averaged vertex normal void addToVec(std::vector<const GLfloat> &c, const set<Face*> &s) { vec3 average_normal; for (auto f : s) average_normal += f->normal; average_normal = glm::normalize(average_normal); c.push_back(average_normal.x); c.push_back(average_normal.y); c.push_back(average_normal.z); } void loadObj(string obj_file, Obj &obj) { // disable syncing with c stdio functions, we only need c++ streams! // improves performance of streams a lot! std::ios::sync_with_stdio(false); ifstream file(obj_file); if (file.is_open()) { file.close(); // file will be read without stream methods for speed! vector<string> vertex_cmds; vector<string> face_cmds; FILE* fileptr; fopen_s(&fileptr, obj_file.c_str(), "r"); // read file line by line as long as it's good const auto linelength = 4096u; char cline[linelength]; while (fgets(cline, linelength, fileptr) != NULL) { // convert line to string string line(cline); line.erase(line.end() - 1); // remove newline // skip empty lines if (line.empty()) continue; // extract command mode (v, f, #, vn, ...), search foe whitespace auto idx = 0u; while (line[idx] != ' ') ++idx; auto mode = line.substr(0, idx); // erase mode from input line line = line.substr(idx+1); // put line in corresponding container if (mode == "#") continue; else if (mode == "v") vertex_cmds.push_back(line); else if (mode == "f") face_cmds.push_back(line); } file.close(); auto& faces = obj.faces; auto& vertices = obj.vertices; // reserve enough space to make sure that the container won't ever resize! // a resize would invalidate all references and pointer to its objects! faces.clear(); faces.reserve(face_cmds.size()); vertices.clear(); vertices.reserve(vertex_cmds.size()); // convert vertex lines into vertices for (const auto& vertex_cmd : vertex_cmds) { // read vertex data vector<float> coords(3, 0.0f); if (readvals(vertex_cmd, 3, &coords[0])) { vertices.push_back(vec3(coords[0], coords[1], coords[2])); } } // for averaging vertex normals, this stores a list of Faces the vertex contributes to map<vec3*, set<Face*>> vtx_triangle_map; for (auto& vtx : vertices) vtx_triangle_map.insert(make_pair(&vtx, set<Face*>())); // read triangle face --- vertices are indexed beginning from 1 for (auto& face_cmd : face_cmds) { // strip out any normals or texture specification if (face_cmd.find("/") != string::npos) { auto vertex_indices = split(face_cmd, ' '); auto stripped_indices = accumulate(begin(vertex_indices), end(vertex_indices), string(), [](string &left, string right) -> string { auto spl = split(right, '/'); return left + " " + spl[0]; }); face_cmd = stripped_indices.substr(1); // remove leading whitespace } // convert indices vector<int> idx(3, 0); if (readvals(face_cmd, 3, &idx[0])) { // vertices are indexed beginning at 1 in a obj file, so subtract 1 to map to zero-indexed array std::transform(begin(idx), end(idx), begin(idx), [](int i) -> int { return i-1; }); auto& v1 = vertices[idx[0]]; auto& v2 = vertices[idx[1]]; auto& v3 = vertices[idx[2]]; auto face = Face(v1, v2, v3); faces.emplace_back(face); // save the triangle for each vertex --- used for averaged normals vtx_triangle_map[&v1].insert(&faces.back()); vtx_triangle_map[&v2].insert(&faces.back()); vtx_triangle_map[&v3].insert(&faces.back()); } } // generate vertex and normal array for fast opengl rendering auto& gl_vertices = obj.gl_vertices; auto& gl_normals = obj.gl_normals; auto& gl_normals_average = obj.gl_normals_average; gl_vertices.clear(); gl_vertices.reserve(vertices.size()); gl_normals.clear(); gl_normals.reserve(vertices.size()); gl_normals_average.clear(); gl_normals_average.reserve(vertices.size()); for (auto& face : faces) { addToVec(gl_vertices, face.v0); addToVec(gl_vertices, face.v1); addToVec(gl_vertices, face.v2); addToVec(gl_normals, face.normal); addToVec(gl_normals, face.normal); addToVec(gl_normals, face.normal); // generate averaged vertex normals addToVec(gl_normals_average, vtx_triangle_map[&face.v0]); addToVec(gl_normals_average, vtx_triangle_map[&face.v1]); addToVec(gl_normals_average, vtx_triangle_map[&face.v2]); } } else { throw std::exception((string("Unable to open file ") + obj_file).c_str()); } }<|endoftext|>
<commit_before>#include <iostream> #include <cassert> #include "CompareCmd.h" #include "StringUtils.h" #include "MeshPart.h" #include "Tet.h" #include "Hex.h" #include "Numeric.h" #include "AnnLocator.h" #include "HdfReader.h" #include "VtkReader.h" #include "VtkWriter.h" #include "Timer.h" #include "Misc.h" using namespace std; // --------------------------------------------------------------------------- cigma::CompareCmd::CompareCmd() { name = "compare"; // integrating mesh mesh = 0; quadrature = 0; // fields field_a = 0; field_b = 0; // residuals residuals = new ResidualField(); // parameters verbose = false; output_frequency = 0; } cigma::CompareCmd::~CompareCmd() { delete residuals; } // --------------------------------------------------------------------------- void cigma::CompareCmd::setupOptions(AnyOption *opt) { std::cout << "Calling cigma::CompareCmd::setupOptions()" << std::endl; assert(opt != 0); /* setup usage */ opt->addUsage("Usage:"); opt->addUsage(" cigma compare [options]"); opt->addUsage(" -a --first First field location"); opt->addUsage(" -b --second Second field location"); opt->addUsage(" -r --rule Quadrature rule location"); opt->addUsage(" -o --output Output file"); /* setup flags and options */ opt->setFlag("help", 'h'); opt->setFlag("debug"); // XXX: uses specific defaults // options for mesh opt->setOption("mesh"); opt->setOption("mesh-coordinates"); opt->setOption("mesh-connectivity"); // options for quadrature opt->setOption("rule",'r'); opt->setOption("rule-order"); opt->setOption("rule-points"); opt->setOption("rule-weights"); // options for first field, in the form /path/to/file:/path/to/dset opt->setOption("first",'a'); opt->setOption("first-mesh"); opt->setOption("first-mesh-coordinates"); opt->setOption("first-mesh-connectivity"); // option for second field, in the form /path/to/file:/path/to/dset opt->setOption("second",'b'); opt->setOption("second-mesh"); opt->setOption("second-mesh-coordinates"); opt->setOption("second-mesh-connectivity"); // options for output opt->setOption("output",'o'); // other options opt->setFlag("verbose"); opt->setOption("output-frequency",'f'); } void cigma::CompareCmd::configure(AnyOption *opt) { std::cout << "Calling cigma::CompareCmd::configure()" << std::endl; string field_prefix; std::string inputstr; char *in; /* Check if --verbose was enabled */ verbose = opt->getFlag("verbose"); if (verbose) { output_frequency = 1000; } /* Determine the --output-frequency option */ in = opt->getValue("output-frequency"); if (in != 0) { inputstr = in; string_to_int(inputstr, output_frequency); } if (output_frequency == 0) { // XXX: emit warning, or quit? if (opt->getValue("output-frequency") != 0) { cerr << "compare: Warning: ignoring option --output-frequency" << endl; } verbose = false; } /* Determine the --output option */ in = opt->getValue("output"); if (in == 0) { if (opt->getFlag("debug")) { // XXX: provide default name when in debug mode in = (char *)"foo.vtk"; } else { cerr << "compare: Please specify the option --output" << endl; exit(1); } } output_path = in; /* * Initialization order: * Load First field * If FE_Field * Load DofsA * Load MeshA if req'd * Load RuleA if req'd * Else * Load Analytic Field * Load Second field * If FE_Field * Load DofsB * Load MeshB if req'd * Load RuleB if req'd * Else * Load Analytic Field * Load Integration mesh * Load Quadrature rule */ /* Gather up the expected command line arguments */ load_args(opt, &meshIO, "mesh"); load_args(opt, &quadratureIO, "rule"); load_args(opt, &firstIO, "first"); load_args(opt, &secondIO, "second"); /* Validate these arguments and complain about missing ones */ if (opt->getFlag("debug")) { // // assign defaults if we're in debug mode. this overrides // the command line settings from load_args() // if (firstIO.field_path == "") firstIO.field_path = "./tests/strikeslip_tet4_1000m_t0.vtk:displacements_t0"; if (secondIO.field_path == "") secondIO.field_path = "./tests/strikeslip_hex8_1000m_t0.vtk:displacements_t0"; } validate_args(&firstIO, "compare"); validate_args(&secondIO, "compare"); validate_args(&meshIO, "compare"); validate_args(&quadratureIO, "compare"); /* Load the datasets into memory */ firstIO.load(); field_a = firstIO.field; assert(field_a != 0); field_a->fe = new FE(); field_a->fe->set_cell(field_a->meshPart->cell); cout << "first field path = " << firstIO.field_path << endl; cout << "first field dimensions = " << field_a->meshPart->nel << " cells, " << field_a->meshPart->nno << " nodes, " << field_a->fe->cell->n_nodes() << " dofs/cell, " << "rank " << field_a->n_rank() << endl; secondIO.load(); field_b = secondIO.field; assert(field_b != 0); field_b->fe = new FE(); field_b->fe->set_cell(field_b->meshPart->cell); cout << "second field path = " << secondIO.field_path << endl; cout << "second field dimensions = " << field_b->meshPart->nel << " cells, " << field_b->meshPart->nno << " nodes, " << field_b->fe->cell->n_nodes() << " dofs/cell, " << "rank " << field_b->n_rank() << endl; /* XXX: if no --mesh option was specified, get mesh from the * first field. if the first field has no mesh, (e.g. specified * by an analytic soln), then try using the second field's mesh. * if we still don't have a mesh that we can use for the integration, * then exit with an error suggesting the user to specify the --mesh * option. */ meshIO.load(); mesh = meshIO.meshPart; if (mesh == 0) { mesh = firstIO.field->meshPart; } assert(mesh != 0); residuals->set_mesh(mesh); /* Now load the quadrature rule. If no rule is specified on the * command line, a default rule is assigned based on the type of * the cell. Also, an exception is thrown if the specified a rule * does not conform geometrically to the interior of the cell. */ quadratureIO.load(mesh->cell); quadrature = quadratureIO.quadrature; assert(quadrature != 0); field_a->fe->set_quadrature(quadrature); return; } int cigma::CompareCmd::run() { std::cout << "Calling cigma::CompareCmd::run()" << std::endl; assert(mesh != 0); assert(quadrature != 0); assert(field_a != 0); assert(field_b != 0); // make sure the field dimensions match // XXX: need graceful failure mode assert(field_a->n_dim() == field_a->n_dim()); assert(field_a->n_rank() == field_b->n_rank()); Cell *cell_a = field_a->fe->cell; Cell *cell_b = field_b->fe->cell; assert(cell_a->n_celldim() == cell_b->n_celldim()); // indices int e,q; int i,j; // dimensions int nel = mesh->nel; int nq = quadrature->n_points(); int ndofs = cell_a->n_nodes(); int valdim = field_a->n_rank(); // local data; double *jxw = field_a->fe->jxw; double *phi_a = new double[nq * valdim]; // XXX: not needed when using tabulation double *phi_b = new double[nq * valdim]; // norm double L2 = 0.0; double *epsilon = residuals->epsilon; // XXX: don't forget about the case when (mesh != field_a->meshPart) // Regardless, this cell pointer needs to come from the integrating // mesh object, not from field_a. Cell *cell = cell_a; // start timer Timer timer; if (verbose) { std::cout << std::setprecision(5); timer.print_header(std::cout, "elts"); timer.start(nel); timer.update(0); std::cout << timer; } // XXX: time to move this main loop into its own function // so we can use polymorphic dispatch on the argument types for (e = 0; e < nel; e++) { // update cell data mesh->select_cell(e); // obtain global points from current quadrature rule quadrature->apply_refmap(cell); // ... calculate phi_a[] // XXX: using eval() -- applicable in general (Field obj) //for (q = 0; q < nq; q++) //{ // field_a->eval((*quadrature)[q], &phi_a[valdim*q]); //} // ... calculate phi_a[] // XXX: using tabulation -- applicable to FE_Field obj field_a->tabulate_element(e, phi_a); // ... calculate phi_b[] for (q = 0; q < nq; q++) { field_b->eval((*quadrature)[q], &phi_b[valdim*q]); } // evaluate jacobian at known quadrature points field_a->fe->update_jxw(); // XXX: somehow, this method needs to be attached // to the MeshPart object, so maybe it needs its // own FE object after all? // ... apply quadrature rule double err = 0.0; for (q = 0; q < nq; q++) { for (i = 0; i < valdim; i++) { int qi = valdim*q + i; err += jxw[q] * SQR(phi_a[qi] - phi_b[qi]); } } epsilon[e] = err; L2 += err; // XXX: debug info if (verbose && ((e+1) % output_frequency == 0)) { timer.update(e+1); std::cout << timer; } } if (verbose) { timer.update(nel); std::cout << timer << std::endl; } L2 = sqrt(L2); std::cout << std::setprecision(12); std::cout << "L2 = " << L2 << std::endl; /* write out data */ residuals->write_vtk(output_path.c_str()); /* clean up */ delete [] phi_a; delete [] phi_b; return 0; } // --------------------------------------------------------------------------- <commit_msg>Took main loop out of CompareCmd::run() * Verified that (FE_Field,FE_Field) comparison still works * Next comparison to check is (FE_Field,PointField)<commit_after>#include <iostream> #include <cassert> #include "CompareCmd.h" #include "StringUtils.h" #include "MeshPart.h" #include "Tet.h" #include "Hex.h" #include "Numeric.h" #include "AnnLocator.h" #include "HdfReader.h" #include "VtkReader.h" #include "VtkWriter.h" #include "Timer.h" #include "Misc.h" using namespace std; using namespace cigma; // --------------------------------------------------------------------------- cigma::CompareCmd::CompareCmd() { name = "compare"; // integrating mesh mesh = 0; quadrature = 0; // fields field_a = 0; field_b = 0; // residuals residuals = new ResidualField(); // parameters verbose = false; output_frequency = 0; } cigma::CompareCmd::~CompareCmd() { delete residuals; } // --------------------------------------------------------------------------- void cigma::CompareCmd::setupOptions(AnyOption *opt) { std::cout << "Calling cigma::CompareCmd::setupOptions()" << std::endl; assert(opt != 0); /* setup usage */ opt->addUsage("Usage:"); opt->addUsage(" cigma compare [options]"); opt->addUsage(" -a --first First field location"); opt->addUsage(" -b --second Second field location"); opt->addUsage(" -r --rule Quadrature rule location"); opt->addUsage(" -o --output Output file"); /* setup flags and options */ opt->setFlag("help", 'h'); opt->setFlag("debug"); // XXX: uses specific defaults // options for mesh opt->setOption("mesh"); opt->setOption("mesh-coordinates"); opt->setOption("mesh-connectivity"); // options for quadrature opt->setOption("rule",'r'); opt->setOption("rule-order"); opt->setOption("rule-points"); opt->setOption("rule-weights"); // options for first field, in the form /path/to/file:/path/to/dset opt->setOption("first",'a'); opt->setOption("first-mesh"); opt->setOption("first-mesh-coordinates"); opt->setOption("first-mesh-connectivity"); // option for second field, in the form /path/to/file:/path/to/dset opt->setOption("second",'b'); opt->setOption("second-mesh"); opt->setOption("second-mesh-coordinates"); opt->setOption("second-mesh-connectivity"); // options for output opt->setOption("output",'o'); // other options opt->setFlag("verbose"); opt->setOption("output-frequency",'f'); } void cigma::CompareCmd::configure(AnyOption *opt) { std::cout << "Calling cigma::CompareCmd::configure()" << std::endl; string field_prefix; std::string inputstr; char *in; /* Check if --verbose was enabled */ verbose = opt->getFlag("verbose"); if (verbose) { output_frequency = 1000; } /* Determine the --output-frequency option */ in = opt->getValue("output-frequency"); if (in != 0) { inputstr = in; string_to_int(inputstr, output_frequency); } if (output_frequency == 0) { // XXX: emit warning, or quit? if (opt->getValue("output-frequency") != 0) { cerr << "compare: Warning: ignoring option --output-frequency" << endl; } verbose = false; } /* Determine the --output option */ in = opt->getValue("output"); if (in == 0) { if (opt->getFlag("debug")) { // XXX: provide default name when in debug mode in = (char *)"foo.vtk"; } else { cerr << "compare: Please specify the option --output" << endl; exit(1); } } output_path = in; /* * Initialization order: * Load First field * If FE_Field * Load DofsA * Load MeshA if req'd * Load RuleA if req'd * Else * Load Analytic Field * Load Second field * If FE_Field * Load DofsB * Load MeshB if req'd * Load RuleB if req'd * Else * Load Analytic Field * Load Integration mesh * Load Quadrature rule */ /* Gather up the expected command line arguments */ load_args(opt, &meshIO, "mesh"); load_args(opt, &quadratureIO, "rule"); load_args(opt, &firstIO, "first"); load_args(opt, &secondIO, "second"); /* Validate these arguments and complain about missing ones */ if (opt->getFlag("debug")) { // // assign defaults if we're in debug mode. this overrides // the command line settings from load_args() // if (firstIO.field_path == "") firstIO.field_path = "./tests/strikeslip_tet4_1000m_t0.vtk:displacements_t0"; if (secondIO.field_path == "") secondIO.field_path = "./tests/strikeslip_hex8_1000m_t0.vtk:displacements_t0"; } validate_args(&firstIO, "compare"); validate_args(&secondIO, "compare"); validate_args(&meshIO, "compare"); validate_args(&quadratureIO, "compare"); /* Load the datasets into memory */ firstIO.load(); field_a = firstIO.field; assert(field_a != 0); field_a->fe = new FE(); field_a->fe->set_cell(field_a->meshPart->cell); cout << "first field path = " << firstIO.field_path << endl; cout << "first field dimensions = " << field_a->meshPart->nel << " cells, " << field_a->meshPart->nno << " nodes, " << field_a->fe->cell->n_nodes() << " dofs/cell, " << "rank " << field_a->n_rank() << endl; secondIO.load(); field_b = secondIO.field; assert(field_b != 0); field_b->fe = new FE(); field_b->fe->set_cell(field_b->meshPart->cell); cout << "second field path = " << secondIO.field_path << endl; cout << "second field dimensions = " << field_b->meshPart->nel << " cells, " << field_b->meshPart->nno << " nodes, " << field_b->fe->cell->n_nodes() << " dofs/cell, " << "rank " << field_b->n_rank() << endl; /* XXX: if no --mesh option was specified, get mesh from the * first field. if the first field has no mesh, (e.g. specified * by an analytic soln), then try using the second field's mesh. * if we still don't have a mesh that we can use for the integration, * then exit with an error suggesting the user to specify the --mesh * option. */ meshIO.load(); mesh = meshIO.meshPart; if (mesh == 0) { mesh = firstIO.field->meshPart; } assert(mesh != 0); residuals->set_mesh(mesh); /* Now load the quadrature rule. If no rule is specified on the * command line, a default rule is assigned based on the type of * the cell. Also, an exception is thrown if the specified a rule * does not conform geometrically to the interior of the cell. */ quadratureIO.load(mesh->cell); quadrature = quadratureIO.quadrature; assert(quadrature != 0); field_a->fe->set_quadrature(quadrature); return; } // --------------------------------------------------------------------------- void compare(CompareCmd *env, MeshPart *mesh, FE_Field *field_a, FE_Field *field_b) { assert(env != 0); const int output_frequency = env->output_frequency; const bool verbose = env->verbose; // XXX: remove need for this assert stmt ... assert(mesh == field_a->meshPart); // XXX: first variable block Cell *cell = field_a->fe->cell; // XXX: change to mesh->fe->cell Quadrature *quadrature = field_a->fe->quadrature; // XXX: change to mesh->fe->quadrature ResidualField *residuals = env->residuals; // dimensions int nel = mesh->nel; int nq = field_a->fe->quadrature->n_points(); // XXX: change to mesh->fe->quadrature->n_points() int ndofs = cell->n_nodes(); int valdim = field_a->n_rank(); // local data double *jxw = field_a->fe->jxw; // XXX: change to mesh->fe->jxw double *phi_a = new double[nq * valdim]; // XXX: use Points object? double *phi_b = new double[nq * valdim]; // XXX: use Points object? // norm double L2 = 0.0; double *epsilon = residuals->epsilon; // start timer Timer timer; if (verbose) { cout << std::setprecision(5); timer.print_header(cout, "elts"); timer.start(nel); timer.update(0); cout << timer; } int e,q,i; for (e = 0; e < nel; e++) { // update cell data mesh->select_cell(e); // obtain global points from current quadrature rule quadrature->apply_refmap(cell); // ... calculate phi_a[] field_a->tabulate_element(e, phi_a); // XXX: second variable block // ... calculate phi_b[] // XXX: change this to field_b->eval(quadrature, phi_b)? // do this if we make phi_b an object of type (Points *) for (q = 0; q < nq; q++) { field_b->eval((*quadrature)[q], &phi_b[valdim*q]); } // evaluate jacobian at qpts // XXX: change this to mesh->fe->update_jxw() field_a->fe->update_jxw(); // apply norm // XXX: calculate squared_differences from phi_a, phi_b // XXX: other norms? // apply quadrature rule // XXX: change this to: err = mesh->quadrature->L2(phi_a, phi_b) // XXX: alternative : err = mesh->quadrature->apply(squared_differences) double err = 0.0; for (q = 0; q < nq; q++) { for (i = 0; i < valdim; i++) { int qi = valdim*q + i; err += jxw[q] * SQR(phi_a[qi] - phi_b[qi]); } } epsilon[e] = err; L2 += err; // debug info if (verbose && ((e+1) % output_frequency == 0)) { timer.update(e+1); cout << timer; } } if (verbose) { timer.update(nel); cout << timer << endl; } // report global norm L2 = sqrt(L2); cout << setprecision(12); cout << "L2 = " << L2 << endl; // write out data residuals->write_vtk(env->output_path.c_str()); // clean up delete [] phi_a; delete [] phi_b; } /* XXX: first, time the effects of introducing branches in the main loop void compare(MeshPart *mesh, FE_Field *field_a, Field *field_b, ResidualField *residuals, int output_frequency) { } void compare(FE_Field *field_a, Field *field_b, ResidualField *residuals, int output_frequency) { } void compare(FE_Field *field_a, PointField *field_b, ResidualField *residuals, int output_frequency) { } void compare(MeshPart *mesh, Field *field_a, PointField *field_b, ResidualField *residuals, int output_frequency) { } // */ //* XXX: new run() method int cigma::CompareCmd::run() { std::cout << "Calling cigma::CompareCmd::run()" << std::endl; // // XXX: need to fail gracefully at this point, instead of throwing // a nasty assert statement whenever something unexpected happens. // clean up memory management so that we can use exceptions, and // verify that all resources are properly finalized. // // start with the obvious checks assert(mesh != 0); assert(quadrature != 0); assert(field_a != 0); assert(field_b != 0); // make sure the field dimensions match assert(field_a->n_dim() == field_a->n_dim()); assert(field_a->n_rank() == field_b->n_rank()); // XXX: call the appropriate compare method based on the field types // XXX: enclose statements in a try-catch-finally clause compare(this, mesh, field_a, field_b); return 0; } // */ /* XXX: old run() method int cigma::CompareCmd::run() { std::cout << "Calling cigma::CompareCmd::run()" << std::endl; assert(mesh != 0); assert(quadrature != 0); assert(field_a != 0); assert(field_b != 0); // make sure the field dimensions match // XXX: need graceful failure mode assert(field_a->n_dim() == field_a->n_dim()); assert(field_a->n_rank() == field_b->n_rank()); Cell *cell_a = field_a->fe->cell; Cell *cell_b = field_b->fe->cell; assert(cell_a->n_celldim() == cell_b->n_celldim()); // indices int e,q; int i,j; // dimensions int nel = mesh->nel; int nq = quadrature->n_points(); int ndofs = cell_a->n_nodes(); int valdim = field_a->n_rank(); // local data; double *jxw = field_a->fe->jxw; double *phi_a = new double[nq * valdim]; // XXX: not needed when using tabulation double *phi_b = new double[nq * valdim]; // norm double L2 = 0.0; double *epsilon = residuals->epsilon; // XXX: don't forget about the case when (mesh != field_a->meshPart) // Regardless, this cell pointer needs to come from the integrating // mesh object, not from field_a. Cell *cell = cell_a; // start timer Timer timer; if (verbose) { std::cout << std::setprecision(5); timer.print_header(std::cout, "elts"); timer.start(nel); timer.update(0); std::cout << timer; } // XXX: time to move this main loop into its own function // so we can use polymorphic dispatch on the argument types for (e = 0; e < nel; e++) { // update cell data mesh->select_cell(e); // obtain global points from current quadrature rule quadrature->apply_refmap(cell); // ... calculate phi_a[] // XXX: using eval() -- applicable in general (Field obj) //for (q = 0; q < nq; q++) //{ // field_a->eval((*quadrature)[q], &phi_a[valdim*q]); //} // ... calculate phi_a[] // XXX: using tabulation -- applicable to FE_Field obj field_a->tabulate_element(e, phi_a); // ... calculate phi_b[] for (q = 0; q < nq; q++) { field_b->eval((*quadrature)[q], &phi_b[valdim*q]); } // evaluate jacobian at known quadrature points field_a->fe->update_jxw(); // XXX: somehow, this method needs to be attached // to the MeshPart object, so maybe it needs its // own FE object after all? // ... apply quadrature rule double err = 0.0; for (q = 0; q < nq; q++) { for (i = 0; i < valdim; i++) { int qi = valdim*q + i; err += jxw[q] * SQR(phi_a[qi] - phi_b[qi]); } } epsilon[e] = err; L2 += err; // XXX: debug info if (verbose && ((e+1) % output_frequency == 0)) { timer.update(e+1); std::cout << timer; } } if (verbose) { timer.update(nel); std::cout << timer << std::endl; } L2 = sqrt(L2); std::cout << std::setprecision(12); std::cout << "L2 = " << L2 << std::endl; // write out data residuals->write_vtk(output_path.c_str()); // clean up delete [] phi_a; delete [] phi_b; return 0; } // */ // --------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* Mailbox Copyright (C) 2015 Will Penington This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QString> #include <QtTest> #include "erlangshell.h" #include "mailboxqt.h" #include "client.h" class MailboxTest : public QObject { Q_OBJECT public: MailboxTest(); private Q_SLOTS: void canCommunicateWithErlangShell_data(); void canCommunicateWithErlangShell(); void canSendMessageToErlang(); void canRecieveMessagesFromErlang(); }; MailboxTest::MailboxTest() { Mailbox::init(); } void MailboxTest::canCommunicateWithErlangShell_data() { QTest::addColumn<QByteArray>("statement"); QTest::addColumn<QByteArray>("expected"); QTest::newRow("atom") << QByteArray("sample_atom.") << QByteArray("sample_atom\n"); QTest::newRow("maths") << QByteArray("1 + 1.") << QByteArray("2\n"); QTest::newRow("complex types") << QByteArray("[{foo, bar}, 1 + 3, baz].") << QByteArray("[{foo,bar},4,baz]\n"); } void MailboxTest::canCommunicateWithErlangShell() { ErlangShell erl("dummy"); QFETCH(QByteArray, statement); QTEST(erl.execStatement(statement), "expected"); } void MailboxTest::canSendMessageToErlang() { ErlangShell erl("sendmessage"); Mailbox::Client node("sendmessage", "sendmessagelib"); erl.execStatement("register(shell, self())."); QCOMPARE(erl.execStatement("flush()."), "Shell got sendmessage"); } void MailboxTest::canRecieveMessagesFromErlang() { ErlangShell erl("recvmessage"); Mailbox::Client *node("recvmessage", "recvmessagelib"); QSignalSpy recvSpy(node, SIGNAL(messageRecieved)); erl.execStatement("{sendmessagelib, foo} ! bar."); QVERIFY(recvSpy.wait(1000)); QCOMPARE(recvSpy.count(), 1); } QTEST_APPLESS_MAIN(MailboxTest) #include "tst_mailboxtest.moc" <commit_msg>Send Message Test Case Fixups<commit_after>/* Mailbox Copyright (C) 2015 Will Penington This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QString> #include <QtTest> #include "erlangshell.h" #include "mailboxqt.h" #include "client.h" class MailboxTest : public QObject { Q_OBJECT public: MailboxTest(); private Q_SLOTS: void canCommunicateWithErlangShell_data(); void canCommunicateWithErlangShell(); void canSendMessageToErlang(); void canRecieveMessagesFromErlang(); }; MailboxTest::MailboxTest() { Mailbox::init(); } void MailboxTest::canCommunicateWithErlangShell_data() { QTest::addColumn<QByteArray>("statement"); QTest::addColumn<QByteArray>("expected"); QTest::newRow("atom") << QByteArray("sample_atom.") << QByteArray("sample_atom\n"); QTest::newRow("maths") << QByteArray("1 + 1.") << QByteArray("2\n"); QTest::newRow("complex types") << QByteArray("[{foo, bar}, 1 + 3, baz].") << QByteArray("[{foo,bar},4,baz]\n"); } void MailboxTest::canCommunicateWithErlangShell() { ErlangShell erl("dummy"); QFETCH(QByteArray, statement); QTEST(erl.execStatement(statement), "expected"); } void MailboxTest::canSendMessageToErlang() { ErlangShell erl("sendmessage"); Mailbox::Client *node = new Mailbox::Client("sendmessage", "sendmessagelib"); erl.execStatement("register(shell, self())."); node->sendAtom("shell", "testmessage"); QCOMPARE(erl.execStatement("flush()."), "Shell got sendmessage"); } void MailboxTest::canRecieveMessagesFromErlang() { ErlangShell erl("recvmessage"); Mailbox::Client *node = new Mailbox::Client("recvmessage", "recvmessagelib"); QSignalSpy recvSpy(node, SIGNAL(messageRecieved)); erl.execStatement("{sendmessagelib, foo} ! bar."); QVERIFY(recvSpy.wait(1000)); QCOMPARE(recvSpy.count(), 1); } QTEST_APPLESS_MAIN(MailboxTest) #include "tst_mailboxtest.moc" <|endoftext|>
<commit_before>#include "control.h" int Curso::codigo = 0; void Control::inicializador() { U = new Universidad(); CE = new Contenedor_Escuelas(); CC = new Contenedor_Cursos(); Escuela* E1 = new Escuela("Ingles"); Escuela* E2 = new Escuela("Matematicas"); Escuela* E3 = new Escuela("Geologia"); Escuela* E4 = new Escuela("Sociales"); CE->insertaralInicio(E1); CE->insertaralInicio(E2); CE->insertaralInicio(E3); CE->insertaralInicio(E4); Curso* CU1 = new Curso("Programacion I", E1->getSiglaEscuela()); Curso* CU2 = new Curso("Programacion II", E2->getSiglaEscuela()); E1->insertarCurso(CU1); E2->insertarCurso(CU2); principal(); } void Control::principal() { Interfaz::vBienvenida(); if (Interfaz::vDatosPrimeraVez(U) == 'S') //Esto me funciona para luego en caso de que ya se hayan ingresado los datos { Interfaz::vIngresarNombre(U); Interfaz::vIngresarNumero(U); Interfaz::vIngresarDireccion(U); } bool end = false; do { char ans = Interfaz::vMenuPrincipal(); switch (ans) { case '1': { Interfaz::vtoString(U); break; } case '2': { Interfaz::vtoStringEscuelas(U, CE, '1'); break; } case '3': { Interfaz::vtoStringEscuelas(U, CE, '2'); break; } case '4': { ajustes(); break; } case '5': { delete CC; delete CE; //se encarga de eliminar donde estan alojadas las escuelas (composicion) delete U; end = true; break; } default: break; } } while (end == false); } void Control::ajustes() { bool end = false; do { char opcion = Interfaz::vMenuAjustes(U); if (U->getNombre() == "Undefined") { switch (opcion) { case '1': { Interfaz::vIngresarNombre(U); break; } case '2': { Interfaz::vIngresarNumero(U); break; } case '3': { Interfaz::vIngresarDireccion(U); break; } case '4': { end = true; break; } default: break; } } else { switch (opcion) { case '1': { Interfaz::vIngresarNumero(U); break; } case '2': { Interfaz::vIngresarDireccion(U); break; } case '3': { Interfaz::vIngresaEscuela(CE); } case '4': { end = true; break; } default: break; } } } while (end == false); } <commit_msg>Elimino un comentario ahi x<commit_after>#include "control.h" int Curso::codigo = 0; void Control::inicializador() { U = new Universidad(); CE = new Contenedor_Escuelas(); CC = new Contenedor_Cursos(); Escuela* E1 = new Escuela("Ingles"); Escuela* E2 = new Escuela("Matematicas"); Escuela* E3 = new Escuela("Geologia"); Escuela* E4 = new Escuela("Sociales"); CE->insertaralInicio(E1); CE->insertaralInicio(E2); CE->insertaralInicio(E3); CE->insertaralInicio(E4); Curso* CU1 = new Curso("Programacion I", E1->getSiglaEscuela()); Curso* CU2 = new Curso("Programacion II", E2->getSiglaEscuela()); E1->insertarCurso(CU1); E2->insertarCurso(CU2); principal(); } void Control::principal() { Interfaz::vBienvenida(); if (Interfaz::vDatosPrimeraVez(U) == 'S') { Interfaz::vIngresarNombre(U); Interfaz::vIngresarNumero(U); Interfaz::vIngresarDireccion(U); } bool end = false; do { char ans = Interfaz::vMenuPrincipal(); switch (ans) { case '1': { Interfaz::vtoString(U); break; } case '2': { Interfaz::vtoStringEscuelas(U, CE, '1'); break; } case '3': { Interfaz::vtoStringEscuelas(U, CE, '2'); break; } case '4': { ajustes(); break; } case '5': { delete CC; delete CE; //se encarga de eliminar donde estan alojadas las escuelas (composicion) delete U; end = true; break; } default: break; } } while (end == false); } void Control::ajustes() { bool end = false; do { char opcion = Interfaz::vMenuAjustes(U); if (U->getNombre() == "Undefined") { switch (opcion) { case '1': { Interfaz::vIngresarNombre(U); break; } case '2': { Interfaz::vIngresarNumero(U); break; } case '3': { Interfaz::vIngresarDireccion(U); break; } case '4': { end = true; break; } default: break; } } else { switch (opcion) { case '1': { Interfaz::vIngresarNumero(U); break; } case '2': { Interfaz::vIngresarDireccion(U); break; } case '3': { Interfaz::vIngresaEscuela(CE); } case '4': { end = true; break; } default: break; } } } while (end == false); } <|endoftext|>
<commit_before>/** @file Decoration.cxx ** Visual elements added over text. **/ // Copyright 1998-2007 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include "Platform.h" #include "Scintilla.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "Decoration.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif Decoration::Decoration(int indicator_) : next(0), indicator(indicator_) { } Decoration::~Decoration() { } bool Decoration::Empty() { return rs.Runs() == 1; } DecorationList::DecorationList() : currentIndicator(0), currentValue(1), current(0), lengthDocument(0), root(0), clickNotified(false) { } DecorationList::~DecorationList() { Decoration *deco = root; while (deco) { Decoration *decoNext = deco->next; delete deco; deco = decoNext; } root = 0; current = 0; } Decoration *DecorationList::DecorationFromIndicator(int indicator) { for (Decoration *deco=root; deco; deco = deco->next) { if (deco->indicator == indicator) { return deco; } } return 0; } Decoration *DecorationList::Create(int indicator, int length) { currentIndicator = indicator; Decoration *decoNew = new Decoration(indicator); decoNew->rs.InsertSpace(0, length); Decoration *decoPrev = 0; Decoration *deco = root; while (deco && (deco->indicator < indicator)) { decoPrev = deco; deco = deco->next; } if (decoPrev == 0) { decoNew->next = root; root = decoNew; } else { decoNew->next = deco; decoPrev->next = decoNew; } return decoNew; } void DecorationList::Delete(int indicator) { Decoration *decoToDelete = 0; if (root) { if (root->indicator == indicator) { decoToDelete = root; root = root->next; } else { Decoration *deco=root; while (deco->next && !decoToDelete) { if (deco->next && deco->next->indicator == indicator) { decoToDelete = deco->next; deco->next = decoToDelete->next; } else { deco = deco->next; } } } } if (decoToDelete) { delete decoToDelete; current = 0; } } void DecorationList::SetCurrentIndicator(int indicator) { currentIndicator = indicator; current = DecorationFromIndicator(indicator); currentValue = 1; } void DecorationList::SetCurrentValue(int value) { currentValue = value ? value : 1; } bool DecorationList::FillRange(int &position, int value, int &fillLength) { if (!current) { current = DecorationFromIndicator(currentIndicator); if (!current) { current = Create(currentIndicator, lengthDocument); } } bool changed = current->rs.FillRange(position, value, fillLength); if (current->Empty()) { Delete(currentIndicator); } return changed; } void DecorationList::InsertSpace(int position, int insertLength) { const bool atEnd = position == lengthDocument; lengthDocument += insertLength; for (Decoration *deco=root; deco; deco = deco->next) { deco->rs.InsertSpace(position, insertLength); if (atEnd) { deco->rs.FillRange(position, 0, insertLength); } } } void DecorationList::DeleteRange(int position, int deleteLength) { lengthDocument -= deleteLength; Decoration *deco; for (deco=root; deco; deco = deco->next) { deco->rs.DeleteRange(position, deleteLength); } DeleteAnyEmpty(); } void DecorationList::DeleteAnyEmpty() { Decoration *deco = root; while (deco) { if (deco->Empty()) { Delete(deco->indicator); deco = root; } else { deco = deco->next; } } } int DecorationList::AllOnFor(int position) { int mask = 0; for (Decoration *deco=root; deco; deco = deco->next) { if (deco->rs.ValueAt(position)) { mask |= 1 << deco->indicator; } } return mask; } int DecorationList::ValueAt(int indicator, int position) { Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.ValueAt(position); } return 0; } int DecorationList::Start(int indicator, int position) { Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.StartRun(position); } return 0; } int DecorationList::End(int indicator, int position) { Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.EndRun(position); } return 0; } <commit_msg>Bug #3487440. Fix bug where setting an indicator on for whole document had no effect since that was regarded as an empty indicator.<commit_after>/** @file Decoration.cxx ** Visual elements added over text. **/ // Copyright 1998-2007 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include "Platform.h" #include "Scintilla.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "Decoration.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif Decoration::Decoration(int indicator_) : next(0), indicator(indicator_) { } Decoration::~Decoration() { } bool Decoration::Empty() { return (rs.Runs() == 1) && (rs.AllSameAs(0)); } DecorationList::DecorationList() : currentIndicator(0), currentValue(1), current(0), lengthDocument(0), root(0), clickNotified(false) { } DecorationList::~DecorationList() { Decoration *deco = root; while (deco) { Decoration *decoNext = deco->next; delete deco; deco = decoNext; } root = 0; current = 0; } Decoration *DecorationList::DecorationFromIndicator(int indicator) { for (Decoration *deco=root; deco; deco = deco->next) { if (deco->indicator == indicator) { return deco; } } return 0; } Decoration *DecorationList::Create(int indicator, int length) { currentIndicator = indicator; Decoration *decoNew = new Decoration(indicator); decoNew->rs.InsertSpace(0, length); Decoration *decoPrev = 0; Decoration *deco = root; while (deco && (deco->indicator < indicator)) { decoPrev = deco; deco = deco->next; } if (decoPrev == 0) { decoNew->next = root; root = decoNew; } else { decoNew->next = deco; decoPrev->next = decoNew; } return decoNew; } void DecorationList::Delete(int indicator) { Decoration *decoToDelete = 0; if (root) { if (root->indicator == indicator) { decoToDelete = root; root = root->next; } else { Decoration *deco=root; while (deco->next && !decoToDelete) { if (deco->next && deco->next->indicator == indicator) { decoToDelete = deco->next; deco->next = decoToDelete->next; } else { deco = deco->next; } } } } if (decoToDelete) { delete decoToDelete; current = 0; } } void DecorationList::SetCurrentIndicator(int indicator) { currentIndicator = indicator; current = DecorationFromIndicator(indicator); currentValue = 1; } void DecorationList::SetCurrentValue(int value) { currentValue = value ? value : 1; } bool DecorationList::FillRange(int &position, int value, int &fillLength) { if (!current) { current = DecorationFromIndicator(currentIndicator); if (!current) { current = Create(currentIndicator, lengthDocument); } } bool changed = current->rs.FillRange(position, value, fillLength); if (current->Empty()) { Delete(currentIndicator); } return changed; } void DecorationList::InsertSpace(int position, int insertLength) { const bool atEnd = position == lengthDocument; lengthDocument += insertLength; for (Decoration *deco=root; deco; deco = deco->next) { deco->rs.InsertSpace(position, insertLength); if (atEnd) { deco->rs.FillRange(position, 0, insertLength); } } } void DecorationList::DeleteRange(int position, int deleteLength) { lengthDocument -= deleteLength; Decoration *deco; for (deco=root; deco; deco = deco->next) { deco->rs.DeleteRange(position, deleteLength); } DeleteAnyEmpty(); } void DecorationList::DeleteAnyEmpty() { Decoration *deco = root; while (deco) { if ((lengthDocument == 0) || deco->Empty()) { Delete(deco->indicator); deco = root; } else { deco = deco->next; } } } int DecorationList::AllOnFor(int position) { int mask = 0; for (Decoration *deco=root; deco; deco = deco->next) { if (deco->rs.ValueAt(position)) { mask |= 1 << deco->indicator; } } return mask; } int DecorationList::ValueAt(int indicator, int position) { Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.ValueAt(position); } return 0; } int DecorationList::Start(int indicator, int position) { Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.StartRun(position); } return 0; } int DecorationList::End(int indicator, int position) { Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.EndRun(position); } return 0; } <|endoftext|>
<commit_before> // This work derives from Vittorio Romeo's code used for cppcon 2015 licensed under the Academic Free License. // His code is available here: https://github.com/SuperV1234/cppcon2015 #ifndef EC_MANAGER_HPP #define EC_MANAGER_HPP #define EC_INIT_ENTITIES_SIZE 256 #define EC_GROW_SIZE_AMOUNT 256 #include <cstddef> #include <tuple> #include <utility> #include "Meta/Combine.hpp" #include "Bitset.hpp" namespace EC { template <typename ComponentsList, typename TagsList> struct Manager { public: using Combined = EC::Meta::Combine<ComponentsList, TagsList>; using BitsetType = EC::Bitset<ComponentsList, TagsList>; private: template <typename... Types> struct Storage { using type = std::tuple<std::vector<Types>... >; }; using ComponentsStorage = typename EC::Meta::Morph<ComponentsList, Storage<> >::type; // Entity: isAlive, dataIndex, ComponentsTags Info using EntitiesTupleType = std::tuple<bool, std::size_t, BitsetType>; using EntitiesType = std::vector<EntitiesTupleType>; EntitiesType entities; ComponentsStorage componentsStorage; std::size_t currentCapacity = 0; std::size_t currentSize = 0; public: Manager() { resize(EC_INIT_ENTITIES_SIZE); } private: void resize(std::size_t newCapacity) { if(currentCapacity >= newCapacity) { return; } EC::Meta::forEach<ComponentsList>([this, newCapacity] (auto t) { std::get<std::vector<decltype(t)> >(this->componentsStorage).resize(newCapacity); }); entities.resize(newCapacity); for(std::size_t i = currentCapacity; i < newCapacity; ++i) { entities[i] = std::make_tuple(false, i, BitsetType{}); } currentCapacity = newCapacity; } public: std::size_t addEntity() { if(currentSize == currentCapacity) { resize(currentCapacity + EC_GROW_SIZE_AMOUNT); } std::get<bool>(entities[currentSize]) = true; return currentSize++; } void deleteEntity(std::size_t index) { std::get<bool>(entities.at(index)) = false; } bool hasEntity(std::size_t index) const { return index < currentSize; } bool isAlive(std::size_t index) const { return hasEntity(index) && std::get<bool>(entities.at(index)); } const EntitiesTupleType& getEntityInfo(std::size_t index) const { return entities.at(index); } template <typename Component> Component& getEntityData(std::size_t index) { return std::get<std::vector<Component> >(componentsStorage).at(std::get<std::size_t>(entities.at(index))); } template <typename Component> bool hasComponent(std::size_t index) const { return std::get<BitsetType>(entities.at(index)).template getComponentBit<Component>(); } template <typename Tag> bool hasTag(std::size_t index) const { return std::get<BitsetType>(entities.at(index)).template getTagBit<Tag>(); } void cleanup() { if(currentSize == 0) { return; } std::size_t rhs = currentSize - 1; std::size_t lhs = 0; while(lhs < rhs) { while(!std::get<bool>(entities[rhs])) { if(rhs == 0) { currentSize = 0; return; } --rhs; } if(lhs >= rhs) { break; } else if(!std::get<bool>(entities[lhs])) { // lhs is marked for deletion // swap lhs entity with rhs entity std::swap(entities[lhs], entities.at(rhs)); // clear deleted bitset std::get<BitsetType>(entities[rhs]).reset(); // inc/dec pointers ++lhs; --rhs; } else { ++lhs; } } currentSize = rhs + 1; } template <typename Component, typename... Args> void addComponent(std::size_t entityID, Args&&... args) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } Component component(std::forward<Args>(args)...); std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = true; std::get<std::vector<Component> >(componentsStorage)[std::get<std::size_t>(entities[entityID])] = std::move(component); } template <typename Component> void removeComponent(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = false; } template <typename Tag> void addTag(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = true; } template <typename Tag> void removeTag(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = false; } private: template <typename... Types> struct ForMatchingSignatureHelper { template <typename CType, typename Function> static void call(std::size_t entityID, CType& ctype, Function&& function) { function( entityID, ctype.template getEntityData<Types>(entityID)... ); } }; public: template <typename Signature, typename Function> void forMatchingSignature(Function&& function) { using SignatureComponents = typename EC::Meta::Matching<Signature, ComponentsList>::type; using Helper = EC::Meta::Morph<SignatureComponents, ForMatchingSignatureHelper<> >; BitsetType signatureBitset = BitsetType::template generateBitset<Signature>(); for(std::size_t i = 0; i < currentSize; ++i) { if(!std::get<bool>(entities[i])) { continue; } if((signatureBitset & std::get<BitsetType>(entities[i])) == signatureBitset) { Helper::call(i, *this, std::forward<Function>(function)); } } } }; } #endif /*! \class EC::Manager \brief Manages an EntityComponent system. EC::Manager must be created with a list of all used Components and all used tags. Note that all components must have a default constructor. Example: \code{.cpp} EC::Manager<TypeList<C0, C1, C2>, TypeList<T0, T1>> manager; \endcode */ /*! \fn EC::Manager::Manager() \brief Initializes the manager with a default capacity. The default capacity is set with macro EC_INIT_ENTITIES_SIZE, and will grow by amounts of EC_GROW_SIZE_AMOUNT when needed. */ /*! \fn std::size_t EC::Manager::addEntity() \brief Adds an entity to the system, returning the ID of the entity. WARNING: The ID of an entity may change after calls to cleanup(). Usage of entity IDs should be safe during initialization. Otherwise, only use the ID given during usage of forMatchingSignature(). */ /*! \fn void EC::Manager::deleteEntity(std::size_t index) \brief Marks an entity for deletion. A deleted Entity is not actually deleted until cleanup() is called. While an Entity is "deleted" but still in the system, calls to forMatchingSignature() will ignore the Entity. */ /*! \fn bool EC::Manager::hasEntity(std::size_t index) const \brief Checks if the Entity with the given ID is in the system. Note that deleted Entities that haven't yet been cleaned up (via cleanup()) are considered still in the system. */ /*! \fn bool EC::Manager::isAlive(std::size_t index) const \brief Checks if the Entity is not marked as deleted. Note that invalid Entities (Entities where calls to hasEntity() returns false) will return false. */ /*! \fn const EntitiesTupleType& EC::Manager::getEntityInfo(std::size_t index) const \brief Returns a const reference to an Entity's info. An Entity's info is a std::tuple with a bool, std::size_t, and a bitset. \n The bool determines if the Entity is alive. \n The std::size_t is the ID to this Entity's data in the system. \n The bitset shows what Components and Tags belong to the Entity. */ /*! \fn Component& EC::Manager::getEntityData(std::size_t index) \brief Returns a reference to a component belonging to the given Entity. This function will return a reference to a Component regardless of whether or not the Entity actually owns the reference. If the Entity doesn't own the Component, changes to the Component will not affect any Entity. It is recommended to use hasComponent() to determine if the Entity actually owns that Component. */ /*! \fn bool EC::Manager::hasComponent(std::size_t index) const \brief Checks whether or not the given Entity has the given Component. Example: \code{.cpp} manager.hasComponent<C0>(entityID); \endcode */ /*! \fn bool EC::Manager::hasTag(std::size_t index) const \brief Checks whether or not the given Entity has the given Tag. Example: \code{.cpp} manager.hasTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::cleanup() \brief Does garbage collection on Entities. Does housekeeping on the vector containing Entities that will result in entity IDs changing if some Entities were marked for deletion. <b>This function should be called periodically to correctly handle deletion of entities.</b> */ /*! \fn void EC::Manager::addComponent(std::size_t entityID, Args&&... args) \brief Adds a component to the given Entity. Additional parameters given to this function will construct the Component with those parameters. Example: \code{.cpp} struct C0 { // constructor is compatible as a default constructor C0(int a = 0, char b = 'b') : a(a), b(b) {} int a; char b; } manager.addComponent<C0>(entityID, 10, 'd'); \endcode */ /*! \fn void EC::Manager::removeComponent(std::size_t entityID) \brief Removes the given Component from the given Entity. If the Entity does not have the Component given, nothing will change. Example: \code{.cpp} manager.removeComponent<C0>(entityID); \endcode */ /*! \fn void EC::Manager::addTag(std::size_t entityID) \brief Adds the given Tag to the given Entity. Example: \code{.cpp} manager.addTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::removeTag(std::size_t entityID) \brief Removes the given Tag from the given Entity. If the Entity does not have the Tag given, nothing will change. Example: \code{.cpp} manager.removeTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::forMatchingSignature(Function&& function) \brief Calls the given function on all Entities matching the given Signature. The function object given to this function must accept std::size_t as its first parameter and Component references for the rest of the parameters. Tags specified in the Signature are only used as filters and will not be given as a parameter to the function. Example: \code{.cpp} manager.forMatchingSignature<TypeList<C0, C1, T0>>([] (std::size_t ID, C0& component0, C1& component1) { // Lambda function contents here. }); \endcode Note, the ID given to the function is not permanent. An entity's ID may change when cleanup() is called. */ <commit_msg>Added note about manager's addComponent<commit_after> // This work derives from Vittorio Romeo's code used for cppcon 2015 licensed under the Academic Free License. // His code is available here: https://github.com/SuperV1234/cppcon2015 #ifndef EC_MANAGER_HPP #define EC_MANAGER_HPP #define EC_INIT_ENTITIES_SIZE 256 #define EC_GROW_SIZE_AMOUNT 256 #include <cstddef> #include <tuple> #include <utility> #include "Meta/Combine.hpp" #include "Bitset.hpp" namespace EC { template <typename ComponentsList, typename TagsList> struct Manager { public: using Combined = EC::Meta::Combine<ComponentsList, TagsList>; using BitsetType = EC::Bitset<ComponentsList, TagsList>; private: template <typename... Types> struct Storage { using type = std::tuple<std::vector<Types>... >; }; using ComponentsStorage = typename EC::Meta::Morph<ComponentsList, Storage<> >::type; // Entity: isAlive, dataIndex, ComponentsTags Info using EntitiesTupleType = std::tuple<bool, std::size_t, BitsetType>; using EntitiesType = std::vector<EntitiesTupleType>; EntitiesType entities; ComponentsStorage componentsStorage; std::size_t currentCapacity = 0; std::size_t currentSize = 0; public: Manager() { resize(EC_INIT_ENTITIES_SIZE); } private: void resize(std::size_t newCapacity) { if(currentCapacity >= newCapacity) { return; } EC::Meta::forEach<ComponentsList>([this, newCapacity] (auto t) { std::get<std::vector<decltype(t)> >(this->componentsStorage).resize(newCapacity); }); entities.resize(newCapacity); for(std::size_t i = currentCapacity; i < newCapacity; ++i) { entities[i] = std::make_tuple(false, i, BitsetType{}); } currentCapacity = newCapacity; } public: std::size_t addEntity() { if(currentSize == currentCapacity) { resize(currentCapacity + EC_GROW_SIZE_AMOUNT); } std::get<bool>(entities[currentSize]) = true; return currentSize++; } void deleteEntity(std::size_t index) { std::get<bool>(entities.at(index)) = false; } bool hasEntity(std::size_t index) const { return index < currentSize; } bool isAlive(std::size_t index) const { return hasEntity(index) && std::get<bool>(entities.at(index)); } const EntitiesTupleType& getEntityInfo(std::size_t index) const { return entities.at(index); } template <typename Component> Component& getEntityData(std::size_t index) { return std::get<std::vector<Component> >(componentsStorage).at(std::get<std::size_t>(entities.at(index))); } template <typename Component> bool hasComponent(std::size_t index) const { return std::get<BitsetType>(entities.at(index)).template getComponentBit<Component>(); } template <typename Tag> bool hasTag(std::size_t index) const { return std::get<BitsetType>(entities.at(index)).template getTagBit<Tag>(); } void cleanup() { if(currentSize == 0) { return; } std::size_t rhs = currentSize - 1; std::size_t lhs = 0; while(lhs < rhs) { while(!std::get<bool>(entities[rhs])) { if(rhs == 0) { currentSize = 0; return; } --rhs; } if(lhs >= rhs) { break; } else if(!std::get<bool>(entities[lhs])) { // lhs is marked for deletion // swap lhs entity with rhs entity std::swap(entities[lhs], entities.at(rhs)); // clear deleted bitset std::get<BitsetType>(entities[rhs]).reset(); // inc/dec pointers ++lhs; --rhs; } else { ++lhs; } } currentSize = rhs + 1; } template <typename Component, typename... Args> void addComponent(std::size_t entityID, Args&&... args) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } Component component(std::forward<Args>(args)...); std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = true; std::get<std::vector<Component> >(componentsStorage)[std::get<std::size_t>(entities[entityID])] = std::move(component); } template <typename Component> void removeComponent(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = false; } template <typename Tag> void addTag(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = true; } template <typename Tag> void removeTag(std::size_t entityID) { if(!hasEntity(entityID) || !isAlive(entityID)) { return; } std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = false; } private: template <typename... Types> struct ForMatchingSignatureHelper { template <typename CType, typename Function> static void call(std::size_t entityID, CType& ctype, Function&& function) { function( entityID, ctype.template getEntityData<Types>(entityID)... ); } }; public: template <typename Signature, typename Function> void forMatchingSignature(Function&& function) { using SignatureComponents = typename EC::Meta::Matching<Signature, ComponentsList>::type; using Helper = EC::Meta::Morph<SignatureComponents, ForMatchingSignatureHelper<> >; BitsetType signatureBitset = BitsetType::template generateBitset<Signature>(); for(std::size_t i = 0; i < currentSize; ++i) { if(!std::get<bool>(entities[i])) { continue; } if((signatureBitset & std::get<BitsetType>(entities[i])) == signatureBitset) { Helper::call(i, *this, std::forward<Function>(function)); } } } }; } #endif /*! \class EC::Manager \brief Manages an EntityComponent system. EC::Manager must be created with a list of all used Components and all used tags. Note that all components must have a default constructor. Example: \code{.cpp} EC::Manager<TypeList<C0, C1, C2>, TypeList<T0, T1>> manager; \endcode */ /*! \fn EC::Manager::Manager() \brief Initializes the manager with a default capacity. The default capacity is set with macro EC_INIT_ENTITIES_SIZE, and will grow by amounts of EC_GROW_SIZE_AMOUNT when needed. */ /*! \fn std::size_t EC::Manager::addEntity() \brief Adds an entity to the system, returning the ID of the entity. WARNING: The ID of an entity may change after calls to cleanup(). Usage of entity IDs should be safe during initialization. Otherwise, only use the ID given during usage of forMatchingSignature(). */ /*! \fn void EC::Manager::deleteEntity(std::size_t index) \brief Marks an entity for deletion. A deleted Entity is not actually deleted until cleanup() is called. While an Entity is "deleted" but still in the system, calls to forMatchingSignature() will ignore the Entity. */ /*! \fn bool EC::Manager::hasEntity(std::size_t index) const \brief Checks if the Entity with the given ID is in the system. Note that deleted Entities that haven't yet been cleaned up (via cleanup()) are considered still in the system. */ /*! \fn bool EC::Manager::isAlive(std::size_t index) const \brief Checks if the Entity is not marked as deleted. Note that invalid Entities (Entities where calls to hasEntity() returns false) will return false. */ /*! \fn const EntitiesTupleType& EC::Manager::getEntityInfo(std::size_t index) const \brief Returns a const reference to an Entity's info. An Entity's info is a std::tuple with a bool, std::size_t, and a bitset. \n The bool determines if the Entity is alive. \n The std::size_t is the ID to this Entity's data in the system. \n The bitset shows what Components and Tags belong to the Entity. */ /*! \fn Component& EC::Manager::getEntityData(std::size_t index) \brief Returns a reference to a component belonging to the given Entity. This function will return a reference to a Component regardless of whether or not the Entity actually owns the reference. If the Entity doesn't own the Component, changes to the Component will not affect any Entity. It is recommended to use hasComponent() to determine if the Entity actually owns that Component. */ /*! \fn bool EC::Manager::hasComponent(std::size_t index) const \brief Checks whether or not the given Entity has the given Component. Example: \code{.cpp} manager.hasComponent<C0>(entityID); \endcode */ /*! \fn bool EC::Manager::hasTag(std::size_t index) const \brief Checks whether or not the given Entity has the given Tag. Example: \code{.cpp} manager.hasTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::cleanup() \brief Does garbage collection on Entities. Does housekeeping on the vector containing Entities that will result in entity IDs changing if some Entities were marked for deletion. <b>This function should be called periodically to correctly handle deletion of entities.</b> */ /*! \fn void EC::Manager::addComponent(std::size_t entityID, Args&&... args) \brief Adds a component to the given Entity. Additional parameters given to this function will construct the Component with those parameters. Note that if the Entity already has the same component, then it will be overwritten by the newly created Component with the given arguments. Example: \code{.cpp} struct C0 { // constructor is compatible as a default constructor C0(int a = 0, char b = 'b') : a(a), b(b) {} int a; char b; } manager.addComponent<C0>(entityID, 10, 'd'); \endcode */ /*! \fn void EC::Manager::removeComponent(std::size_t entityID) \brief Removes the given Component from the given Entity. If the Entity does not have the Component given, nothing will change. Example: \code{.cpp} manager.removeComponent<C0>(entityID); \endcode */ /*! \fn void EC::Manager::addTag(std::size_t entityID) \brief Adds the given Tag to the given Entity. Example: \code{.cpp} manager.addTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::removeTag(std::size_t entityID) \brief Removes the given Tag from the given Entity. If the Entity does not have the Tag given, nothing will change. Example: \code{.cpp} manager.removeTag<T0>(entityID); \endcode */ /*! \fn void EC::Manager::forMatchingSignature(Function&& function) \brief Calls the given function on all Entities matching the given Signature. The function object given to this function must accept std::size_t as its first parameter and Component references for the rest of the parameters. Tags specified in the Signature are only used as filters and will not be given as a parameter to the function. Example: \code{.cpp} manager.forMatchingSignature<TypeList<C0, C1, T0>>([] (std::size_t ID, C0& component0, C1& component1) { // Lambda function contents here. }); \endcode Note, the ID given to the function is not permanent. An entity's ID may change when cleanup() is called. */ <|endoftext|>
<commit_before>/* * InspIRCd -- Internet Relay Chat Daemon * * Copyright (C) 2015-2017 Attila Molnar <attilamolnar@hush.com> * * This file is part of InspIRCd. InspIRCd is free software: you can * redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, version 2. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* $ModAuthor: Attila Molnar */ /* $ModAuthorMail: attilamolnar@hush.com */ /* $ModDesc: Implements IRCv3 STS (Strict Transport Security) policy advertisement */ /* $ModDepends: core 2.0 */ #include "inspircd.h" #include "m_cap.h" class STSCap { std::string cap; public: void HandleEvent(Event& ev) { if (ev.id != "cap_request") return; // Empty cap name means configuration is invalid if (cap.empty()) return; CapEvent* data = static_cast<CapEvent*>(&ev); if (data->type == CapEvent::CAPEVENT_LS) data->wanted.push_back(cap); } void SetPolicy(const std::string& newpolicystr) { cap = "draft/sts=" + newpolicystr; } }; class STSPolicy { unsigned long duration; unsigned int port; bool preload; public: STSPolicy(unsigned long Duration = 0, unsigned int Port = 0, bool Preload = false) : duration(Duration) , port(Port) , preload(Preload) { } bool operator==(const STSPolicy& other) const { return ((duration == other.duration) && (port == other.port) && (preload == other.preload)); } std::string GetString() const { std::string newpolicystr = "duration="; newpolicystr.append(ConvToStr(duration)).append(",port=").append(ConvToStr(port)); if (preload) newpolicystr.append(",preload"); return newpolicystr; } }; class ModuleIRCv3STS : public Module { STSCap cap; STSPolicy policy; public: void init() { OnRehash(NULL); Implementation eventlist[] = { I_OnRehash, I_OnEvent }; ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist) / sizeof(Implementation)); } void OnRehash(User* user) { ConfigTag* tag = ServerInstance->Config->ConfValue("sts"); unsigned int port = tag->getInt("port", 6697); if ((port <= 0) || (port > 65535)) { ServerInstance->Logs->Log("m_ircv3_sts", DEFAULT, "STS: Invalid port specified (%u), not applying policy", port); return; } std::string durationstr; if (!tag->readString("duration", durationstr)) { ServerInstance->Logs->Log("m_ircv3_sts", DEFAULT, "STS: Duration not configured, not applying policy"); return; } unsigned long duration = ServerInstance->Duration(durationstr); bool preload = tag->getBool("preload"); STSPolicy newpolicy(duration, port, preload); if (newpolicy == policy) return; policy = newpolicy; const std::string newpolicystr = policy.GetString(); ServerInstance->Logs->Log("m_ircv3_sts", DEFAULT, "STS: policy changed to \"%s\"", newpolicystr.c_str()); cap.SetPolicy(newpolicystr); } void OnEvent(Event& ev) { cap.HandleEvent(ev); } Version GetVersion() { return Version("Implements IRCv3 STS (Strict Transport Security) policy advertisement"); } }; MODULE_INIT(ModuleIRCv3STS) <commit_msg>Delete m_ircv3_sts.cpp<commit_after><|endoftext|>
<commit_before>// String.cpp // This file is part of the EScript programming language. // See copyright notice in EScript.h // ------------------------------------------------------ #include "String.h" #include "../EScript.h" #include "../Utils/StringUtils.h" #include <sstream> using namespace EScript; //--- using std::string; std::stack<String *> String::stringPool; //! static, internal StringData String::objToStringData(Object * obj){ String * strObj=dynamic_cast<String*>(obj); return strObj==NULL ? StringData(obj->toString()) : strObj->sData; } //--- Type* String::typeObject=NULL; //! initMembers void String::init(EScript::Namespace & globals) { // // String ---|> [Object] typeObject=new Type(Object::getTypeObject()); typeObject->setFlag(Type::FLAG_CALL_BY_VALUE,true); declareConstant(&globals,getClassName(),typeObject); //! [ESMF] String new String((String)Obj) ESF_DECLARE(typeObject,"_constructor",0,1,String::create(parameter[0].toString(""))) //- Operators //! [ESMF] String String+(String)Obj ESMF_DECLARE(typeObject,String,"+",1,1,String::create( self->getString() + parameter[0]->toString())) //! [ESMF] String String*(Number)Obj ES_MFUNCTION_DECLARE(typeObject,String,"*",1,1,{ string s; string s2( self->getString() ); for (int i=parameter[0].toInt();i>0;--i) s+=s2; return String::create(s); }) //! [ESMF] self String+=(String)Obj ESMF_DECLARE(typeObject,String,"+=",1,1,(self->appendString(parameter[0].toString()),caller)) //! [ESMF] self String*=(Number)Obj ES_MFUNCTION_DECLARE(typeObject,String,"*=",1,1,{ string s; string s2( self->getString() ); for (int i=parameter[0]->toInt();i>0;--i) s+=s2; self->setString(s); return caller; }) //! [ESMF] bool String>(String)Obj ESMF_DECLARE(typeObject,String,">",1,1,Bool::create( self->getString() > parameter[0].toString())) //! [ESMF] bool String>=(String)Obj ESMF_DECLARE(typeObject,String,">=",1,1,Bool::create( self->getString() >= parameter[0].toString())) //! [ESMF] bool String<(String)Obj ESMF_DECLARE(typeObject,String,"<",1,1,Bool::create( self->getString() < parameter[0].toString())) //! [ESMF] bool String<=(String)Obj ESMF_DECLARE(typeObject,String,"<=",1,1,Bool::create( self->getString() <= parameter[0].toString())) // --- //! [ESMF] Bool String.empty() ESMF_DECLARE(typeObject,String,"empty",0,0,Bool::create( self->getString().empty())) //! [ESMF] Number String.length() ESMF_DECLARE(typeObject,String,"length",0,0,Number::create( self->getString().length())) //! [ESMF] String String.ltrim() ESMF_DECLARE(typeObject,String,"lTrim",0,0,String::create( StringUtils::lTrim(self->getString()))) //! [ESMF] String String.trim() ESMF_DECLARE(typeObject,String,"trim",0,0,String::create( StringUtils::trim(self->getString()))) //! [ESMF] String String.rTrim() ESMF_DECLARE(typeObject,String,"rTrim",0,0,String::create( StringUtils::rTrim(self->getString()))) //! [ESMF] String String.substr( (Number)begin [,(Number)length] ) ES_MFUNCTION_DECLARE(typeObject,String,"substr",1,2, { int start=parameter[0].toInt(); int length=self->getString().length(); if (start>=length) return String::create(""); if (start<0) start=length+start; if (start<0) start=0; int count=length-start; if (parameter.count()>1) { int i=parameter[1].toInt(); if (i<count) { if (i<0) { count+=i; } else { count=i; } } } return String::create(self->getString().substr(start,count)); }) //! [ESMF] String String[(Number)position ] ES_MFUNCTION_DECLARE(typeObject,String,"_get",1,1, { assertParamCount(runtime,parameter.count(),1,1); int pos=parameter[0]->toInt(); if (static_cast<unsigned int>(pos)>=self->getString().length()) return NULL; return String::create(self->getString().substr(pos,1)); }) //! [ESMF] Number|false String.find( (String)search [,(Number)startIndex] ) ES_MFUNCTION_DECLARE(typeObject,String,"find",1,2, { const string & s(self->getString()); string search=parameter[0].toString(); size_t start=0; if (parameter.count()>1) { start=static_cast<size_t>(parameter[1].toInt()); if (start>=s.length()) return Bool::create(false); } size_t pos=s.find(search,start); if (pos==string::npos ) { return Bool::create(false); } else return Number::create(pos); }) //! [ESMF] Number|false String.rFind( (String)search [,(Number)startIndex] ) ES_MFUNCTION_DECLARE(typeObject,String,"rFind",1,2, { const string & s(self->getString()); string search=parameter[0].toString(); size_t start=s.length(); if (parameter.count()>1) { start=static_cast<size_t>(parameter[1].toInt()); if (start>=s.length()) start=s.length(); //std::cout << " #"<<start<< " "; } size_t pos=s.rfind(search,start); if (pos==string::npos ) { return Bool::create(false); } else return Number::create(pos); }) //! [ESMF] Bool String.contains (String)search [,(Number)startIndex] ) ES_MFUNCTION_DECLARE(typeObject,String,"contains",1,2, { const string & s(self->getString()); string search=parameter[0]->toString(); size_t start=s.length(); if (parameter.count()>1) { start=static_cast<size_t>(parameter[1].toInt()); if (start>=s.length()) start=s.length(); } return Bool::create(s.rfind(search,start)!=string::npos); }) //! [ESMF] String String.replace((String)search,(String)replace) ESMF_DECLARE(typeObject,String,"replace",2,2, String::create(StringUtils::replaceAll(self->getString(),parameter[0]->toString(),parameter[1]->toString(),1))) typedef std::pair<std::string,std::string> keyValuePair_t; //! [ESMF] String.replaceAll( (Map | ((String)search,(String)replace)) [,(Number)max]) ES_MFUNCTION_DECLARE(typeObject,String,"replaceAll",1,3,{ const string & subject(self->getString()); //Map * m if ( Map * m=parameter[0].toType<Map>()) { assertParamCount(runtime,parameter.count(),1,2); std::vector<keyValuePair_t> rules; ERef<Iterator> iRef=m->getIterator(); while (!iRef->end()) { ObjRef key=iRef->key(); ObjRef value=iRef->value(); rules.push_back(std::make_pair(key.toString(),value.toString())); iRef->next(); } return String::create(StringUtils::replaceMultiple(subject,rules,parameter[1].toInt(-1))); } const std::string search(parameter[0]->toString()); const std::string replace(parameter[1]->toString()); return String::create(StringUtils::replaceAll(subject,search,replace,parameter[2].toInt(-1))); }) //! [ESMF] Array String.split((String)search[,(Number)max]) ES_MFUNCTION_DECLARE(typeObject,String,"split",1,2, { std::vector<std::string> result; StringUtils::split( self->getString(), parameter[0].toString(), result, parameter[1].toInt(-1) ); Array * a=Array::create(); for(std::vector<std::string>::const_iterator it=result.begin();it!=result.end();++it) a->pushBack( String::create(*it) ); return a; }) //! [ESMF] String String.fillUp(length[, string fill=" ") ES_MFUNCTION_DECLARE(typeObject,String,"fillUp",1,2,{ const string & s(self->getString()); std::ostringstream sprinter; sprinter<<s; string fill=parameter[1].toString(" "); int count=(parameter[0].toInt()-s.length())/(fill.length()>0?fill.length():0); for(int i=0;i<count;++i) sprinter<<fill; return String::create(sprinter.str()); }) //! [ESMF] Bool String.beginsWith( (String)search ) ES_MFUNCTION_DECLARE(typeObject,String,"beginsWith",1,1, { const string & s(self->getString()); string search=parameter[0]->toString(); if(s.length()<search.length()) return Bool::create(false); return Bool::create(s.substr(0,search.length())==search); }) //! [ESMF] Bool String.endsWith( (String)search ) ES_MFUNCTION_DECLARE(typeObject,String,"endsWith",1,1, { const string & s(self->getString()); string search=parameter[0]->toString(); if(s.length()<search.length()) return Bool::create(false); return Bool::create(s.substr(s.length()-search.length(),search.length())==search); }) } //--- String * String::create(const StringData & sData){ #ifdef ES_DEBUG_MEMORY return new String(s); #endif if(stringPool.empty()){ return new String (sData); }else{ String * o=stringPool.top(); stringPool.pop(); o->setString(sData); return o; } } String * String::create(const StringData & sData,Type * type){ #ifdef ES_DEBUG_MEMORY return new String(sData,type); #endif if(type==typeObject){ return create(sData); }else{ return new String(sData,type); } } void String::release(String * o){ #ifdef ES_DEBUG_MEMORY delete o; return; #endif if(o->getType()!=typeObject){ delete o; std::cout << "Found diff StringType\n"; }else{ stringPool.push(o); } } //--- //! (ctor) String::String(const StringData & _sData,Type * type): Object(type?type:typeObject),sData(_sData) { //ctor } //! (dtor) String::~String() { //dtor } //! ---|> [Object] Object * String::clone() const { return String::create(sData,getType()); } //! ---|> [Object] std::string String::toString()const { return sData.str(); } //! ---|> [Object] std::string String::toDbgString()const{ return std::string("\"")+sData.str()+"\""; } //! ---|> [Object] double String::toDouble()const { int to=0; return StringUtils::getNumber(sData.str().c_str(),to, true); } //! ---|> [Object] int String::toInt()const { int to=0; return static_cast<int>(StringUtils::getNumber(sData.str().c_str(),to, true)); } //! ---|> [Object] bool String::toBool()const { return true;//s.length()>0; } //! ---|> [Object] bool String::rt_isEqual(Runtime &, const ObjPtr o){ return o.isNull()?false:sData==objToStringData(o.get()); } <commit_msg>Strings: Methods sorted alphabetically.<commit_after>// String.cpp // This file is part of the EScript programming language. // See copyright notice in EScript.h // ------------------------------------------------------ #include "String.h" #include "../EScript.h" #include "../Utils/StringUtils.h" #include <sstream> using namespace EScript; //--- using std::string; std::stack<String *> String::stringPool; //! static, internal StringData String::objToStringData(Object * obj){ String * strObj=dynamic_cast<String*>(obj); return strObj==NULL ? StringData(obj->toString()) : strObj->sData; } //--- Type* String::typeObject=NULL; //! initMembers void String::init(EScript::Namespace & globals) { // // String ---|> [Object] typeObject=new Type(Object::getTypeObject()); typeObject->setFlag(Type::FLAG_CALL_BY_VALUE,true); declareConstant(&globals,getClassName(),typeObject); //! [ESMF] String new String((String)Obj) ESF_DECLARE(typeObject,"_constructor",0,1,String::create(parameter[0].toString(""))) //! [ESMF] String String[(Number)position ] ES_MFUNCTION_DECLARE(typeObject,String,"_get",1,1, { assertParamCount(runtime,parameter.count(),1,1); int pos=parameter[0]->toInt(); if (static_cast<unsigned int>(pos)>=self->getString().length()) return NULL; return String::create(self->getString().substr(pos,1)); }) // --- //! [ESMF] Bool String.beginsWith( (String)search ) ES_MFUNCTION_DECLARE(typeObject,String,"beginsWith",1,1, { const string & s(self->getString()); string search=parameter[0]->toString(); if(s.length()<search.length()) return Bool::create(false); return Bool::create(s.substr(0,search.length())==search); }) //! [ESMF] Bool String.contains (String)search [,(Number)startIndex] ) ES_MFUNCTION_DECLARE(typeObject,String,"contains",1,2, { const string & s(self->getString()); string search=parameter[0]->toString(); size_t start=s.length(); if (parameter.count()>1) { start=static_cast<size_t>(parameter[1].toInt()); if (start>=s.length()) start=s.length(); } return Bool::create(s.rfind(search,start)!=string::npos); }) //! [ESMF] Bool String.empty() ESMF_DECLARE(typeObject,String,"empty",0,0,Bool::create( self->getString().empty())) //! [ESMF] Bool String.endsWith( (String)search ) ES_MFUNCTION_DECLARE(typeObject,String,"endsWith",1,1, { const string & s(self->getString()); string search=parameter[0]->toString(); if(s.length()<search.length()) return Bool::create(false); return Bool::create(s.substr(s.length()-search.length(),search.length())==search); }) //! [ESMF] String String.fillUp(length[, string fill=" ") ES_MFUNCTION_DECLARE(typeObject,String,"fillUp",1,2,{ const string & s(self->getString()); std::ostringstream sprinter; sprinter<<s; string fill=parameter[1].toString(" "); int count=(parameter[0].toInt()-s.length())/(fill.length()>0?fill.length():0); for(int i=0;i<count;++i) sprinter<<fill; return String::create(sprinter.str()); }) //! [ESMF] Number|false String.find( (String)search [,(Number)startIndex] ) ES_MFUNCTION_DECLARE(typeObject,String,"find",1,2, { const string & s(self->getString()); string search=parameter[0].toString(); size_t start=0; if (parameter.count()>1) { start=static_cast<size_t>(parameter[1].toInt()); if (start>=s.length()) return Bool::create(false); } size_t pos=s.find(search,start); if (pos==string::npos ) { return Bool::create(false); } else return Number::create(pos); }) //! [ESMF] Number String.length() ESMF_DECLARE(typeObject,String,"length",0,0,Number::create( self->getString().length())) //! [ESMF] String String.ltrim() ESMF_DECLARE(typeObject,String,"lTrim",0,0,String::create( StringUtils::lTrim(self->getString()))) //! [ESMF] String String.rTrim() ESMF_DECLARE(typeObject,String,"rTrim",0,0,String::create( StringUtils::rTrim(self->getString()))) //! [ESMF] String String.substr( (Number)begin [,(Number)length] ) ES_MFUNCTION_DECLARE(typeObject,String,"substr",1,2, { int start=parameter[0].toInt(); int length=self->getString().length(); if (start>=length) return String::create(""); if (start<0) start=length+start; if (start<0) start=0; int count=length-start; if (parameter.count()>1) { int i=parameter[1].toInt(); if (i<count) { if (i<0) { count+=i; } else { count=i; } } } return String::create(self->getString().substr(start,count)); }) //! [ESMF] String String.trim() ESMF_DECLARE(typeObject,String,"trim",0,0,String::create( StringUtils::trim(self->getString()))) //! [ESMF] String String.replace((String)search,(String)replace) ESMF_DECLARE(typeObject,String,"replace",2,2, String::create(StringUtils::replaceAll(self->getString(),parameter[0]->toString(),parameter[1]->toString(),1))) typedef std::pair<std::string,std::string> keyValuePair_t; //! [ESMF] String.replaceAll( (Map | ((String)search,(String)replace)) [,(Number)max]) ES_MFUNCTION_DECLARE(typeObject,String,"replaceAll",1,3,{ const string & subject(self->getString()); //Map * m if ( Map * m=parameter[0].toType<Map>()) { assertParamCount(runtime,parameter.count(),1,2); std::vector<keyValuePair_t> rules; ERef<Iterator> iRef=m->getIterator(); while (!iRef->end()) { ObjRef key=iRef->key(); ObjRef value=iRef->value(); rules.push_back(std::make_pair(key.toString(),value.toString())); iRef->next(); } return String::create(StringUtils::replaceMultiple(subject,rules,parameter[1].toInt(-1))); } const std::string search(parameter[0]->toString()); const std::string replace(parameter[1]->toString()); return String::create(StringUtils::replaceAll(subject,search,replace,parameter[2].toInt(-1))); }) //! [ESMF] Number|false String.rFind( (String)search [,(Number)startIndex] ) ES_MFUNCTION_DECLARE(typeObject,String,"rFind",1,2, { const string & s(self->getString()); string search=parameter[0].toString(); size_t start=s.length(); if (parameter.count()>1) { start=static_cast<size_t>(parameter[1].toInt()); if (start>=s.length()) start=s.length(); //std::cout << " #"<<start<< " "; } size_t pos=s.rfind(search,start); if (pos==string::npos ) { return Bool::create(false); } else return Number::create(pos); }) //! [ESMF] Array String.split((String)search[,(Number)max]) ES_MFUNCTION_DECLARE(typeObject,String,"split",1,2, { std::vector<std::string> result; StringUtils::split( self->getString(), parameter[0].toString(), result, parameter[1].toInt(-1) ); Array * a=Array::create(); for(std::vector<std::string>::const_iterator it=result.begin();it!=result.end();++it) a->pushBack( String::create(*it) ); return a; }) //- Operators //! [ESMF] String String+(String)Obj ESMF_DECLARE(typeObject,String,"+",1,1,String::create( self->getString() + parameter[0]->toString())) //! [ESMF] String String*(Number)Obj ES_MFUNCTION_DECLARE(typeObject,String,"*",1,1,{ string s; string s2( self->getString() ); for (int i=parameter[0].toInt();i>0;--i) s+=s2; return String::create(s); }) //! [ESMF] self String+=(String)Obj ESMF_DECLARE(typeObject,String,"+=",1,1,(self->appendString(parameter[0].toString()),caller)) //! [ESMF] self String*=(Number)Obj ES_MFUNCTION_DECLARE(typeObject,String,"*=",1,1,{ string s; string s2( self->getString() ); for (int i=parameter[0]->toInt();i>0;--i) s+=s2; self->setString(s); return caller; }) //! [ESMF] bool String>(String)Obj ESMF_DECLARE(typeObject,String,">",1,1,Bool::create( self->getString() > parameter[0].toString())) //! [ESMF] bool String>=(String)Obj ESMF_DECLARE(typeObject,String,">=",1,1,Bool::create( self->getString() >= parameter[0].toString())) //! [ESMF] bool String<(String)Obj ESMF_DECLARE(typeObject,String,"<",1,1,Bool::create( self->getString() < parameter[0].toString())) //! [ESMF] bool String<=(String)Obj ESMF_DECLARE(typeObject,String,"<=",1,1,Bool::create( self->getString() <= parameter[0].toString())) } //--- String * String::create(const StringData & sData){ #ifdef ES_DEBUG_MEMORY return new String(s); #endif if(stringPool.empty()){ return new String (sData); }else{ String * o=stringPool.top(); stringPool.pop(); o->setString(sData); return o; } } String * String::create(const StringData & sData,Type * type){ #ifdef ES_DEBUG_MEMORY return new String(sData,type); #endif if(type==typeObject){ return create(sData); }else{ return new String(sData,type); } } void String::release(String * o){ #ifdef ES_DEBUG_MEMORY delete o; return; #endif if(o->getType()!=typeObject){ delete o; std::cout << "Found diff StringType\n"; }else{ stringPool.push(o); } } //--- //! (ctor) String::String(const StringData & _sData,Type * type): Object(type?type:typeObject),sData(_sData) { //ctor } //! (dtor) String::~String() { //dtor } //! ---|> [Object] Object * String::clone() const { return String::create(sData,getType()); } //! ---|> [Object] std::string String::toString()const { return sData.str(); } //! ---|> [Object] std::string String::toDbgString()const{ return std::string("\"")+sData.str()+"\""; } //! ---|> [Object] double String::toDouble()const { int to=0; return StringUtils::getNumber(sData.str().c_str(),to, true); } //! ---|> [Object] int String::toInt()const { int to=0; return static_cast<int>(StringUtils::getNumber(sData.str().c_str(),to, true)); } //! ---|> [Object] bool String::toBool()const { return true;//s.length()>0; } //! ---|> [Object] bool String::rt_isEqual(Runtime &, const ObjPtr o){ return o.isNull()?false:sData==objToStringData(o.get()); } <|endoftext|>
<commit_before>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <unistd.h> #include <jni.h> #include <sal/types.h> #include <android/log.h> #include <osl/detail/android-bootstrap.h> #define LOK_USE_UNSTABLE_API #include <LibreOfficeKit/LibreOfficeKit.h> /* LibreOfficeKit */ namespace { jfieldID getHandleField(JNIEnv* pEnv, jobject aObject) { jclass clazz = pEnv->GetObjectClass(aObject); return pEnv->GetFieldID(clazz, "handle", "Ljava/nio/ByteBuffer;"); } template <typename T> T* getHandle(JNIEnv* pEnv, jobject aObject) { jobject aHandle = pEnv->GetObjectField(aObject, getHandleField(pEnv, aObject)); return reinterpret_cast<T*>(pEnv->GetDirectBufferAddress(aHandle)); } const char* copyJavaString(JNIEnv* pEnv, jstring aJavaString) { const char* pClone = NULL; const char* pTemp = pEnv->GetStringUTFChars(aJavaString, NULL); pClone = strdup(pTemp); pEnv->ReleaseStringUTFChars(aJavaString, pTemp); return pClone; } } // anonymous namespace extern "C" SAL_JNI_EXPORT jstring JNICALL Java_org_libreoffice_kit_Office_getError (JNIEnv* pEnv, jobject aObject) { LibreOfficeKit* pLibreOfficeKit = getHandle<LibreOfficeKit>(pEnv, aObject); char* pError = pLibreOfficeKit->pClass->getError(pLibreOfficeKit); return pEnv->NewStringUTF(pError); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Office_destroy (JNIEnv* pEnv, jobject aObject) { LibreOfficeKit* pLibreOfficeKit = getHandle<LibreOfficeKit>(pEnv, aObject); pLibreOfficeKit->pClass->destroy(pLibreOfficeKit); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Office_destroyAndExit(JNIEnv* pEnv, jobject aObject) { LibreOfficeKit* pLibreOfficeKit = getHandle<LibreOfficeKit>(pEnv, aObject); pLibreOfficeKit->pClass->destroy(pLibreOfficeKit); // Stopgap fix: _exit() to force the OS to restart the LO activity. // Better than to hang. _exit(0); } namespace { struct CallbackData { jmethodID aJavaCallbackMethod; jclass aClass; jobject aObject; }; static CallbackData gCallbackData; /** * Handle retrieved callback */ void messageCallback(int nType, const char* pPayload, void* pData) { CallbackData* pCallbackData = (CallbackData*) pData; JavaVM* pJavaVM = lo_get_javavm(); JNIEnv* pEnv; bool bIsAttached = false; int status = pJavaVM->GetEnv((void **) &pEnv, JNI_VERSION_1_6); if(status < 0) { status = pJavaVM->AttachCurrentThread(&pEnv, NULL); if(status < 0) { return; } bIsAttached = true; } jstring sPayload = pEnv->NewStringUTF(pPayload); jvalue aParameter[2]; aParameter[0].i = nType; aParameter[1].l = sPayload; pEnv->CallVoidMethodA(pCallbackData->aObject, pCallbackData->aJavaCallbackMethod, aParameter); pEnv->DeleteLocalRef(sPayload); if (bIsAttached) { pJavaVM->DetachCurrentThread(); } } } // anonymous namespace extern "C" SAL_JNI_EXPORT jobject JNICALL Java_org_libreoffice_kit_Office_documentLoadNative (JNIEnv* pEnv, jobject aObject, jstring documentPath) { const char* aCloneDocumentPath = copyJavaString(pEnv, documentPath); LibreOfficeKit* pLibreOfficeKit = getHandle<LibreOfficeKit>(pEnv, aObject); LibreOfficeKitDocument* pDocument = pLibreOfficeKit->pClass->documentLoad(pLibreOfficeKit, aCloneDocumentPath); if (pDocument == NULL) return NULL; jobject aHandle = pEnv->NewDirectByteBuffer((void*) pDocument, sizeof(LibreOfficeKitDocument)); return aHandle; } /* Document */ /** Implementation of org.libreoffice.kit.Document.bindMessageCallback method */ extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_bindMessageCallback (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); gCallbackData.aObject = (jobject) pEnv->NewGlobalRef(aObject); jclass aClass = pEnv->GetObjectClass(aObject); gCallbackData.aClass = (jclass) pEnv->NewGlobalRef(aClass); gCallbackData.aJavaCallbackMethod = pEnv->GetMethodID(aClass, "messageRetrieved", "(ILjava/lang/String;)V"); pDocument->pClass->registerCallback(pDocument, messageCallback, (void*) &gCallbackData); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_destroy (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->destroy(pDocument); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_setPart (JNIEnv* pEnv, jobject aObject, jint aPart) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->setPart(pDocument, aPart); } extern "C" SAL_JNI_EXPORT jint JNICALL Java_org_libreoffice_kit_Document_getPart (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); return (jint) pDocument->pClass->getPart(pDocument); } extern "C" SAL_JNI_EXPORT jint JNICALL Java_org_libreoffice_kit_Document_getParts (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); return (jint) pDocument->pClass->getParts(pDocument); } extern "C" SAL_JNI_EXPORT jstring JNICALL Java_org_libreoffice_kit_Document_getPartName (JNIEnv* pEnv, jobject aObject, jint nPartIndex) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); char* pPartName = pDocument->pClass->getPartName(pDocument, nPartIndex); return pEnv->NewStringUTF(pPartName); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_setPartMode (JNIEnv* pEnv, jobject aObject, jint nPartMode) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->setPartMode(pDocument, nPartMode); } extern "C" SAL_JNI_EXPORT jint JNICALL Java_org_libreoffice_kit_Document_getDocumentTypeNative (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); return (jint) pDocument->pClass->getDocumentType(pDocument); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_paintTileNative (JNIEnv* pEnv, jobject aObject, jobject aByteBuffer, jint nCanvasWidth, jint nCanvasHeight, jint nTilePosX, jint nTilePosY, jint nTileWidth, jint nTileHeight) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); unsigned char* buffer = (unsigned char*) pEnv->GetDirectBufferAddress(aByteBuffer); pDocument->pClass->paintTile(pDocument, buffer, nCanvasWidth, nCanvasHeight, nTilePosX, nTilePosY, nTileWidth, nTileHeight); } extern "C" SAL_JNI_EXPORT jlong JNICALL Java_org_libreoffice_kit_Document_getDocumentHeight (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); long nWidth; long nHeight; pDocument->pClass->getDocumentSize(pDocument, &nWidth, &nHeight); return nHeight; } extern "C" SAL_JNI_EXPORT jlong JNICALL Java_org_libreoffice_kit_Document_getDocumentWidth (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); long nWidth; long nHeight; pDocument->pClass->getDocumentSize(pDocument, &nWidth, &nHeight); return nWidth; } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_initializeForRendering (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->initializeForRendering(pDocument); } extern "C" SAL_JNI_EXPORT jint JNICALL Java_org_libreoffice_kit_Office_saveAs (JNIEnv* pEnv, jobject aObject, jstring sUrl, jstring sFormat, jstring sOptions) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); const char* pUrl = pEnv->GetStringUTFChars(sUrl, NULL); const char* pFormat = pEnv->GetStringUTFChars(sFormat, NULL); const char* pOptions = pEnv->GetStringUTFChars(sOptions, NULL); int result = pDocument->pClass->saveAs(pDocument, pUrl, pFormat, pOptions); pEnv->ReleaseStringUTFChars(sUrl, pUrl); pEnv->ReleaseStringUTFChars(sFormat, pFormat); pEnv->ReleaseStringUTFChars(sOptions, pOptions); return result; } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_postKeyEvent (JNIEnv* pEnv, jobject aObject, jint nType, jint nCharCode, jint nKeyCode) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->postKeyEvent(pDocument, nType, nCharCode, nKeyCode); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_postMouseEvent (JNIEnv* pEnv, jobject aObject, jint type, jint x, jint y, jint count) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->postMouseEvent(pDocument, type, x, y, count); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_postUnoCommand (JNIEnv* pEnv, jobject aObject, jstring command) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); const char* pCommand = pEnv->GetStringUTFChars(command, NULL); pDocument->pClass->postUnoCommand(pDocument, pCommand); pEnv->ReleaseStringUTFChars(command, pCommand); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_setTextSelection (JNIEnv* pEnv, jobject aObject, jint type, jint x, jint y) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->setTextSelection(pDocument, type, x, y); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_setGraphicSelection (JNIEnv* pEnv, jobject aObject, jint type, jint x, jint y) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->setGraphicSelection(pDocument, type, x, y); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_resetSelection (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->resetSelection(pDocument); } /* DirectBufferAllocator */ extern "C" SAL_JNI_EXPORT jobject JNICALL Java_org_libreoffice_kit_DirectBufferAllocator_allocateDirectBufferNative (JNIEnv* pEnv, jclass /*aClass*/, jint nSize) { jobject aBuffer = NULL; if (nSize > 0) { void* pMemory = malloc(nSize); if (pMemory != NULL) { aBuffer = pEnv->NewDirectByteBuffer(pMemory, nSize); if (aBuffer == NULL) { free(pMemory); } } } return aBuffer; } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_DirectBufferAllocator_freeDirectBufferNative (JNIEnv* pEnv, jclass, jobject aBuffer) { free(pEnv->GetDirectBufferAddress(aBuffer)); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>desktop: fix Android build<commit_after>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <unistd.h> #include <jni.h> #include <sal/types.h> #include <android/log.h> #include <osl/detail/android-bootstrap.h> #define LOK_USE_UNSTABLE_API #include <LibreOfficeKit/LibreOfficeKit.h> /* LibreOfficeKit */ namespace { jfieldID getHandleField(JNIEnv* pEnv, jobject aObject) { jclass clazz = pEnv->GetObjectClass(aObject); return pEnv->GetFieldID(clazz, "handle", "Ljava/nio/ByteBuffer;"); } template <typename T> T* getHandle(JNIEnv* pEnv, jobject aObject) { jobject aHandle = pEnv->GetObjectField(aObject, getHandleField(pEnv, aObject)); return reinterpret_cast<T*>(pEnv->GetDirectBufferAddress(aHandle)); } const char* copyJavaString(JNIEnv* pEnv, jstring aJavaString) { const char* pClone = NULL; const char* pTemp = pEnv->GetStringUTFChars(aJavaString, NULL); pClone = strdup(pTemp); pEnv->ReleaseStringUTFChars(aJavaString, pTemp); return pClone; } } // anonymous namespace extern "C" SAL_JNI_EXPORT jstring JNICALL Java_org_libreoffice_kit_Office_getError (JNIEnv* pEnv, jobject aObject) { LibreOfficeKit* pLibreOfficeKit = getHandle<LibreOfficeKit>(pEnv, aObject); char* pError = pLibreOfficeKit->pClass->getError(pLibreOfficeKit); return pEnv->NewStringUTF(pError); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Office_destroy (JNIEnv* pEnv, jobject aObject) { LibreOfficeKit* pLibreOfficeKit = getHandle<LibreOfficeKit>(pEnv, aObject); pLibreOfficeKit->pClass->destroy(pLibreOfficeKit); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Office_destroyAndExit(JNIEnv* pEnv, jobject aObject) { LibreOfficeKit* pLibreOfficeKit = getHandle<LibreOfficeKit>(pEnv, aObject); pLibreOfficeKit->pClass->destroy(pLibreOfficeKit); // Stopgap fix: _exit() to force the OS to restart the LO activity. // Better than to hang. _exit(0); } namespace { struct CallbackData { jmethodID aJavaCallbackMethod; jclass aClass; jobject aObject; }; static CallbackData gCallbackData; /** * Handle retrieved callback */ void messageCallback(int nType, const char* pPayload, void* pData) { CallbackData* pCallbackData = (CallbackData*) pData; JavaVM* pJavaVM = lo_get_javavm(); JNIEnv* pEnv; bool bIsAttached = false; int status = pJavaVM->GetEnv((void **) &pEnv, JNI_VERSION_1_6); if(status < 0) { status = pJavaVM->AttachCurrentThread(&pEnv, NULL); if(status < 0) { return; } bIsAttached = true; } jstring sPayload = pEnv->NewStringUTF(pPayload); jvalue aParameter[2]; aParameter[0].i = nType; aParameter[1].l = sPayload; pEnv->CallVoidMethodA(pCallbackData->aObject, pCallbackData->aJavaCallbackMethod, aParameter); pEnv->DeleteLocalRef(sPayload); if (bIsAttached) { pJavaVM->DetachCurrentThread(); } } } // anonymous namespace extern "C" SAL_JNI_EXPORT jobject JNICALL Java_org_libreoffice_kit_Office_documentLoadNative (JNIEnv* pEnv, jobject aObject, jstring documentPath) { const char* aCloneDocumentPath = copyJavaString(pEnv, documentPath); LibreOfficeKit* pLibreOfficeKit = getHandle<LibreOfficeKit>(pEnv, aObject); LibreOfficeKitDocument* pDocument = pLibreOfficeKit->pClass->documentLoad(pLibreOfficeKit, aCloneDocumentPath); if (pDocument == NULL) return NULL; jobject aHandle = pEnv->NewDirectByteBuffer((void*) pDocument, sizeof(LibreOfficeKitDocument)); return aHandle; } /* Document */ /** Implementation of org.libreoffice.kit.Document.bindMessageCallback method */ extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_bindMessageCallback (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); gCallbackData.aObject = (jobject) pEnv->NewGlobalRef(aObject); jclass aClass = pEnv->GetObjectClass(aObject); gCallbackData.aClass = (jclass) pEnv->NewGlobalRef(aClass); gCallbackData.aJavaCallbackMethod = pEnv->GetMethodID(aClass, "messageRetrieved", "(ILjava/lang/String;)V"); pDocument->pClass->registerCallback(pDocument, messageCallback, (void*) &gCallbackData); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_destroy (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->destroy(pDocument); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_setPart (JNIEnv* pEnv, jobject aObject, jint aPart) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->setPart(pDocument, aPart); } extern "C" SAL_JNI_EXPORT jint JNICALL Java_org_libreoffice_kit_Document_getPart (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); return (jint) pDocument->pClass->getPart(pDocument); } extern "C" SAL_JNI_EXPORT jint JNICALL Java_org_libreoffice_kit_Document_getParts (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); return (jint) pDocument->pClass->getParts(pDocument); } extern "C" SAL_JNI_EXPORT jstring JNICALL Java_org_libreoffice_kit_Document_getPartName (JNIEnv* pEnv, jobject aObject, jint nPartIndex) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); char* pPartName = pDocument->pClass->getPartName(pDocument, nPartIndex); return pEnv->NewStringUTF(pPartName); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_setPartMode (JNIEnv* pEnv, jobject aObject, jint nPartMode) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->setPartMode(pDocument, nPartMode); } extern "C" SAL_JNI_EXPORT jint JNICALL Java_org_libreoffice_kit_Document_getDocumentTypeNative (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); return (jint) pDocument->pClass->getDocumentType(pDocument); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_paintTileNative (JNIEnv* pEnv, jobject aObject, jobject aByteBuffer, jint nCanvasWidth, jint nCanvasHeight, jint nTilePosX, jint nTilePosY, jint nTileWidth, jint nTileHeight) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); unsigned char* buffer = (unsigned char*) pEnv->GetDirectBufferAddress(aByteBuffer); pDocument->pClass->paintTile(pDocument, buffer, nCanvasWidth, nCanvasHeight, nTilePosX, nTilePosY, nTileWidth, nTileHeight); } extern "C" SAL_JNI_EXPORT jlong JNICALL Java_org_libreoffice_kit_Document_getDocumentHeight (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); long nWidth; long nHeight; pDocument->pClass->getDocumentSize(pDocument, &nWidth, &nHeight); return nHeight; } extern "C" SAL_JNI_EXPORT jlong JNICALL Java_org_libreoffice_kit_Document_getDocumentWidth (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); long nWidth; long nHeight; pDocument->pClass->getDocumentSize(pDocument, &nWidth, &nHeight); return nWidth; } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_initializeForRendering (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->initializeForRendering(pDocument); } extern "C" SAL_JNI_EXPORT jint JNICALL Java_org_libreoffice_kit_Office_saveAs (JNIEnv* pEnv, jobject aObject, jstring sUrl, jstring sFormat, jstring sOptions) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); const char* pUrl = pEnv->GetStringUTFChars(sUrl, NULL); const char* pFormat = pEnv->GetStringUTFChars(sFormat, NULL); const char* pOptions = pEnv->GetStringUTFChars(sOptions, NULL); int result = pDocument->pClass->saveAs(pDocument, pUrl, pFormat, pOptions); pEnv->ReleaseStringUTFChars(sUrl, pUrl); pEnv->ReleaseStringUTFChars(sFormat, pFormat); pEnv->ReleaseStringUTFChars(sOptions, pOptions); return result; } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_postKeyEvent (JNIEnv* pEnv, jobject aObject, jint nType, jint nCharCode, jint nKeyCode) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->postKeyEvent(pDocument, nType, nCharCode, nKeyCode); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_postMouseEvent (JNIEnv* pEnv, jobject aObject, jint type, jint x, jint y, jint count) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->postMouseEvent(pDocument, type, x, y, count); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_postUnoCommand (JNIEnv* pEnv, jobject aObject, jstring command) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); const char* pCommand = pEnv->GetStringUTFChars(command, NULL); pDocument->pClass->postUnoCommand(pDocument, pCommand, 0); pEnv->ReleaseStringUTFChars(command, pCommand); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_setTextSelection (JNIEnv* pEnv, jobject aObject, jint type, jint x, jint y) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->setTextSelection(pDocument, type, x, y); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_setGraphicSelection (JNIEnv* pEnv, jobject aObject, jint type, jint x, jint y) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->setGraphicSelection(pDocument, type, x, y); } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_Document_resetSelection (JNIEnv* pEnv, jobject aObject) { LibreOfficeKitDocument* pDocument = getHandle<LibreOfficeKitDocument>(pEnv, aObject); pDocument->pClass->resetSelection(pDocument); } /* DirectBufferAllocator */ extern "C" SAL_JNI_EXPORT jobject JNICALL Java_org_libreoffice_kit_DirectBufferAllocator_allocateDirectBufferNative (JNIEnv* pEnv, jclass /*aClass*/, jint nSize) { jobject aBuffer = NULL; if (nSize > 0) { void* pMemory = malloc(nSize); if (pMemory != NULL) { aBuffer = pEnv->NewDirectByteBuffer(pMemory, nSize); if (aBuffer == NULL) { free(pMemory); } } } return aBuffer; } extern "C" SAL_JNI_EXPORT void JNICALL Java_org_libreoffice_kit_DirectBufferAllocator_freeDirectBufferNative (JNIEnv* pEnv, jclass, jobject aBuffer) { free(pEnv->GetDirectBufferAddress(aBuffer)); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// // main.c // EmojicodeCompiler // // Created by Theo Weidmann on 27.02.15. // Copyright (c) 2015 Theo Weidmann. All rights reserved. // #include <libgen.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include "Lexer.hpp" #include "utf8.h" #include "EmojicodeCompiler.hpp" #include "FileParser.hpp" #include "StaticAnalyzer.hpp" #include "Class.hpp" StartingFlag startingFlag; bool foundStartingFlag; std::map<std::array<EmojicodeChar, 2>, Class*> classesRegister; std::map<std::array<EmojicodeChar, 2>, Protocol*> protocolsRegister; std::map<std::array<EmojicodeChar, 2>, Enum*> enumsRegister; std::vector<Class *> classes; std::vector<Package *> packages; char* EmojicodeString::utf8CString() const { //Size needed for UTF8 representation size_t ds = u8_codingsize(c_str(), size()); //Allocate space for the UTF8 string char *utf8str = new char[ds + 1]; //Convert size_t written = u8_toutf8(utf8str, ds, c_str(), size()); utf8str[written] = 0; return utf8str; } static bool outputJSON = false; static bool gaveWarning = false; void printJSONStringToFile(const char *string, FILE *f){ char c; fputc('"', f); while ((c = *(string++))) { switch (c) { case '\\': fprintf(f, "\\\\"); break; case '"': fprintf(f, "\\\""); break; case '/': fprintf(f, "\\/"); break; case '\b': fprintf(f, "\\b"); break; case '\f': fprintf(f, "\\f"); break; case '\n': fprintf(f, "\\n"); break; case '\r': fprintf(f, "\\r"); break; case '\t': fprintf(f, "\\t"); break; default: fputc(c, f); } } fputc('"', f); } //MARK: Warnings void compilerError(const Token *token, const char *err, ...){ va_list list; va_start(list, err); const char *file; char error[450]; vsprintf(error, err, list); size_t line, col; if (token) { line = token->position.line; col = token->position.character; file = token->position.file; } else { line = col = 0; file = ""; } if (outputJSON) { fprintf(stderr, "%s{\"type\": \"error\", \"line\": %zu, \"character\": %zu, \"file\":", gaveWarning ? ",": "", line, col); printJSONStringToFile(file, stderr); fprintf(stderr, ", \"message\":"); printJSONStringToFile(error, stderr); fprintf(stderr, "}\n]"); } else { fprintf(stderr, "🚨 line %zu column %zu %s: %s\n", line, col, file, error); } va_end(list); exit(1); } void compilerWarning(const Token *token, const char *err, ...){ va_list list; va_start(list, err); const char *file; char error[450]; vsprintf(error, err, list); size_t line, col; if (token) { line = token->position.line; col = token->position.character; file = token->position.file; } else { line = col = 0; file = ""; } if (outputJSON) { fprintf(stderr, "%s{\"type\": \"warning\", \"line\": %zu, \"character\": %zu, \"file\":", gaveWarning ? ",": "", line, col); printJSONStringToFile(file, stderr); fprintf(stderr, ", \"message\":"); printJSONStringToFile(error, stderr); fprintf(stderr, "}\n"); } else { fprintf(stderr, "⚠️ line %zu col %zu %s: %s\n", line, col, file, error); } gaveWarning = true; va_end(list); } void loadStandard(){ packageRegisterHeaderNewest("s", globalNamespace); CL_STRING = classes[0]; CL_LIST = classes[1]; CL_ERROR = classes[2]; CL_DATA = classes[3]; CL_ENUMERATOR = classes[4]; CL_DICTIONARY = classes[5]; PR_ENUMERATEABLE = getProtocol(E_CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS_WITH_CIRCLED_ONE_OVERLAY, globalNamespace); } int main(int argc, char * argv[]) { const char *reportPackage = nullptr; std::string outPath; //Parse options char ch; while ((ch = getopt(argc, argv, "vrjR:o:")) != -1) { switch (ch) { case 'v': puts("Emojicode Compiler 1.0.0alpha1. Emojicode 0.2. Built with 💚 by Theo Weidmann."); return 0; break; case 'R': reportPackage = optarg; break; case 'r': reportPackage = "_"; break; case 'o': outPath = optarg; break; case 'j': outputJSON = true; break; default: break; } } argc -= optind; argv += optind; if (outputJSON){ fprintf(stderr, "["); } if(argc == 0){ compilerWarning(nullptr, "No input files provided."); return 1; } if(outPath.size() == 0){ outPath = std::string(argv[0]); outPath[outPath.size() - 1] = 'b'; } foundStartingFlag = false; loadStandard(); Package *pkg = new Package("_", (PackageVersion){1, 0}, false); packages.push_back(pkg); for (int i = 0; i < argc; i++) { parseFile(argv[i], pkg, false, globalNamespace); } FILE *out = fopen(outPath.c_str(), "wb"); if(!out || ferror(out)){ compilerError(nullptr, "Couldn't write output file."); return 1; } //If we did not find a mouse method the programm has no start point if (!foundStartingFlag) { compilerError(nullptr, "No 🏁 eclass method was found."); } //Now let us anaylze these classes and write them analyzeClassesAndWrite(out); if (outputJSON){ fprintf(stderr, "]"); } //Print a report on request if(reportPackage){ report(reportPackage); } return 0; } <commit_msg>🌕 Explicit singed character<commit_after>// // main.c // EmojicodeCompiler // // Created by Theo Weidmann on 27.02.15. // Copyright (c) 2015 Theo Weidmann. All rights reserved. // #include <libgen.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include "Lexer.hpp" #include "utf8.h" #include "EmojicodeCompiler.hpp" #include "FileParser.hpp" #include "StaticAnalyzer.hpp" #include "Class.hpp" StartingFlag startingFlag; bool foundStartingFlag; std::map<std::array<EmojicodeChar, 2>, Class*> classesRegister; std::map<std::array<EmojicodeChar, 2>, Protocol*> protocolsRegister; std::map<std::array<EmojicodeChar, 2>, Enum*> enumsRegister; std::vector<Class *> classes; std::vector<Package *> packages; char* EmojicodeString::utf8CString() const { //Size needed for UTF8 representation size_t ds = u8_codingsize(c_str(), size()); //Allocate space for the UTF8 string char *utf8str = new char[ds + 1]; //Convert size_t written = u8_toutf8(utf8str, ds, c_str(), size()); utf8str[written] = 0; return utf8str; } static bool outputJSON = false; static bool gaveWarning = false; void printJSONStringToFile(const char *string, FILE *f){ char c; fputc('"', f); while ((c = *(string++))) { switch (c) { case '\\': fprintf(f, "\\\\"); break; case '"': fprintf(f, "\\\""); break; case '/': fprintf(f, "\\/"); break; case '\b': fprintf(f, "\\b"); break; case '\f': fprintf(f, "\\f"); break; case '\n': fprintf(f, "\\n"); break; case '\r': fprintf(f, "\\r"); break; case '\t': fprintf(f, "\\t"); break; default: fputc(c, f); } } fputc('"', f); } //MARK: Warnings void compilerError(const Token *token, const char *err, ...){ va_list list; va_start(list, err); const char *file; char error[450]; vsprintf(error, err, list); size_t line, col; if (token) { line = token->position.line; col = token->position.character; file = token->position.file; } else { line = col = 0; file = ""; } if (outputJSON) { fprintf(stderr, "%s{\"type\": \"error\", \"line\": %zu, \"character\": %zu, \"file\":", gaveWarning ? ",": "", line, col); printJSONStringToFile(file, stderr); fprintf(stderr, ", \"message\":"); printJSONStringToFile(error, stderr); fprintf(stderr, "}\n]"); } else { fprintf(stderr, "🚨 line %zu column %zu %s: %s\n", line, col, file, error); } va_end(list); exit(1); } void compilerWarning(const Token *token, const char *err, ...){ va_list list; va_start(list, err); const char *file; char error[450]; vsprintf(error, err, list); size_t line, col; if (token) { line = token->position.line; col = token->position.character; file = token->position.file; } else { line = col = 0; file = ""; } if (outputJSON) { fprintf(stderr, "%s{\"type\": \"warning\", \"line\": %zu, \"character\": %zu, \"file\":", gaveWarning ? ",": "", line, col); printJSONStringToFile(file, stderr); fprintf(stderr, ", \"message\":"); printJSONStringToFile(error, stderr); fprintf(stderr, "}\n"); } else { fprintf(stderr, "⚠️ line %zu col %zu %s: %s\n", line, col, file, error); } gaveWarning = true; va_end(list); } void loadStandard(){ packageRegisterHeaderNewest("s", globalNamespace); CL_STRING = classes[0]; CL_LIST = classes[1]; CL_ERROR = classes[2]; CL_DATA = classes[3]; CL_ENUMERATOR = classes[4]; CL_DICTIONARY = classes[5]; PR_ENUMERATEABLE = getProtocol(E_CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS_WITH_CIRCLED_ONE_OVERLAY, globalNamespace); } int main(int argc, char * argv[]) { const char *reportPackage = nullptr; std::string outPath; //Parse options signed char ch; while ((ch = getopt(argc, argv, "vrjR:o:")) != -1) { switch (ch) { case 'v': puts("Emojicode Compiler 1.0.0alpha1. Emojicode 0.2. Built with 💚 by Theo Weidmann."); return 0; break; case 'R': reportPackage = optarg; break; case 'r': reportPackage = "_"; break; case 'o': outPath = optarg; break; case 'j': outputJSON = true; break; default: break; } } argc -= optind; argv += optind; if (outputJSON){ fprintf(stderr, "["); } if(argc == 0){ compilerWarning(nullptr, "No input files provided."); return 1; } if(outPath.size() == 0){ outPath = std::string(argv[0]); outPath[outPath.size() - 1] = 'b'; } foundStartingFlag = false; loadStandard(); Package *pkg = new Package("_", (PackageVersion){1, 0}, false); packages.push_back(pkg); for (int i = 0; i < argc; i++) { parseFile(argv[i], pkg, false, globalNamespace); } FILE *out = fopen(outPath.c_str(), "wb"); if(!out || ferror(out)){ compilerError(nullptr, "Couldn't write output file."); return 1; } //If we did not find a mouse method the programm has no start point if (!foundStartingFlag) { compilerError(nullptr, "No 🏁 eclass method was found."); } //Now let us anaylze these classes and write them analyzeClassesAndWrite(out); if (outputJSON){ fprintf(stderr, "]"); } //Print a report on request if(reportPackage){ report(reportPackage); } return 0; } <|endoftext|>
<commit_before>#include "Globals.h" #include "Engine.h" #include "ModuleRender.h" #include "ModuleTextures.h" #include "SDL/include/SDL.h" #include "SDL_image/include/SDL_image.h" #include <IL/ilut.h> #include <cassert> #pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" ) using namespace std; ModuleTextures::ModuleTextures() { } // Destructor ModuleTextures::~ModuleTextures() { IMG_Quit(); } // Called before render is available bool ModuleTextures::Init() { LOG("Init Texture Manager"); bool ret = true; // load support for the PNG image format ilInit(); iluInit(); ilutInit(); // Enable OpenGL access to DevIL ilutRenderer(ILUT_OPENGL); ilutEnable(ILUT_OPENGL_CONV); return ret; } // Called before quitting bool ModuleTextures::CleanUp() { LOG("Freeing textures and Texture Manager"); for (TextureMap::iterator it = _textures.begin(); it != _textures.end(); ++it) { glDeleteTextures(1, &it->second); } _textures.clear(); return true; } // Load new texture from file path unsigned ModuleTextures::Load(const string& path) { TextureMap::iterator it = _textures.find(path); if (it != _textures.end()) return it->second; unsigned textureID = 0; ILuint imageID; ilGenImages(1, &imageID); ilBindImage(imageID); ilLoadImage(path.c_str()); ILubyte* data = ilGetData(); if (!data) { ilBindImage(0); ilDeleteImages(1, &imageID); return 0; } int width = ilGetInteger(IL_IMAGE_WIDTH); int height = ilGetInteger(IL_IMAGE_HEIGHT); int components = 3; int format = GL_RGB; switch (ilGetInteger(IL_IMAGE_FORMAT)) { case IL_RGB: components = 3; format = GL_RGB; break; case IL_RGBA: components = 4; format = GL_RGBA; break; case IL_BGR: components = 3; format = GL_BGR_EXT; break; case IL_BGRA: components = 4; format = GL_BGRA_EXT; break; default: assert(false); } glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, components, width, height, 0, format, GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); ilDeleteImage(imageID); _textures[path] = textureID; return textureID; } // Free texture from memory void ModuleTextures::Unload(unsigned id) { for (TextureMap::iterator it = _textures.begin(); it != _textures.end(); ++it) { if (it->second == id) { glDeleteTextures(1, &it->second); _textures.erase(it); break; } } }<commit_msg>Fix moduleTextures<commit_after>#include "Globals.h" #include "Engine.h" #include "ModuleRender.h" #include "ModuleTextures.h" #include "SDL/include/SDL.h" #include "SDL_image/include/SDL_image.h" #include <IL/ilut.h> #include <cassert> #pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" ) using namespace std; ModuleTextures::ModuleTextures() { } // Destructor ModuleTextures::~ModuleTextures() { IMG_Quit(); } // Called before render is available bool ModuleTextures::Init() { LOG("Init Texture Manager"); bool ret = true; // load support for the PNG image format ilInit(); iluInit(); ilutInit(); // Enable OpenGL access to DevIL ilutRenderer(ILUT_OPENGL); ilutEnable(ILUT_OPENGL_CONV); return ret; } // Called before quitting bool ModuleTextures::CleanUp() { LOG("Freeing textures and Texture Manager"); for (TextureMap::iterator it = _textures.begin(); it != _textures.end(); ++it) { glDeleteTextures(1, &it->second); } _textures.clear(); return true; } // Load new texture from file path unsigned ModuleTextures::Load(const string& path) { TextureMap::iterator it = _textures.find(path); if (it != _textures.end()) return it->second; unsigned textureID = 0; ILuint imageID; ilGenImages(1, &imageID); ilBindImage(imageID); ilLoadImage(path.c_str()); ILubyte* data = ilGetData(); if (!data) { ilBindImage(0); ilDeleteImages(1, &imageID); return 0; } ILinfo ImageInfo; iluGetImageInfo(&ImageInfo); if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT) { iluFlipImage(); } ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE); int width = ilGetInteger(IL_IMAGE_WIDTH); int height = ilGetInteger(IL_IMAGE_HEIGHT); data = ilGetData(); glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_FORMAT), width, height, 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); ilDeleteImage(imageID); _textures[path] = textureID; return textureID; } // Free texture from memory void ModuleTextures::Unload(unsigned id) { for (TextureMap::iterator it = _textures.begin(); it != _textures.end(); ++it) { if (it->second == id) { glDeleteTextures(1, &it->second); _textures.erase(it); break; } } }<|endoftext|>
<commit_before>/* Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Terrain.h" #include "Device.h" #include "Renderer.h" #include "MathUtils.h" #include "Log.h" #include "Vec2.h" #include "Interpolation.h" namespace crown { Terrain::Terrain() : mHeights(NULL), mMinHeight(-10.0f), mMaxHeight(10.0f), mVertices(NULL), mNormals(NULL), mTexCoords(NULL), mIndices(NULL) { } Terrain::~Terrain() { if (mHeights != NULL) { delete[] mHeights; } delete[] mVertices; delete[] mNormals; delete[] mTexCoords; delete[] mIndices; } void Terrain::CreateTerrain(uint32_t xSize, uint32_t zSize, uint32_t tilePerMeter, float initialHeight) { assert(xSize > 0); assert(zSize > 0); assert(tilePerMeter > 0); mSizeX = xSize; mSizeZ = zSize; mTilePerMeter = tilePerMeter; float tileStep = +(float)mSizeX / ((float)mSizeX * (float)mTilePerMeter); // Tile step is the same for both x and z ;) mTilesInSizeX = ((float)mSizeX / tileStep); mTilesInSizeZ = ((float)mSizeZ / tileStep); mVerticesInSizeX = mTilesInSizeX + 1; mVerticesInSizeZ = mTilesInSizeZ + 1; Log::d("Vertices in size x/z: %d %d\n", mVerticesInSizeX, mVerticesInSizeZ); uint32_t heightsCount = mVerticesInSizeX * mVerticesInSizeZ; mHeights = new float[heightsCount]; // Init heights for (uint32_t i = 0; i < heightsCount; i++) { mHeights[i] = initialHeight; } // Construct drawing data mVertices = new Vec3[heightsCount]; // There are as many vertices as heights mVertexCount = heightsCount; mNormals = new Vec3[heightsCount]; // Same as vertices mNormalCount = heightsCount; mTexCoords = new Vec2[heightsCount]; // Same as vertices mTexCoordCount = heightsCount; mIndices = new uint16_t[mTilesInSizeX * mTilesInSizeZ * 6]; // mIndexCount = mTilesInSizeX * mTilesInSizeZ * 6; // Populate vertex list (generate a grid lying on the xz-plane and facing upwards) float xStart = -(float)mSizeX * 0.5f; float zStart = +(float)mSizeZ * 0.5f; mOffsetX = xStart; mOffsetZ = zStart; uint32_t vIndex = 0; // Just because I'm lazy float xCurrent; // Keeps track of current x position float zCurrent = zStart; // Keeps track of current z position for (uint32_t z = 0; z < mVerticesInSizeZ; z++) { xCurrent = xStart; for (uint32_t x = 0; x < mVerticesInSizeX; x++) { mVertices[vIndex].x = xCurrent; mVertices[vIndex].y = mHeights[vIndex]; mVertices[vIndex].z = zCurrent; mNormals[vIndex].x = 0.0f; mNormals[vIndex].y = 1.0f; mNormals[vIndex].z = 0.0f; mTexCoords[vIndex].x = (float)x; mTexCoords[vIndex].y = (float)z; vIndex++; xCurrent += tileStep; } zCurrent -= tileStep; } // Populate index list uint32_t iIndex = 0; for (uint32_t z = 0; z < mTilesInSizeZ; z++) { for (uint32_t x = 0; x < mTilesInSizeX; x++) { uint32_t firstRow = z * mVerticesInSizeX + x; uint32_t secondRow = (z + 1) * mVerticesInSizeX + x; mIndices[iIndex + 0] = firstRow; mIndices[iIndex + 1] = secondRow + 1; mIndices[iIndex + 2] = secondRow; mIndices[iIndex + 3] = firstRow; mIndices[iIndex + 4] = firstRow + 1; mIndices[iIndex + 5] = secondRow + 1; iIndex += 6; } } } void Terrain::UpdateVertexBuffer(bool recomputeNormals) { uint32_t vIndex = 0; for (uint32_t z = 0; z < mVerticesInSizeZ; z++) { for (uint32_t x = 0; x < mVerticesInSizeX; x++) { mVertices[vIndex].y = mHeights[vIndex]; vIndex++; } } if (recomputeNormals) { for (uint32_t i = 0; i < mIndexCount; i += 3) { Vec3 normal; Vec3 v1; Vec3 v2; v1 = mVertices[mIndices[i + 0]] - mVertices[mIndices[i + 1]]; v2 = mVertices[mIndices[i + 2]] - mVertices[mIndices[i + 1]]; normal = v2.cross(v1).normalize(); mNormals[mIndices[i + 0]] = normal; mNormals[mIndices[i + 1]] = normal; mNormals[mIndices[i + 2]] = normal; } } } float Terrain::GetHeightAt(uint32_t x, uint32_t z) const { if (x > mVerticesInSizeX) return 0.0f; if (z > mVerticesInSizeZ) return 0.0f; return mHeights[z * mVerticesInSizeX + x]; } float Terrain::GetHeightAt(const Vec3& xyz) const { uint32_t x, z; WorldToHeight(xyz, x, z); return GetHeightAt(x, z); } void Terrain::SetHeightAt(uint32_t x, uint32_t z, float height) { if (x >= mVerticesInSizeX) return; if (z >= mVerticesInSizeZ) return; mHeights[z * mVerticesInSizeX + x] += height; mHeights[z * mVerticesInSizeX + x] = math::clamp_to_range(mMinHeight, mMaxHeight, mHeights[z * mVerticesInSizeX + x]); } void Terrain::SetHeightAt(const Vec3& xyz, float height) { uint32_t x, z; WorldToHeight(xyz, x, z); SetHeightAt(x + 0, z + 0, height); } void Terrain::WorldToHeight(const Vec3& xyz, uint32_t& x, uint32_t& z) const { Vec3 offsetted = xyz + Vec3(-mOffsetX, 0.0f, mOffsetZ); offsetted.z = (float)mSizeZ - offsetted.z; x = (uint32_t)offsetted.x; z = (uint32_t)offsetted.z; } bool Terrain::TraceRay(const Ray& ray, Triangle& result, Triangle& /*tri2*/, real& dist) { bool hit = false; real minDist = 9999999.0f; for (uint32_t i = 0; i < mIndexCount; i += 3) { Triangle tri(mVertices[mIndices[i + 0]], mVertices[mIndices[i + 1]], mVertices[mIndices[i + 2]]); real ret; Vec3 int32_tersectionPoint32_t; if (Intersection::TestRayTriangle(ray, tri, ret, int32_tersectionPoint32_t)) { if (ret < minDist) { minDist = ret; result = tri; } hit = true; } } dist = minDist; return hit; } uint32_t Terrain::SnapToGrid(const Vec3& vertex) { float minDist = 9999999.0f; uint32_t indexToSnapped; // Find the snapped point32_t to input vertex for (uint32_t i = 0; i < mVertexCount; i++) { Vec3 tmp = mVertices[i]; Vec3 vertex2 = vertex; tmp.y = vertex2.y = 0.0f; if (tmp.get_distance_to(vertex2) < minDist) { indexToSnapped = i; minDist = tmp.get_distance_to(vertex2); } } return indexToSnapped; } void Terrain::Render() { Renderer* renderer = device()->renderer(); renderer->draw_triangles( mVertices[0].to_float_ptr(), mNormals[0].to_float_ptr(), mTexCoords[0].to_float_ptr(), mIndices, mTilesInSizeX * mTilesInSizeZ * 6); } float Terrain::GaussDist(float x, float y, float sigma) { float gauss = 1.0f / math::TWO_PI * (sigma * sigma); float e = 2.71828183f; float exponent = ((x * x) + (y * y)) / (2.0f * (sigma * sigma)); return gauss * pow(e, -exponent); } void Terrain::BuildBrush(uint32_t width, uint32_t height, float smooth) { assert(width < MAX_BRUSH_SIZE); assert(height < MAX_BRUSH_SIZE); mBrushWidth = width; mBrushHeight = height; float xStart = -(float)width * 0.5f; float yStart = -(float)height * 0.5f; float xCurrent = xStart; for (uint32_t i = 0; i <= width; i++) { float yCurrent = yStart; for (uint32_t j = 0; j <= height; j++) { mBrush[j * MAX_BRUSH_SIZE + i] = GaussDist(xCurrent, yCurrent, smooth); yCurrent += 1.0f; } xCurrent += 1.0f; } } void Terrain::PlotCircle(int32_t xx, int32_t yy, int32_t radius, int32_t i) { for (int32_t j = 0; j < 256 * 256; j++) { mBrush[j] = 0; } int32_t x, y; mBrushWidth = radius * 2; mBrushHeight = radius * 2; for (y = -radius; y <= radius; y++) for (x = -radius; x <= radius; x++) if ((x * x) + (y * y) <= (radius * radius)) { float rDist = 1.0 - math::sqrt(x * x + y * y) / radius; if (i == 0) { mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = interpolation::linear(0.0f, 1.0f, rDist); } else if (i == 1) { mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = interpolation::cosine(0.0f, 1.0f, rDist); } else if (i == 2) { mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = interpolation::cubic(0.0f, 1.0f, rDist); } } } void Terrain::ApplyBrush(uint32_t x, uint32_t z, float scale) { uint32_t offsetX = mBrushWidth / 2; uint32_t offsetY = mBrushHeight / 2; for (uint32_t i = 0; i < mBrushWidth; i++) { for (uint32_t j = 0; j < mBrushHeight; j++) { SetHeightAt((x - offsetX) + i, (z - offsetY) + j, scale * mBrush[j * MAX_BRUSH_SIZE + i]); } } } void Terrain::ApplyBrush(const Vec3& xyz, float scale) { uint32_t x, z; WorldToHeight(xyz, x, z); ApplyBrush(x, z, scale); } } // namespace crown <commit_msg>Update Terrain<commit_after>/* Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Terrain.h" #include "Device.h" #include "Renderer.h" #include "MathUtils.h" #include "Log.h" #include "Vec2.h" #include "Interpolation.h" namespace crown { Terrain::Terrain() : mHeights(NULL), mMinHeight(-10.0f), mMaxHeight(10.0f), mVertices(NULL), mNormals(NULL), mTexCoords(NULL), mIndices(NULL) { } Terrain::~Terrain() { if (mHeights != NULL) { delete[] mHeights; } delete[] mVertices; delete[] mNormals; delete[] mTexCoords; delete[] mIndices; } void Terrain::CreateTerrain(uint32_t xSize, uint32_t zSize, uint32_t tilePerMeter, float initialHeight) { assert(xSize > 0); assert(zSize > 0); assert(tilePerMeter > 0); mSizeX = xSize; mSizeZ = zSize; mTilePerMeter = tilePerMeter; float tileStep = +(float)mSizeX / ((float)mSizeX * (float)mTilePerMeter); // Tile step is the same for both x and z ;) mTilesInSizeX = ((float)mSizeX / tileStep); mTilesInSizeZ = ((float)mSizeZ / tileStep); mVerticesInSizeX = mTilesInSizeX + 1; mVerticesInSizeZ = mTilesInSizeZ + 1; Log::d("Vertices in size x/z: %d %d\n", mVerticesInSizeX, mVerticesInSizeZ); uint32_t heightsCount = mVerticesInSizeX * mVerticesInSizeZ; mHeights = new float[heightsCount]; // Init heights for (uint32_t i = 0; i < heightsCount; i++) { mHeights[i] = initialHeight; } // Construct drawing data mVertices = new Vec3[heightsCount]; // There are as many vertices as heights mVertexCount = heightsCount; mNormals = new Vec3[heightsCount]; // Same as vertices mNormalCount = heightsCount; mTexCoords = new Vec2[heightsCount]; // Same as vertices mTexCoordCount = heightsCount; mIndices = new uint16_t[mTilesInSizeX * mTilesInSizeZ * 6]; // mIndexCount = mTilesInSizeX * mTilesInSizeZ * 6; // Populate vertex list (generate a grid lying on the xz-plane and facing upwards) float xStart = -(float)mSizeX * 0.5f; float zStart = +(float)mSizeZ * 0.5f; mOffsetX = xStart; mOffsetZ = zStart; uint32_t vIndex = 0; // Just because I'm lazy float xCurrent; // Keeps track of current x position float zCurrent = zStart; // Keeps track of current z position for (uint32_t z = 0; z < mVerticesInSizeZ; z++) { xCurrent = xStart; for (uint32_t x = 0; x < mVerticesInSizeX; x++) { mVertices[vIndex].x = xCurrent; mVertices[vIndex].y = mHeights[vIndex]; mVertices[vIndex].z = zCurrent; mNormals[vIndex].x = 0.0f; mNormals[vIndex].y = 1.0f; mNormals[vIndex].z = 0.0f; mTexCoords[vIndex].x = (float)x; mTexCoords[vIndex].y = (float)z; vIndex++; xCurrent += tileStep; } zCurrent -= tileStep; } // Populate index list uint32_t iIndex = 0; for (uint32_t z = 0; z < mTilesInSizeZ; z++) { for (uint32_t x = 0; x < mTilesInSizeX; x++) { uint32_t firstRow = z * mVerticesInSizeX + x; uint32_t secondRow = (z + 1) * mVerticesInSizeX + x; mIndices[iIndex + 0] = firstRow; mIndices[iIndex + 1] = secondRow + 1; mIndices[iIndex + 2] = secondRow; mIndices[iIndex + 3] = firstRow; mIndices[iIndex + 4] = firstRow + 1; mIndices[iIndex + 5] = secondRow + 1; iIndex += 6; } } } void Terrain::UpdateVertexBuffer(bool recomputeNormals) { uint32_t vIndex = 0; for (uint32_t z = 0; z < mVerticesInSizeZ; z++) { for (uint32_t x = 0; x < mVerticesInSizeX; x++) { mVertices[vIndex].y = mHeights[vIndex]; vIndex++; } } if (recomputeNormals) { for (uint32_t i = 0; i < mIndexCount; i += 3) { Vec3 normal; Vec3 v1; Vec3 v2; v1 = mVertices[mIndices[i + 0]] - mVertices[mIndices[i + 1]]; v2 = mVertices[mIndices[i + 2]] - mVertices[mIndices[i + 1]]; normal = v2.cross(v1).normalize(); mNormals[mIndices[i + 0]] = normal; mNormals[mIndices[i + 1]] = normal; mNormals[mIndices[i + 2]] = normal; } } } float Terrain::GetHeightAt(uint32_t x, uint32_t z) const { if (x > mVerticesInSizeX) return 0.0f; if (z > mVerticesInSizeZ) return 0.0f; return mHeights[z * mVerticesInSizeX + x]; } float Terrain::GetHeightAt(const Vec3& xyz) const { uint32_t x, z; WorldToHeight(xyz, x, z); return GetHeightAt(x, z); } void Terrain::SetHeightAt(uint32_t x, uint32_t z, float height) { if (x >= mVerticesInSizeX) return; if (z >= mVerticesInSizeZ) return; mHeights[z * mVerticesInSizeX + x] += height; mHeights[z * mVerticesInSizeX + x] = math::clamp_to_range(mMinHeight, mMaxHeight, mHeights[z * mVerticesInSizeX + x]); } void Terrain::SetHeightAt(const Vec3& xyz, float height) { uint32_t x, z; WorldToHeight(xyz, x, z); SetHeightAt(x + 0, z + 0, height); } void Terrain::WorldToHeight(const Vec3& xyz, uint32_t& x, uint32_t& z) const { Vec3 offsetted = xyz + Vec3(-mOffsetX, 0.0f, mOffsetZ); offsetted.z = (float)mSizeZ - offsetted.z; x = (uint32_t)offsetted.x; z = (uint32_t)offsetted.z; } bool Terrain::TraceRay(const Ray& ray, Triangle& result, Triangle& /*tri2*/, real& dist) { bool hit = false; real minDist = 9999999.0f; for (uint32_t i = 0; i < mIndexCount; i += 3) { Triangle tri(mVertices[mIndices[i + 0]], mVertices[mIndices[i + 1]], mVertices[mIndices[i + 2]]); real ret; Vec3 int32_tersectionPoint32_t; if (Intersection::test_ray_triangle(ray, tri, ret, int32_tersectionPoint32_t)) { if (ret < minDist) { minDist = ret; result = tri; } hit = true; } } dist = minDist; return hit; } uint32_t Terrain::SnapToGrid(const Vec3& vertex) { float minDist = 9999999.0f; uint32_t indexToSnapped; // Find the snapped point32_t to input vertex for (uint32_t i = 0; i < mVertexCount; i++) { Vec3 tmp = mVertices[i]; Vec3 vertex2 = vertex; tmp.y = vertex2.y = 0.0f; if (tmp.get_distance_to(vertex2) < minDist) { indexToSnapped = i; minDist = tmp.get_distance_to(vertex2); } } return indexToSnapped; } void Terrain::Render() { Renderer* renderer = device()->renderer(); renderer->draw_triangles( mVertices[0].to_float_ptr(), mNormals[0].to_float_ptr(), mTexCoords[0].to_float_ptr(), mIndices, mTilesInSizeX * mTilesInSizeZ * 6); } float Terrain::GaussDist(float x, float y, float sigma) { float gauss = 1.0f / math::TWO_PI * (sigma * sigma); float e = 2.71828183f; float exponent = ((x * x) + (y * y)) / (2.0f * (sigma * sigma)); return gauss * pow(e, -exponent); } void Terrain::BuildBrush(uint32_t width, uint32_t height, float smooth) { assert(width < MAX_BRUSH_SIZE); assert(height < MAX_BRUSH_SIZE); mBrushWidth = width; mBrushHeight = height; float xStart = -(float)width * 0.5f; float yStart = -(float)height * 0.5f; float xCurrent = xStart; for (uint32_t i = 0; i <= width; i++) { float yCurrent = yStart; for (uint32_t j = 0; j <= height; j++) { mBrush[j * MAX_BRUSH_SIZE + i] = GaussDist(xCurrent, yCurrent, smooth); yCurrent += 1.0f; } xCurrent += 1.0f; } } void Terrain::PlotCircle(int32_t xx, int32_t yy, int32_t radius, int32_t i) { for (int32_t j = 0; j < 256 * 256; j++) { mBrush[j] = 0; } int32_t x, y; mBrushWidth = radius * 2; mBrushHeight = radius * 2; for (y = -radius; y <= radius; y++) for (x = -radius; x <= radius; x++) if ((x * x) + (y * y) <= (radius * radius)) { float rDist = 1.0 - math::sqrt(x * x + y * y) / radius; if (i == 0) { mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = interpolation::linear(0.0f, 1.0f, rDist); } else if (i == 1) { mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = interpolation::cosine(0.0f, 1.0f, rDist); } else if (i == 2) { mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = interpolation::cubic(0.0f, 1.0f, rDist); } } } void Terrain::ApplyBrush(uint32_t x, uint32_t z, float scale) { uint32_t offsetX = mBrushWidth / 2; uint32_t offsetY = mBrushHeight / 2; for (uint32_t i = 0; i < mBrushWidth; i++) { for (uint32_t j = 0; j < mBrushHeight; j++) { SetHeightAt((x - offsetX) + i, (z - offsetY) + j, scale * mBrush[j * MAX_BRUSH_SIZE + i]); } } } void Terrain::ApplyBrush(const Vec3& xyz, float scale) { uint32_t x, z; WorldToHeight(xyz, x, z); ApplyBrush(x, z, scale); } } // namespace crown <|endoftext|>
<commit_before>// Button.cc for FbTk - fluxbox toolkit // Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // 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: Button.cc,v 1.8 2003/06/05 12:42:31 fluxgen Exp $ #include "Button.hh" #include "Command.hh" #include "EventManager.hh" #include "App.hh" namespace FbTk { Button::Button(int screen_num, int x, int y, unsigned int width, unsigned int height): m_win(screen_num, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_foreground_pm(0), m_background_pm(0), m_pressed_pm(0), m_gc(DefaultGC(FbTk::App::instance()->display(), screen_num)), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, m_win); } Button::Button(const FbWindow &parent, int x, int y, unsigned int width, unsigned int height): m_win(parent, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_foreground_pm(0), m_background_pm(0), m_pressed_pm(0), m_gc(DefaultGC(FbTk::App::instance()->display(), m_win.screenNumber())), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, m_win); } Button::~Button() { FbTk::EventManager::instance()->remove(m_win); } void Button::setOnClick(RefCount<Command> &cmd, int button) { // we only handle buttons 1 to 5 if (button > 5 || button == 0) return; //set on click command for the button m_onclick[button - 1] = cmd; } void Button::move(int x, int y) { m_win.move(x, y); } void Button::resize(unsigned int w, unsigned int h) { m_win.resize(w, h); } void Button::moveResize(int x, int y, unsigned int width, unsigned int height) { m_win.moveResize(x, y, width, height); } void Button::setPixmap(Pixmap pm) { m_foreground_pm = pm; } void Button::setPressedPixmap(Pixmap pm) { m_pressed_pm = pm; } void Button::setBackgroundColor(const Color &color) { m_win.setBackgroundColor(color); m_background_color = color; clear(); } void Button::setBackgroundPixmap(Pixmap pm) { m_win.setBackgroundPixmap(pm); m_background_pm = pm; clear(); } void Button::show() { m_win.show(); } void Button::hide() { m_win.hide(); } void Button::buttonPressEvent(XButtonEvent &event) { if (m_pressed_pm != 0) m_win.setBackgroundPixmap(m_pressed_pm); m_pressed = true; clear(); } void Button::buttonReleaseEvent(XButtonEvent &event) { m_pressed = false; if (m_background_pm) m_win.setBackgroundPixmap(m_background_pm); else m_win.setBackgroundColor(m_background_color); clear(); // clear background if (m_foreground_pm) { // draw foreground Display *disp = App::instance()->display(); if (m_gc == 0) // get default gc m_gc = DefaultGC(disp, m_win.screenNumber()); XCopyArea(disp, m_foreground_pm, m_win.window(), m_gc, 0, 0, width(), height(), 0, 0); } if (event.x < 0 || event.y < 0 || event.x > width() || event.y > height()) return; if (event.button > 0 && event.button <= 5 && m_onclick[event.button -1].get() != 0) m_onclick[event.button - 1]->execute(); } void Button::exposeEvent(XExposeEvent &event) { m_win.clear(); } }; // end namespace FbTk <commit_msg>using transparent<commit_after>// Button.cc for FbTk - fluxbox toolkit // Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // 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: Button.cc,v 1.9 2003/08/04 12:46:49 fluxgen Exp $ #include "Button.hh" #include "Command.hh" #include "EventManager.hh" #include "App.hh" namespace FbTk { Button::Button(int screen_num, int x, int y, unsigned int width, unsigned int height): m_win(screen_num, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_foreground_pm(0), m_background_pm(0), m_pressed_pm(0), m_gc(DefaultGC(FbTk::App::instance()->display(), screen_num)), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, m_win); } Button::Button(const FbWindow &parent, int x, int y, unsigned int width, unsigned int height): m_win(parent, x, y, width, height, ExposureMask | ButtonPressMask | ButtonReleaseMask), m_foreground_pm(0), m_background_pm(0), m_pressed_pm(0), m_gc(DefaultGC(FbTk::App::instance()->display(), m_win.screenNumber())), m_pressed(false) { // add this to eventmanager FbTk::EventManager::instance()->add(*this, m_win); } Button::~Button() { FbTk::EventManager::instance()->remove(m_win); } void Button::setOnClick(RefCount<Command> &cmd, int button) { // we only handle buttons 1 to 5 if (button > 5 || button == 0) return; //set on click command for the button m_onclick[button - 1] = cmd; } void Button::move(int x, int y) { window().move(x, y); } void Button::resize(unsigned int w, unsigned int h) { window().resize(w, h); } void Button::moveResize(int x, int y, unsigned int width, unsigned int height) { window().moveResize(x, y, width, height); } void Button::setPixmap(Pixmap pm) { m_foreground_pm = pm; } void Button::setPressedPixmap(Pixmap pm) { m_pressed_pm = pm; } void Button::setBackgroundColor(const Color &color) { m_win.setBackgroundColor(color); m_background_color = color; clear(); window().updateTransparent(); } void Button::setBackgroundPixmap(Pixmap pm) { m_win.setBackgroundPixmap(pm); m_background_pm = pm; clear(); window().updateTransparent(); } void Button::show() { m_win.show(); } void Button::hide() { m_win.hide(); } void Button::buttonPressEvent(XButtonEvent &event) { if (m_pressed_pm != 0) m_win.setBackgroundPixmap(m_pressed_pm); m_pressed = true; clear(); window().updateTransparent(); } void Button::buttonReleaseEvent(XButtonEvent &event) { m_pressed = false; if (m_background_pm) m_win.setBackgroundPixmap(m_background_pm); else m_win.setBackgroundColor(m_background_color); clear(); // clear background if (m_foreground_pm) { // draw foreground Display *disp = App::instance()->display(); if (m_gc == 0) // get default gc m_gc = DefaultGC(disp, m_win.screenNumber()); XCopyArea(disp, m_foreground_pm, m_win.window(), m_gc, 0, 0, width(), height(), 0, 0); } if (event.x < 0 || event.y < 0 || event.x > width() || event.y > height()) return; if (event.button > 0 && event.button <= 5 && m_onclick[event.button -1].get() != 0) m_onclick[event.button - 1]->execute(); window().updateTransparent(); } void Button::exposeEvent(XExposeEvent &event) { clear(); window().updateTransparent(event.x, event.y, event.width, event.height); } }; // end namespace FbTk <|endoftext|>
<commit_before>#include <cstdint> #include <cstdlib> #include <iostream> static constexpr std::uint64_t MOD = 1000000007; int main() { std::cin.tie(0); std::ios::sync_with_stdio(false); int w, h; std::cin >> w >> h; std::uint64_t *dp = new std::uint64_t[h * w]; for (int i = 0; i < h; i++) { dp[i * w] = 1; } for (int i = 0; i < w; i++) { dp[i] = 1; } for (int i = 1; i < h; i++) { for (int j = 1; j < w; j++) { dp[i * w + j] = (dp[(i - 1) * w + j] + dp[i * w + j - 1]) % MOD; } } std::cout << dp[h * w - 1] << std::endl; delete[] dp; return EXIT_SUCCESS; } <commit_msg>Fix codes to get 101 points<commit_after>#include <cstdint> #include <cstdlib> #include <iostream> #include <type_traits> static constexpr std::int64_t MOD = 1000000007; template<typename IntType, typename std::enable_if<std::is_signed<IntType>::value, std::nullptr_t>::type = nullptr> static IntType modfact(IntType n, IntType mod) { IntType p = 1; for (; n > 0; n--) { p = (p * n) % mod; } return p; } template<typename IntType, typename std::enable_if<std::is_signed<IntType>::value, std::nullptr_t>::type = nullptr> static IntType extgcd(IntType a, IntType b, IntType& x, IntType& y) { IntType v = x = 0; IntType u = y = 1; while (a != 0) { IntType q = b / a; std::swap(x -= q * u, u); std::swap(y -= q * v, v); std::swap(b -= q * a, a); } return b; } template<typename IntType, typename std::enable_if<std::is_integral<IntType>::value, std::nullptr_t>::type = nullptr> static IntType modinv(IntType a, IntType mod) { IntType x, y; extgcd(a, mod, x, y); return (mod + x % mod) % mod; } int main() { std::cin.tie(0); std::ios::sync_with_stdio(false); std::int64_t w, h; std::cin >> w >> h; w--; h--; std::cout << (modfact(w + h, MOD) * modinv(modfact(w, MOD), MOD) % MOD * modinv(modfact(h, MOD), MOD) % MOD) << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.5 2001/05/16 14:57:07 alibrary New files for folders and Stack Revision 1.4 2000/12/20 08:39:37 fca Support for Cerenkov and process list in Virtual MC Revision 1.3 1999/09/29 09:24:07 fca Introduction of the Copyright and cvs Log */ ////////////////////////////////////////////////////////////////////////// // // // aliroot // // // // Main program used to create aliroot application. // // // // // // To be able to communicate between the FORTRAN code of GEANT and the // // ROOT data structure, a number of interface routines have been // // developed. // //Begin_Html /* <img src="picts/newg.gif"> */ //End_Html ////////////////////////////////////////////////////////////////////////// //Standard Root includes #include <TROOT.h> #include <TRint.h> #include <TFile.h> #include <AliRun.h> #include <AliConfig.h> #if defined __linux //On linux Fortran wants this, so we give to it! int xargv=0; int xargc=0; #endif #if defined WIN32 extern "C" int __fastflag=0; extern "C" int _pctype=0; extern "C" int __mb_cur_max=0; #endif int gcbank_[3000000]; //Initialise the Root environment extern void InitGui(); VoidFuncPtr_t initfuncs[] = { InitGui, 0 }; TROOT root("galice","The Alice/ROOT Interface", initfuncs); //_____________________________________________________________________________ int main(int argc, char **argv) { // // gAlice main program. // It creates the main Geant3 and AliRun objects. // // The Hits are written out after each track in a ROOT Tree structure TreeH, // of the file galice.root. There is one such tree per event. The kinematics // of all the particles that produce hits, together with their genealogy up // to the primary tracks is stared in the galice.root file in an other tree // TreeK of which exists one per event. Finally the information of the events // in the run is stored in the same file in the tree TreeE, containing the // run and event number, the number of vertices, tracks and primary tracks // in the event. // Create new configuration new AliConfig (); new AliRun("gAlice","The ALICE Off-line Simulation Framework"); // Start interactive geant TRint *theApp = new TRint("aliroot", &argc, argv, 0, 0); // --- Start the event loop --- theApp->Run(); return(0); } <commit_msg>Restored proper name for top level AliRoot folder.<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.6 2001/05/21 17:22:50 buncic Fixed problem with missing AliConfig while reading galice.root Revision 1.5 2001/05/16 14:57:07 alibrary New files for folders and Stack Revision 1.4 2000/12/20 08:39:37 fca Support for Cerenkov and process list in Virtual MC Revision 1.3 1999/09/29 09:24:07 fca Introduction of the Copyright and cvs Log */ ////////////////////////////////////////////////////////////////////////// // // // aliroot // // // // Main program used to create aliroot application. // // // // // // To be able to communicate between the FORTRAN code of GEANT and the // // ROOT data structure, a number of interface routines have been // // developed. // //Begin_Html /* <img src="picts/newg.gif"> */ //End_Html ////////////////////////////////////////////////////////////////////////// //Standard Root includes #include <TROOT.h> #include <TRint.h> #include <TFile.h> #include <AliRun.h> #include <AliConfig.h> #if defined __linux //On linux Fortran wants this, so we give to it! int xargv=0; int xargc=0; #endif #if defined WIN32 extern "C" int __fastflag=0; extern "C" int _pctype=0; extern "C" int __mb_cur_max=0; #endif int gcbank_[3000000]; //Initialise the Root environment extern void InitGui(); VoidFuncPtr_t initfuncs[] = { InitGui, 0 }; TROOT root("galice","The Alice/ROOT Interface", initfuncs); //_____________________________________________________________________________ int main(int argc, char **argv) { // // gAlice main program. // It creates the main Geant3 and AliRun objects. // // The Hits are written out after each track in a ROOT Tree structure TreeH, // of the file galice.root. There is one such tree per event. The kinematics // of all the particles that produce hits, together with their genealogy up // to the primary tracks is stared in the galice.root file in an other tree // TreeK of which exists one per event. Finally the information of the events // in the run is stored in the same file in the tree TreeE, containing the // run and event number, the number of vertices, tracks and primary tracks // in the event. // Create new configuration new AliConfig ("Folders","Alice data exchange"); new AliRun("gAlice","The ALICE Off-line Simulation Framework"); // Start interactive geant TRint *theApp = new TRint("aliroot", &argc, argv, 0, 0); // --- Start the event loop --- theApp->Run(); return(0); } <|endoftext|>
<commit_before>#include <string.h> #include <util/atomic.h> #include "GNSS_Clock.h" #include <MicroNMEA.h> GNSS_Clock gnss_clock; void GNSS_Clock::isr(void) { gnss_clock.ppsHandler(); } bool GNSS_Clock::begin(void* buffer, uint8_t len, uint8_t ppsPin, uint8_t edge) { _nmea.setBuffer(buffer, len); pinMode(ppsPin, INPUT); attachInterrupt(digitalPinToInterrupt(ppsPin), isr, edge); return true; } bool GNSS_Clock::isValid(void) const volatile { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { return _isValid; } } bool GNSS_Clock::readClock(RTCx::time_t *t) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { if (t != NULL) *t = _secondsSinceEpoch; r = true; } } return r; } bool GNSS_Clock::readClock(RTCx::time_t& t, long& latitude, long& longitude, long& altitude, bool& altitudeValid, char& navSystem, uint8_t& numSat, uint8_t& hdop) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { t = _secondsSinceEpoch; latitude = _latitude; longitude = _longitude; altitudeValid = _altitudeValid; if (_altitudeValid) altitude = _altitude; navSystem = _navSystem; numSat = _numSat; hdop = _hdop; r = true; } } return r; } bool GNSS_Clock::readClock(struct RTCx::tm *tm) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { RTCx::gmtime_r((const RTCx::time_t*)&_secondsSinceEpoch, tm); r = true; } } return r; } void GNSS_Clock::clear(void) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { _isValid = false; _navSystem = '\0'; _numSat = 0; _hdop = 255; _latitude = 999000000L; _longitude = 999000000L; _altitude = _speed = _course = LONG_MIN; _altitudeValid = false; // _tm.tm_year = _tm.tm_mon = _tm.tm_mday = 0; // _tm.tm_yday = -1; // _tm.tm_hour = _tm.tm_min = _tm.tm_sec = 99; } } void GNSS_Clock::ppsHandler(void) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_nmea.isValid()) { struct RTCx::tm tm; tm.tm_year = _nmea.getYear() - 1900; tm.tm_mon = _nmea.getMonth() - 1; tm.tm_mday = _nmea.getDay(); tm.tm_hour = _nmea.getHour(); tm.tm_min = _nmea.getMinute(); tm.tm_sec = _nmea.getSecond(); tm.tm_yday = -1; _secondsSinceEpoch = RTCx::mktime(tm); if (_secondsSinceEpoch == -1) _isValid = false; else { // Increment to get current time. NB this doesn't take into // account any leap seconds which may be added. ++_secondsSinceEpoch; _isValid = true; } _navSystem = _nmea.getNavSystem(); _numSat = _nmea.getNumSatellites(); _hdop = _nmea.getHDOP(); _latitude = _nmea.getLatitude(); _longitude = _nmea.getLongitude(); long tmp = LONG_MIN; _altitudeValid = _nmea.getAltitude(tmp); if (_altitudeValid) _altitude = tmp; } else { clear(); } _nmea.clear(); if (_1ppsCallback) (*_1ppsCallback)(*this); } } <commit_msg>Read time from NMEA even when no valid fix<commit_after>#include <string.h> #include <util/atomic.h> #include "GNSS_Clock.h" #include <MicroNMEA.h> GNSS_Clock gnss_clock; void GNSS_Clock::isr(void) { gnss_clock.ppsHandler(); } bool GNSS_Clock::begin(void* buffer, uint8_t len, uint8_t ppsPin, uint8_t edge) { _nmea.setBuffer(buffer, len); pinMode(ppsPin, INPUT); attachInterrupt(digitalPinToInterrupt(ppsPin), isr, edge); return true; } bool GNSS_Clock::isValid(void) const volatile { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { return _isValid; } } bool GNSS_Clock::readClock(RTCx::time_t *t) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { if (t != NULL) *t = _secondsSinceEpoch; r = true; } } return r; } bool GNSS_Clock::readClock(RTCx::time_t& t, long& latitude, long& longitude, long& altitude, bool& altitudeValid, char& navSystem, uint8_t& numSat, uint8_t& hdop) const { bool r; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { t = _secondsSinceEpoch; r = _isValid; if (_isValid) { latitude = _latitude; longitude = _longitude; altitudeValid = _altitudeValid; if (_altitudeValid) altitude = _altitude; navSystem = _navSystem; numSat = _numSat; hdop = _hdop; } } return r; } bool GNSS_Clock::readClock(struct RTCx::tm *tm) const { bool r; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { RTCx::gmtime_r((const RTCx::time_t*)&_secondsSinceEpoch, tm); r = _isValid; } return r; } void GNSS_Clock::clear(void) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { _isValid = false; _navSystem = '\0'; _numSat = 0; _hdop = 255; _latitude = 999000000L; _longitude = 999000000L; _altitude = _speed = _course = LONG_MIN; _altitudeValid = false; // _tm.tm_year = _tm.tm_mon = _tm.tm_mday = 0; // _tm.tm_yday = -1; // _tm.tm_hour = _tm.tm_min = _tm.tm_sec = 99; } } void GNSS_Clock::ppsHandler(void) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { // Try to obtain the time of fix, even if the time/position is not valid struct RTCx::tm tm; tm.tm_year = _nmea.getYear() - 1900; tm.tm_mon = _nmea.getMonth() - 1; tm.tm_mday = _nmea.getDay(); tm.tm_hour = _nmea.getHour(); tm.tm_min = _nmea.getMinute(); tm.tm_sec = _nmea.getSecond(); tm.tm_yday = -1; _secondsSinceEpoch = RTCx::mktime(tm); if (_nmea.isValid()) { if (_secondsSinceEpoch == -1) _isValid = false; else { // Increment to get current time. NB this doesn't take into // account any leap seconds which may be added. ++_secondsSinceEpoch; _isValid = true; } _navSystem = _nmea.getNavSystem(); _numSat = _nmea.getNumSatellites(); _hdop = _nmea.getHDOP(); _latitude = _nmea.getLatitude(); _longitude = _nmea.getLongitude(); long tmp = LONG_MIN; _altitudeValid = _nmea.getAltitude(tmp); if (_altitudeValid) _altitude = tmp; } else { clear(); } _nmea.clear(); if (_1ppsCallback) (*_1ppsCallback)(*this); } } <|endoftext|>
<commit_before>//Copyright (c) 2019 Ultimaker B.V. #include "BeadingOrderOptimizer.h" #include <iterator> #include <unordered_map> #include <vector> #include <list> namespace arachne { void BeadingOrderOptimizer::optimize(const std::vector<ExtrusionSegment>& segments, std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polylines_per_index) { BeadingOrderOptimizer optimizer(segments); optimizer.connect(result_polygons_per_index); optimizer.reduceIntersectionOverlap(result_polygons_per_index); optimizer.transferUnconnectedPolylines(result_polygons_per_index, result_polylines_per_index); } void BeadingOrderOptimizer::connect(std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polygons_per_index) { debugCheck(); for (const ExtrusionSegment& segment : segments) { if (segment.from.p == segment.to.p) { assert(segment.from.w == segment.to.w); continue; } assert(segment.from.perimeter_index == segment.to.perimeter_index); coord_t inset_idx = segment.from.perimeter_index; std::list<Polyline>& polylines = segment.is_odd? odd_polylines : even_polylines; std::unordered_map<Point, PolylineEndRef>& polyline_end_points = segment.is_odd? odd_polyline_end_points : even_polyline_end_points; auto start_it = polyline_end_points.find(segment.from.p); auto end_it = polyline_end_points.find(segment.to.p); bool connect_start = start_it != polyline_end_points.end(); bool connect_end = end_it != polyline_end_points.end(); debugCheck(); if (!connect_start && !connect_end) { polylines.emplace_back(inset_idx); std::list<ExtrusionJunction>& junctions = polylines.back().junctions; junctions.emplace_front(segment.from); junctions.emplace_back(segment.to); polyline_end_points.emplace(segment.from.p, PolylineEndRef(inset_idx, --polylines.end(), true)); polyline_end_points.emplace(segment.to.p, PolylineEndRef(inset_idx, --polylines.end(), false)); } else if (connect_start && !connect_end) { PolylineEndRef ref = start_it->second; if (ref.front) { ref.polyline->junctions.emplace_front(segment.to); } else { ref.polyline->junctions.emplace_back(segment.to); } polyline_end_points.erase(start_it); polyline_end_points.emplace(segment.to.p, ref); } else if (!connect_start && connect_end) { PolylineEndRef ref = end_it->second; if (ref.front) { ref.polyline->junctions.emplace_front(segment.from); } else { ref.polyline->junctions.emplace_back(segment.from); } polyline_end_points.erase(end_it); polyline_end_points.emplace(segment.from.p, ref); } else // if (connect_start && connect_end) { PolylineEndRef start_ref = start_it->second; PolylineEndRef end_ref = end_it->second; std::list<ExtrusionJunction>& result_junctions = start_ref.polyline->junctions; assert(start_it != end_it); polyline_end_points.erase(start_it); polyline_end_points.erase(end_it); if (&*start_ref.polyline != &*end_ref.polyline) { polyline_end_points.erase((start_ref.front)? start_ref.polyline->junctions.back().p : start_ref.polyline->junctions.front().p); polyline_end_points.erase((end_ref.front)? end_ref.polyline->junctions.back().p : end_ref.polyline->junctions.front().p); std::list<ExtrusionJunction>::iterator insert_position = start_ref.front? result_junctions.begin() : result_junctions.end(); if (end_ref.front == start_ref.front) { result_junctions.insert(insert_position, end_ref.polyline->junctions.rbegin(), end_ref.polyline->junctions.rend()); } else { result_junctions.insert(insert_position, end_ref.polyline->junctions.begin(), end_ref.polyline->junctions.end()); } polyline_end_points.emplace(result_junctions.front().p, PolylineEndRef(start_ref.inset_idx, start_ref.polyline, true)); polyline_end_points.emplace(result_junctions.back().p, PolylineEndRef(start_ref.inset_idx, start_ref.polyline, false)); polylines.erase(end_ref.polyline); } else // if start_ref.polyline == end_ref.polyline { polyline_end_points.erase((start_ref.front)? start_ref.polyline->junctions.back().p : start_ref.polyline->junctions.front().p); polyline_end_points.erase((end_ref.front)? end_ref.polyline->junctions.back().p : end_ref.polyline->junctions.front().p); // close polygon and add it to the results result_polygons_per_index.resize(std::max(result_polygons_per_index.size(), static_cast<size_t>(start_ref.inset_idx + 1))); result_polygons_per_index[start_ref.inset_idx].emplace_back(result_junctions.begin(), result_junctions.end()); polylines.erase(start_ref.polyline); } } } debugCheck(); } void BeadingOrderOptimizer::reduceIntersectionOverlap(std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index) { for (Polyline& polyline : odd_polylines) { reduceIntersectionOverlap(polyline, polyline.junctions.begin(), polyline.inset_idx, polygons_per_index); reduceIntersectionOverlap(polyline, polyline.junctions.rbegin(), polyline.inset_idx, polygons_per_index); } } template<typename directional_iterator> void BeadingOrderOptimizer::reduceIntersectionOverlap(Polyline& polyline, directional_iterator polyline_start_it, coord_t inset_idx, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index) { ExtrusionJunction& start_junction = *polyline_start_it; ExtrusionJunction* intersecting_junction = nullptr; if (inset_idx < polygons_per_index.size()) { for (std::vector<ExtrusionJunction>& polygon : polygons_per_index[inset_idx]) { for (ExtrusionJunction& junction : polygon) { if (junction.p == start_junction.p) { assert(junction.w == start_junction.w); intersecting_junction = &junction; break; } } if (intersecting_junction) break; } } if (!intersecting_junction) { for (Polyline& other_polyline : odd_polylines) { if (other_polyline.inset_idx != polyline.inset_idx) continue; for (auto junction_it = ++other_polyline.junctions.begin(); junction_it != --other_polyline.junctions.end() && junction_it != other_polyline.junctions.end(); junction_it++) { // skip end points, because they would have been connected to this point! if (junction_it->p == start_junction.p) { intersecting_junction = &*junction_it; break; } } if (intersecting_junction) break; } } if (!intersecting_junction) return; reduceIntersectionOverlap(polyline, polyline_start_it, 0, intersecting_junction->w / 2 * (1.0 - intersection_overlap)); } template<typename directional_iterator> void BeadingOrderOptimizer::reduceIntersectionOverlap(Polyline& polyline, directional_iterator polyline_it, coord_t traveled_dist, coord_t reduction_length) { ExtrusionJunction& start_junction = *polyline_it; polyline_it++; if (isEnd(polyline_it, polyline)) { return; } ExtrusionJunction& next_junction = *polyline_it; Point a = start_junction.p; Point b = next_junction.p; Point ab = b - a; coord_t length = vSize(ab); coord_t total_reduction_length = reduction_length + start_junction.w / 2; if (traveled_dist + length > total_reduction_length) { Point mid1 = a + ab * std::max(static_cast<coord_t>(0), std::min(length, (total_reduction_length - traveled_dist) / length)); // Point mid2 = mid1; // a + ab * std::min(reduction_length + 10, length) / length; std::list<ExtrusionJunction>::iterator forward_it = getInsertPosIt( polyline_it ); coord_t mid_w = start_junction.w + (next_junction.w - start_junction.w) * reduction_length / length; polyline.junctions.insert(forward_it, ExtrusionJunction(mid1, mid_w, start_junction.perimeter_index)); // polyline.junctions.insert(forward_it, ExtrusionJunction(mid1, 0, start_junction.perimeter_index)); } else { // NOTE: polyline_start_it was already increased reduceIntersectionOverlap(polyline, polyline_it, traveled_dist + length, reduction_length); } if (polyline.junctions.size() > 1) { polyline.junctions.erase(getSelfPosIt(--polyline_it)); } if (polyline.junctions.size() == 1) { polyline.junctions.emplace_back(polyline.junctions.front()); polyline.junctions.back().p += Point(1,1); } } template<> bool BeadingOrderOptimizer::isEnd(std::list<ExtrusionJunction>::iterator it, Polyline& polyline) { return it == polyline.junctions.end(); } template<> bool BeadingOrderOptimizer::isEnd(std::list<ExtrusionJunction>::reverse_iterator it, Polyline& polyline) { return it == polyline.junctions.rend(); } template<> std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getInsertPosIt(std::list<ExtrusionJunction>::iterator it) { return it; } template<> std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getInsertPosIt(std::list<ExtrusionJunction>::reverse_iterator it) { return it.base(); } template<> std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getSelfPosIt(std::list<ExtrusionJunction>::iterator it) { return it; } template<> std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getSelfPosIt(std::list<ExtrusionJunction>::reverse_iterator it) { return (++it).base(); } void BeadingOrderOptimizer::transferUnconnectedPolylines(std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polylines_per_index) { // copy unfinished polylines to result result_polylines_per_index.resize(std::max(result_polylines_per_index.size(), even_polylines.size() + odd_polylines.size())); for (auto polylines : { even_polylines, odd_polylines }) { for (Polyline& polyline : polylines) { result_polylines_per_index[polyline.inset_idx].emplace_back(polyline.junctions.begin(), polyline.junctions.end()); } } } void BeadingOrderOptimizer::debugCheck() { #ifdef DEBUG for (auto polylines : { even_polylines, odd_polylines }) { for (Polyline& polyline : polylines) { for (ExtrusionJunction& junction : polyline.junctions) { assert(junction.perimeter_index == polyline.inset_idx); assert(junction.p.X < 100000 && junction.p.Y < 100000); assert(junction.p.X > -100000 && junction.p.Y > -100000); } } } for (auto polyline_end_points : { even_polyline_end_points, odd_polyline_end_points }) { for (auto pair : polyline_end_points) { PolylineEndRef ref = pair.second; Point p = pair.first; assert(p == ((ref.front)? ref.polyline->junctions.front().p : ref.polyline->junctions.back().p)); auto find_it = even_polylines.begin(); for (; find_it != even_polylines.end(); ++find_it) { if (find_it == ref.polyline) break; } if (find_it == even_polylines.end()) { for (find_it = odd_polylines.begin(); find_it != odd_polylines.end(); ++find_it) { if (find_it == ref.polyline) break; } } assert(find_it != odd_polylines.end()); } } #endif }; } // namespace arachne <commit_msg>fix mem access bug of invalid iterator<commit_after>//Copyright (c) 2019 Ultimaker B.V. #include "BeadingOrderOptimizer.h" #include <iterator> #include <unordered_map> #include <vector> #include <list> namespace arachne { void BeadingOrderOptimizer::optimize(const std::vector<ExtrusionSegment>& segments, std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polylines_per_index) { BeadingOrderOptimizer optimizer(segments); optimizer.connect(result_polygons_per_index); optimizer.reduceIntersectionOverlap(result_polygons_per_index); optimizer.transferUnconnectedPolylines(result_polygons_per_index, result_polylines_per_index); } void BeadingOrderOptimizer::connect(std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polygons_per_index) { debugCheck(); for (const ExtrusionSegment& segment : segments) { if (segment.from.p == segment.to.p) { assert(segment.from.w == segment.to.w); continue; } assert(segment.from.perimeter_index == segment.to.perimeter_index); coord_t inset_idx = segment.from.perimeter_index; std::list<Polyline>& polylines = segment.is_odd? odd_polylines : even_polylines; std::unordered_map<Point, PolylineEndRef>& polyline_end_points = segment.is_odd? odd_polyline_end_points : even_polyline_end_points; auto start_it = polyline_end_points.find(segment.from.p); auto end_it = polyline_end_points.find(segment.to.p); bool connect_start = start_it != polyline_end_points.end(); bool connect_end = end_it != polyline_end_points.end(); debugCheck(); if (!connect_start && !connect_end) { polylines.emplace_back(inset_idx); std::list<ExtrusionJunction>& junctions = polylines.back().junctions; junctions.emplace_front(segment.from); junctions.emplace_back(segment.to); polyline_end_points.emplace(segment.from.p, PolylineEndRef(inset_idx, --polylines.end(), true)); polyline_end_points.emplace(segment.to.p, PolylineEndRef(inset_idx, --polylines.end(), false)); } else if (connect_start && !connect_end) { PolylineEndRef ref = start_it->second; if (ref.front) { ref.polyline->junctions.emplace_front(segment.to); } else { ref.polyline->junctions.emplace_back(segment.to); } polyline_end_points.erase(start_it); polyline_end_points.emplace(segment.to.p, ref); } else if (!connect_start && connect_end) { PolylineEndRef ref = end_it->second; if (ref.front) { ref.polyline->junctions.emplace_front(segment.from); } else { ref.polyline->junctions.emplace_back(segment.from); } polyline_end_points.erase(end_it); polyline_end_points.emplace(segment.from.p, ref); } else // if (connect_start && connect_end) { PolylineEndRef start_ref = start_it->second; PolylineEndRef end_ref = end_it->second; std::list<ExtrusionJunction>& result_junctions = start_ref.polyline->junctions; assert(start_it != end_it); polyline_end_points.erase(start_it); polyline_end_points.erase(end_it); if (&*start_ref.polyline != &*end_ref.polyline) { polyline_end_points.erase((start_ref.front)? start_ref.polyline->junctions.back().p : start_ref.polyline->junctions.front().p); polyline_end_points.erase((end_ref.front)? end_ref.polyline->junctions.back().p : end_ref.polyline->junctions.front().p); std::list<ExtrusionJunction>::iterator insert_position = start_ref.front? result_junctions.begin() : result_junctions.end(); if (end_ref.front == start_ref.front) { result_junctions.insert(insert_position, end_ref.polyline->junctions.rbegin(), end_ref.polyline->junctions.rend()); } else { result_junctions.insert(insert_position, end_ref.polyline->junctions.begin(), end_ref.polyline->junctions.end()); } polyline_end_points.emplace(result_junctions.front().p, PolylineEndRef(start_ref.inset_idx, start_ref.polyline, true)); polyline_end_points.emplace(result_junctions.back().p, PolylineEndRef(start_ref.inset_idx, start_ref.polyline, false)); polylines.erase(end_ref.polyline); } else // if start_ref.polyline == end_ref.polyline { polyline_end_points.erase((start_ref.front)? start_ref.polyline->junctions.back().p : start_ref.polyline->junctions.front().p); polyline_end_points.erase((end_ref.front)? end_ref.polyline->junctions.back().p : end_ref.polyline->junctions.front().p); // close polygon and add it to the results result_polygons_per_index.resize(std::max(result_polygons_per_index.size(), static_cast<size_t>(start_ref.inset_idx + 1))); result_polygons_per_index[start_ref.inset_idx].emplace_back(result_junctions.begin(), result_junctions.end()); polylines.erase(start_ref.polyline); } } } debugCheck(); } void BeadingOrderOptimizer::reduceIntersectionOverlap(std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index) { for (Polyline& polyline : odd_polylines) { reduceIntersectionOverlap(polyline, polyline.junctions.begin(), polyline.inset_idx, polygons_per_index); reduceIntersectionOverlap(polyline, polyline.junctions.rbegin(), polyline.inset_idx, polygons_per_index); } } template<typename directional_iterator> void BeadingOrderOptimizer::reduceIntersectionOverlap(Polyline& polyline, directional_iterator polyline_start_it, coord_t inset_idx, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index) { ExtrusionJunction& start_junction = *polyline_start_it; ExtrusionJunction* intersecting_junction = nullptr; if (inset_idx < polygons_per_index.size()) { for (std::vector<ExtrusionJunction>& polygon : polygons_per_index[inset_idx]) { for (ExtrusionJunction& junction : polygon) { if (junction.p == start_junction.p) { assert(junction.w == start_junction.w); intersecting_junction = &junction; break; } } if (intersecting_junction) break; } } if (!intersecting_junction) { for (Polyline& other_polyline : odd_polylines) { if (other_polyline.inset_idx != polyline.inset_idx) continue; for (auto junction_it = ++other_polyline.junctions.begin(); junction_it != --other_polyline.junctions.end() && junction_it != other_polyline.junctions.end(); junction_it++) { // skip end points, because they would have been connected to this point! if (junction_it->p == start_junction.p) { intersecting_junction = &*junction_it; break; } } if (intersecting_junction) break; } } if (!intersecting_junction) return; reduceIntersectionOverlap(polyline, polyline_start_it, 0, intersecting_junction->w / 2 * (1.0 - intersection_overlap)); } template<typename directional_iterator> void BeadingOrderOptimizer::reduceIntersectionOverlap(Polyline& polyline, directional_iterator polyline_it, coord_t traveled_dist, coord_t reduction_length) { ExtrusionJunction& start_junction = *polyline_it; directional_iterator next_junction_it = polyline_it; next_junction_it++; if (isEnd(next_junction_it, polyline)) { return; } ExtrusionJunction& next_junction = *next_junction_it; Point a = start_junction.p; Point b = next_junction.p; Point ab = b - a; coord_t length = vSize(ab); coord_t total_reduction_length = reduction_length + start_junction.w / 2; if (traveled_dist + length > total_reduction_length) { Point mid1 = a + ab * std::max(static_cast<coord_t>(0), std::min(length, (total_reduction_length - traveled_dist) / length)); // Point mid2 = mid1; // a + ab * std::min(reduction_length + 10, length) / length; std::list<ExtrusionJunction>::iterator forward_it = getInsertPosIt(next_junction_it); coord_t mid_w = start_junction.w + (next_junction.w - start_junction.w) * reduction_length / length; polyline.junctions.insert(forward_it, ExtrusionJunction(mid1, mid_w, start_junction.perimeter_index)); // polyline.junctions.insert(forward_it, ExtrusionJunction(mid1, 0, start_junction.perimeter_index)); } else { // NOTE: polyline_start_it was already increased reduceIntersectionOverlap(polyline, next_junction_it, traveled_dist + length, reduction_length); } if (polyline.junctions.size() > 1) { polyline.junctions.erase(getSelfPosIt(polyline_it)); } if (polyline.junctions.size() == 1) { polyline.junctions.emplace_back(polyline.junctions.front()); polyline.junctions.back().p += Point(1,1); } } template<> bool BeadingOrderOptimizer::isEnd(std::list<ExtrusionJunction>::iterator it, Polyline& polyline) { return it == polyline.junctions.end(); } template<> bool BeadingOrderOptimizer::isEnd(std::list<ExtrusionJunction>::reverse_iterator it, Polyline& polyline) { return it == polyline.junctions.rend(); } template<> std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getInsertPosIt(std::list<ExtrusionJunction>::iterator it) { return it; } template<> std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getInsertPosIt(std::list<ExtrusionJunction>::reverse_iterator it) { return it.base(); } template<> std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getSelfPosIt(std::list<ExtrusionJunction>::iterator it) { return it; } template<> std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getSelfPosIt(std::list<ExtrusionJunction>::reverse_iterator it) { return (++it).base(); } void BeadingOrderOptimizer::transferUnconnectedPolylines(std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& result_polylines_per_index) { // copy unfinished polylines to result result_polylines_per_index.resize(std::max(result_polylines_per_index.size(), even_polylines.size() + odd_polylines.size())); for (auto polylines : { even_polylines, odd_polylines }) { for (Polyline& polyline : polylines) { result_polylines_per_index[polyline.inset_idx].emplace_back(polyline.junctions.begin(), polyline.junctions.end()); } } } void BeadingOrderOptimizer::debugCheck() { #ifdef DEBUG for (auto polylines : { even_polylines, odd_polylines }) { for (Polyline& polyline : polylines) { for (ExtrusionJunction& junction : polyline.junctions) { assert(junction.perimeter_index == polyline.inset_idx); assert(junction.p.X < 100000 && junction.p.Y < 100000); assert(junction.p.X > -100000 && junction.p.Y > -100000); } } } for (auto polyline_end_points : { even_polyline_end_points, odd_polyline_end_points }) { for (auto pair : polyline_end_points) { PolylineEndRef ref = pair.second; Point p = pair.first; assert(p == ((ref.front)? ref.polyline->junctions.front().p : ref.polyline->junctions.back().p)); auto find_it = even_polylines.begin(); for (; find_it != even_polylines.end(); ++find_it) { if (find_it == ref.polyline) break; } if (find_it == even_polylines.end()) { for (find_it = odd_polylines.begin(); find_it != odd_polylines.end(); ++find_it) { if (find_it == ref.polyline) break; } } assert(find_it != odd_polylines.end()); } } #endif }; } // namespace arachne <|endoftext|>
<commit_before>#include <Nazara/Utility.hpp> #include <Nazara/Renderer.hpp> #include <Nazara/Shader.hpp> #include <Nazara/Shader/SpirvConstantCache.hpp> #include <Nazara/Shader/SpirvPrinter.hpp> #include <array> #include <iostream> int main() { Nz::Modules<Nz::Renderer> nazara; Nz::RenderWindow window; Nz::MeshParams meshParams; meshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 90.f, 180.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f)); meshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ_Normal_UV); Nz::String windowTitle = "Vulkan Test"; if (!window.Create(Nz::VideoMode(800, 600, 32), windowTitle)) { std::cout << "Failed to create Window" << std::endl; return __LINE__; } std::shared_ptr<Nz::RenderDevice> device = window.GetRenderDevice(); auto fragmentShader = device->InstantiateShaderStage(Nz::ShaderStageType::Fragment, Nz::ShaderLanguage::NazaraBinary, "frag.shader"); if (!fragmentShader) { std::cout << "Failed to instantiate fragment shader" << std::endl; return __LINE__; } auto vertexShader = device->InstantiateShaderStage(Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraBinary, "vert.shader"); if (!vertexShader) { std::cout << "Failed to instantiate fragment shader" << std::endl; return __LINE__; } Nz::MeshRef drfreak = Nz::Mesh::LoadFromFile("resources/Spaceship/spaceship.obj", meshParams); if (!drfreak) { NazaraError("Failed to load model"); return __LINE__; } Nz::StaticMesh* drfreakMesh = static_cast<Nz::StaticMesh*>(drfreak->GetSubMesh(0)); const Nz::VertexBuffer* drfreakVB = drfreakMesh->GetVertexBuffer(); const Nz::IndexBuffer* drfreakIB = drfreakMesh->GetIndexBuffer(); // Index buffer std::cout << "Index count: " << drfreakIB->GetIndexCount() << std::endl; // Vertex buffer std::cout << "Vertex count: " << drfreakVB->GetVertexCount() << std::endl; // Texture Nz::ImageRef drfreakImage = Nz::Image::LoadFromFile("resources/Spaceship/Texture/diffuse.png"); if (!drfreakImage || !drfreakImage->Convert(Nz::PixelFormat_RGBA8)) { NazaraError("Failed to load image"); return __LINE__; } Nz::TextureInfo texParams; texParams.pixelFormat = drfreakImage->GetFormat(); texParams.type = drfreakImage->GetType(); texParams.width = drfreakImage->GetWidth(); texParams.height = drfreakImage->GetHeight(); texParams.depth = drfreakImage->GetDepth(); std::unique_ptr<Nz::Texture> texture = device->InstantiateTexture(texParams); if (!texture->Update(drfreakImage->GetConstPixels())) { NazaraError("Failed to update texture"); return __LINE__; } std::unique_ptr<Nz::TextureSampler> textureSampler = device->InstantiateTextureSampler({}); struct { Nz::Matrix4f projectionMatrix; Nz::Matrix4f modelMatrix; Nz::Matrix4f viewMatrix; } ubo; Nz::Vector2ui windowSize = window.GetSize(); ubo.projectionMatrix = Nz::Matrix4f::Perspective(70.f, float(windowSize.x) / windowSize.y, 0.1f, 1000.f); ubo.viewMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Backward() * 1); ubo.modelMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Forward() * 2 + Nz::Vector3f::Right()); Nz::UInt32 uniformSize = sizeof(ubo); Nz::RenderPipelineLayoutInfo pipelineLayoutInfo; auto& uboBinding = pipelineLayoutInfo.bindings.emplace_back(); uboBinding.index = 0; uboBinding.shaderStageFlags = Nz::ShaderStageType::Vertex; uboBinding.type = Nz::ShaderBindingType::UniformBuffer; auto& textureBinding = pipelineLayoutInfo.bindings.emplace_back(); textureBinding.index = 1; textureBinding.shaderStageFlags = Nz::ShaderStageType::Fragment; textureBinding.type = Nz::ShaderBindingType::Texture; std::shared_ptr<Nz::RenderPipelineLayout> renderPipelineLayout = device->InstantiateRenderPipelineLayout(std::move(pipelineLayoutInfo)); Nz::ShaderBindingPtr shaderBinding = renderPipelineLayout->AllocateShaderBinding(); std::unique_ptr<Nz::AbstractBuffer> uniformBuffer = device->InstantiateBuffer(Nz::BufferType_Uniform); if (!uniformBuffer->Initialize(uniformSize, Nz::BufferUsage_DeviceLocal | Nz::BufferUsage_Dynamic)) { NazaraError("Failed to create uniform buffer"); return __LINE__; } shaderBinding->Update({ { 0, Nz::ShaderBinding::UniformBufferBinding { uniformBuffer.get(), 0, uniformSize } }, { 1, Nz::ShaderBinding::TextureBinding { texture.get(), textureSampler.get() } } }); Nz::RenderPipelineInfo pipelineInfo; pipelineInfo.pipelineLayout = renderPipelineLayout; pipelineInfo.depthBuffer = true; pipelineInfo.shaderStages.emplace_back(fragmentShader); pipelineInfo.shaderStages.emplace_back(vertexShader); auto& vertexBuffer = pipelineInfo.vertexBuffers.emplace_back(); vertexBuffer.binding = 0; vertexBuffer.declaration = drfreakVB->GetVertexDeclaration(); std::unique_ptr<Nz::RenderPipeline> pipeline = device->InstantiateRenderPipeline(pipelineInfo); Nz::RenderDevice* renderDevice = window.GetRenderDevice().get(); Nz::RenderWindowImpl* windowImpl = window.GetImpl(); std::unique_ptr<Nz::CommandPool> commandPool = windowImpl->CreateCommandPool(Nz::QueueType::Graphics); Nz::RenderBuffer* renderBufferIB = static_cast<Nz::RenderBuffer*>(drfreakIB->GetBuffer()->GetImpl()); Nz::RenderBuffer* renderBufferVB = static_cast<Nz::RenderBuffer*>(drfreakVB->GetBuffer()->GetImpl()); if (!renderBufferIB->Synchronize(renderDevice)) { NazaraError("Failed to synchronize render buffer"); return __LINE__; } if (!renderBufferVB->Synchronize(renderDevice)) { NazaraError("Failed to synchronize render buffer"); return __LINE__; } Nz::AbstractBuffer* indexBufferImpl = renderBufferIB->GetHardwareBuffer(renderDevice); Nz::AbstractBuffer* vertexBufferImpl = renderBufferVB->GetHardwareBuffer(renderDevice); Nz::CommandBufferPtr drawCommandBuffer; auto RebuildCommandBuffer = [&] { Nz::Vector2ui windowSize = window.GetSize(); drawCommandBuffer = commandPool->BuildCommandBuffer([&](Nz::CommandBufferBuilder& builder) { Nz::Recti renderRect(0, 0, window.GetSize().x, window.GetSize().y); Nz::CommandBufferBuilder::ClearValues clearValues[2]; clearValues[0].color = Nz::Color::Black; clearValues[1].depth = 1.f; clearValues[1].stencil = 0; builder.BeginDebugRegion("Main window rendering", Nz::Color::Green); { builder.BeginRenderPass(windowImpl->GetFramebuffer(), windowImpl->GetRenderPass(), renderRect, { clearValues[0], clearValues[1] }); { builder.BindIndexBuffer(indexBufferImpl); builder.BindPipeline(*pipeline); builder.BindVertexBuffer(0, vertexBufferImpl); builder.BindShaderBinding(*shaderBinding); builder.SetScissor(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); builder.SetViewport(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); builder.DrawIndexed(drfreakIB->GetIndexCount()); } builder.EndRenderPass(); } builder.EndDebugRegion(); }); }; RebuildCommandBuffer(); Nz::Vector3f viewerPos = Nz::Vector3f::Zero(); Nz::EulerAnglesf camAngles(0.f, 0.f, 0.f); Nz::Quaternionf camQuat(camAngles); window.EnableEventPolling(true); Nz::Clock updateClock; Nz::Clock secondClock; unsigned int fps = 0; bool uboUpdate = true; //Nz::Mouse::SetRelativeMouseMode(true); while (window.IsOpen()) { Nz::WindowEvent event; while (window.PollEvent(&event)) { switch (event.type) { case Nz::WindowEventType_Quit: window.Close(); break; /*case Nz::WindowEventType_MouseMoved: // La souris a bougé { // Gestion de la caméra free-fly (Rotation) float sensitivity = 0.3f; // Sensibilité de la souris // On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris camAngles.yaw = Nz::NormalizeAngle(camAngles.yaw - event.mouseMove.deltaX*sensitivity); // Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles camAngles.pitch = Nz::Clamp(camAngles.pitch + event.mouseMove.deltaY*sensitivity, -89.f, 89.f); camQuat = camAngles; uboUpdate = true; break; }*/ case Nz::WindowEventType_Resized: { Nz::Vector2ui windowSize = window.GetSize(); ubo.projectionMatrix = Nz::Matrix4f::Perspective(70.f, float(windowSize.x) / windowSize.y, 0.1f, 1000.f); uboUpdate = true; break; } default: break; } } if (updateClock.GetMilliseconds() > 1000 / 60) { float cameraSpeed = 2.f * updateClock.GetSeconds(); updateClock.Restart(); if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z)) viewerPos += camQuat * Nz::Vector3f::Forward() * cameraSpeed; // Si la flèche du bas ou la touche S est pressée, on recule if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S)) viewerPos += camQuat * Nz::Vector3f::Backward() * cameraSpeed; // Etc... if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q)) viewerPos += camQuat * Nz::Vector3f::Left() * cameraSpeed; // Etc... if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D)) viewerPos += camQuat * Nz::Vector3f::Right() * cameraSpeed; // Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift)) viewerPos += Nz::Vector3f::Up() * cameraSpeed; // Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc... if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl)) viewerPos += Nz::Vector3f::Down() * cameraSpeed; uboUpdate = true; } Nz::RenderFrame frame = windowImpl->Acquire(); if (!frame) continue; if (frame.IsFramebufferInvalidated()) RebuildCommandBuffer(); ubo.viewMatrix = Nz::Matrix4f::ViewMatrix(viewerPos, camAngles); if (uboUpdate) { auto& allocation = frame.GetUploadPool().Allocate(uniformSize); std::memcpy(allocation.mappedPtr, &ubo, sizeof(ubo)); frame.Execute([&](Nz::CommandBufferBuilder& builder) { builder.BeginDebugRegion("UBO Update", Nz::Color::Yellow); { builder.PreTransferBarrier(); builder.CopyBuffer(allocation, uniformBuffer.get()); builder.PostTransferBarrier(); } builder.EndDebugRegion(); }, Nz::QueueType::Transfer); uboUpdate = false; } frame.SubmitCommandBuffer(drawCommandBuffer.get(), Nz::QueueType::Graphics); frame.Present(); window.Display(); // On incrémente le compteur de FPS improvisé fps++; if (secondClock.GetMilliseconds() >= 1000) // Toutes les secondes { // Et on insère ces données dans le titre de la fenêtre window.SetTitle(windowTitle + " - " + Nz::String::Number(fps) + " FPS"); /* Note: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier, via quelque chose de similaire à u8"Cha\u00CEne de caract\u00E8res". Cependant, si le code source est encodé en UTF-8 (Comme c'est le cas dans ce fichier), cela fonctionnera aussi comme ceci : "Chaîne de caractères". */ // Et on réinitialise le compteur de FPS fps = 0; // Et on relance l'horloge pour refaire ça dans une seconde secondClock.Restart(); } } return EXIT_SUCCESS; } <commit_msg>Update RenderTest demo<commit_after>#include <Nazara/Core.hpp> #include <Nazara/Platform.hpp> #include <Nazara/Renderer.hpp> #include <Nazara/Shader.hpp> #include <Nazara/Shader/SpirvConstantCache.hpp> #include <Nazara/Shader/SpirvPrinter.hpp> #include <Nazara/Utility.hpp> #include <array> #include <iostream> int main() { Nz::Renderer::Config rendererConfig; std::cout << "Run using Vulkan? (y/n)" << std::endl; if (std::getchar() == 'y') rendererConfig.preferredAPI = Nz::RenderAPI::Vulkan; else rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL; Nz::Modules<Nz::Renderer> nazara(rendererConfig); Nz::RenderWindow window; Nz::MeshParams meshParams; meshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 90.f, 180.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f)); meshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ_Normal_UV); Nz::String windowTitle = "Render Test"; if (!window.Create(Nz::VideoMode(800, 600, 32), windowTitle)) { std::cout << "Failed to create Window" << std::endl; return __LINE__; } std::shared_ptr<Nz::RenderDevice> device = window.GetRenderDevice(); auto fragmentShader = device->InstantiateShaderStage(Nz::ShaderStageType::Fragment, Nz::ShaderLanguage::NazaraBinary, "frag.shader"); if (!fragmentShader) { std::cout << "Failed to instantiate fragment shader" << std::endl; return __LINE__; } auto vertexShader = device->InstantiateShaderStage(Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraBinary, "vert.shader"); if (!vertexShader) { std::cout << "Failed to instantiate fragment shader" << std::endl; return __LINE__; } Nz::MeshRef drfreak = Nz::Mesh::LoadFromFile("resources/Spaceship/spaceship.obj", meshParams); if (!drfreak) { NazaraError("Failed to load model"); return __LINE__; } Nz::StaticMesh* drfreakMesh = static_cast<Nz::StaticMesh*>(drfreak->GetSubMesh(0)); const Nz::VertexBuffer* drfreakVB = drfreakMesh->GetVertexBuffer(); const Nz::IndexBuffer* drfreakIB = drfreakMesh->GetIndexBuffer(); // Index buffer std::cout << "Index count: " << drfreakIB->GetIndexCount() << std::endl; // Vertex buffer std::cout << "Vertex count: " << drfreakVB->GetVertexCount() << std::endl; // Texture Nz::ImageRef drfreakImage = Nz::Image::LoadFromFile("resources/Spaceship/Texture/diffuse.png"); if (!drfreakImage || !drfreakImage->Convert(Nz::PixelFormat_RGBA8)) { NazaraError("Failed to load image"); return __LINE__; } Nz::TextureInfo texParams; texParams.pixelFormat = drfreakImage->GetFormat(); texParams.type = drfreakImage->GetType(); texParams.width = drfreakImage->GetWidth(); texParams.height = drfreakImage->GetHeight(); texParams.depth = drfreakImage->GetDepth(); std::unique_ptr<Nz::Texture> texture = device->InstantiateTexture(texParams); if (!texture->Update(drfreakImage->GetConstPixels())) { NazaraError("Failed to update texture"); return __LINE__; } std::unique_ptr<Nz::TextureSampler> textureSampler = device->InstantiateTextureSampler({}); struct { Nz::Matrix4f projectionMatrix; Nz::Matrix4f modelMatrix; Nz::Matrix4f viewMatrix; } ubo; Nz::Vector2ui windowSize = window.GetSize(); ubo.projectionMatrix = Nz::Matrix4f::Perspective(70.f, float(windowSize.x) / windowSize.y, 0.1f, 1000.f); ubo.viewMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Backward() * 1); ubo.modelMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Forward() * 2 + Nz::Vector3f::Right()); Nz::UInt32 uniformSize = sizeof(ubo); Nz::RenderPipelineLayoutInfo pipelineLayoutInfo; auto& uboBinding = pipelineLayoutInfo.bindings.emplace_back(); uboBinding.index = 0; uboBinding.shaderStageFlags = Nz::ShaderStageType::Vertex; uboBinding.type = Nz::ShaderBindingType::UniformBuffer; auto& textureBinding = pipelineLayoutInfo.bindings.emplace_back(); textureBinding.index = 1; textureBinding.shaderStageFlags = Nz::ShaderStageType::Fragment; textureBinding.type = Nz::ShaderBindingType::Texture; std::shared_ptr<Nz::RenderPipelineLayout> renderPipelineLayout = device->InstantiateRenderPipelineLayout(std::move(pipelineLayoutInfo)); Nz::ShaderBindingPtr shaderBinding = renderPipelineLayout->AllocateShaderBinding(); std::unique_ptr<Nz::AbstractBuffer> uniformBuffer = device->InstantiateBuffer(Nz::BufferType_Uniform); if (!uniformBuffer->Initialize(uniformSize, Nz::BufferUsage_DeviceLocal | Nz::BufferUsage_Dynamic)) { NazaraError("Failed to create uniform buffer"); return __LINE__; } shaderBinding->Update({ { 0, Nz::ShaderBinding::UniformBufferBinding { uniformBuffer.get(), 0, uniformSize } }, { 1, Nz::ShaderBinding::TextureBinding { texture.get(), textureSampler.get() } } }); Nz::RenderPipelineInfo pipelineInfo; pipelineInfo.pipelineLayout = renderPipelineLayout; pipelineInfo.depthBuffer = true; pipelineInfo.shaderStages.emplace_back(fragmentShader); pipelineInfo.shaderStages.emplace_back(vertexShader); auto& vertexBuffer = pipelineInfo.vertexBuffers.emplace_back(); vertexBuffer.binding = 0; vertexBuffer.declaration = drfreakVB->GetVertexDeclaration(); std::unique_ptr<Nz::RenderPipeline> pipeline = device->InstantiateRenderPipeline(pipelineInfo); Nz::RenderDevice* renderDevice = window.GetRenderDevice().get(); Nz::RenderWindowImpl* windowImpl = window.GetImpl(); std::unique_ptr<Nz::CommandPool> commandPool = windowImpl->CreateCommandPool(Nz::QueueType::Graphics); Nz::RenderBuffer* renderBufferIB = static_cast<Nz::RenderBuffer*>(drfreakIB->GetBuffer()->GetImpl()); Nz::RenderBuffer* renderBufferVB = static_cast<Nz::RenderBuffer*>(drfreakVB->GetBuffer()->GetImpl()); if (!renderBufferIB->Synchronize(renderDevice)) { NazaraError("Failed to synchronize render buffer"); return __LINE__; } if (!renderBufferVB->Synchronize(renderDevice)) { NazaraError("Failed to synchronize render buffer"); return __LINE__; } Nz::AbstractBuffer* indexBufferImpl = renderBufferIB->GetHardwareBuffer(renderDevice); Nz::AbstractBuffer* vertexBufferImpl = renderBufferVB->GetHardwareBuffer(renderDevice); Nz::CommandBufferPtr drawCommandBuffer; auto RebuildCommandBuffer = [&] { Nz::Vector2ui windowSize = window.GetSize(); drawCommandBuffer = commandPool->BuildCommandBuffer([&](Nz::CommandBufferBuilder& builder) { Nz::Recti renderRect(0, 0, window.GetSize().x, window.GetSize().y); Nz::CommandBufferBuilder::ClearValues clearValues[2]; clearValues[0].color = Nz::Color::Black; clearValues[1].depth = 1.f; clearValues[1].stencil = 0; builder.BeginDebugRegion("Main window rendering", Nz::Color::Green); { builder.BeginRenderPass(windowImpl->GetFramebuffer(), windowImpl->GetRenderPass(), renderRect, { clearValues[0], clearValues[1] }); { builder.BindIndexBuffer(indexBufferImpl); builder.BindPipeline(*pipeline); builder.BindVertexBuffer(0, vertexBufferImpl); builder.BindShaderBinding(*shaderBinding); builder.SetScissor(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); builder.SetViewport(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); builder.DrawIndexed(drfreakIB->GetIndexCount()); } builder.EndRenderPass(); } builder.EndDebugRegion(); }); }; RebuildCommandBuffer(); Nz::Vector3f viewerPos = Nz::Vector3f::Zero(); Nz::EulerAnglesf camAngles(0.f, 0.f, 0.f); Nz::Quaternionf camQuat(camAngles); window.EnableEventPolling(true); Nz::Clock updateClock; Nz::Clock secondClock; unsigned int fps = 0; bool uboUpdate = true; Nz::Mouse::SetRelativeMouseMode(true); while (window.IsOpen()) { Nz::WindowEvent event; while (window.PollEvent(&event)) { switch (event.type) { case Nz::WindowEventType_Quit: window.Close(); break; case Nz::WindowEventType_MouseMoved: // La souris a bougé { // Gestion de la caméra free-fly (Rotation) float sensitivity = 0.3f; // Sensibilité de la souris // On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris camAngles.yaw = Nz::NormalizeAngle(camAngles.yaw - event.mouseMove.deltaX*sensitivity); // Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles camAngles.pitch = Nz::Clamp(camAngles.pitch + event.mouseMove.deltaY*sensitivity, -89.f, 89.f); camQuat = camAngles; uboUpdate = true; break; } case Nz::WindowEventType_Resized: { Nz::Vector2ui windowSize = window.GetSize(); ubo.projectionMatrix = Nz::Matrix4f::Perspective(70.f, float(windowSize.x) / windowSize.y, 0.1f, 1000.f); uboUpdate = true; break; } default: break; } } if (updateClock.GetMilliseconds() > 1000 / 60) { float cameraSpeed = 2.f * updateClock.GetSeconds(); updateClock.Restart(); if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z)) viewerPos += camQuat * Nz::Vector3f::Forward() * cameraSpeed; // Si la flèche du bas ou la touche S est pressée, on recule if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S)) viewerPos += camQuat * Nz::Vector3f::Backward() * cameraSpeed; // Etc... if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q)) viewerPos += camQuat * Nz::Vector3f::Left() * cameraSpeed; // Etc... if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D)) viewerPos += camQuat * Nz::Vector3f::Right() * cameraSpeed; // Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift)) viewerPos += Nz::Vector3f::Up() * cameraSpeed; // Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc... if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl)) viewerPos += Nz::Vector3f::Down() * cameraSpeed; uboUpdate = true; } Nz::RenderFrame frame = windowImpl->Acquire(); if (!frame) continue; if (frame.IsFramebufferInvalidated()) RebuildCommandBuffer(); ubo.viewMatrix = Nz::Matrix4f::ViewMatrix(viewerPos, camAngles); if (uboUpdate) { auto& allocation = frame.GetUploadPool().Allocate(uniformSize); std::memcpy(allocation.mappedPtr, &ubo, sizeof(ubo)); frame.Execute([&](Nz::CommandBufferBuilder& builder) { builder.BeginDebugRegion("UBO Update", Nz::Color::Yellow); { builder.PreTransferBarrier(); builder.CopyBuffer(allocation, uniformBuffer.get()); builder.PostTransferBarrier(); } builder.EndDebugRegion(); }, Nz::QueueType::Transfer); uboUpdate = false; } frame.SubmitCommandBuffer(drawCommandBuffer.get(), Nz::QueueType::Graphics); frame.Present(); window.Display(); // On incrémente le compteur de FPS improvisé fps++; if (secondClock.GetMilliseconds() >= 1000) // Toutes les secondes { // Et on insère ces données dans le titre de la fenêtre window.SetTitle(windowTitle + " - " + Nz::String::Number(fps) + " FPS"); /* Note: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier, via quelque chose de similaire à u8"Cha\u00CEne de caract\u00E8res". Cependant, si le code source est encodé en UTF-8 (Comme c'est le cas dans ce fichier), cela fonctionnera aussi comme ceci : "Chaîne de caractères". */ // Et on réinitialise le compteur de FPS fps = 0; // Et on relance l'horloge pour refaire ça dans une seconde secondClock.Restart(); } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//Copyright (c) 2019 Ultimaker B.V. #include "BeadingStrategyHelper.h" namespace arachne { double inward_distributed_center_size = 2; int max_bead_count = -1; StrategyType toStrategyType(char c) { switch (c) { case 'n': return StrategyType::Naive; case 'N': return StrategyType::NaiveStrategy; case 'c': return StrategyType::Constant; case 'r': return StrategyType::Center; case 'd': return StrategyType::Distributed; case 'i': return StrategyType::InwardDistributed; case 's': return StrategyType::SingleBead; case 'l': return StrategyType::LimitedDistributed; case 'o': return StrategyType::OutlineAccuracy; } return StrategyType::COUNT; } std::string to_string(StrategyType type) { switch (type) { case StrategyType::Naive: return "Naive"; case StrategyType::NaiveStrategy: return "NaiveStrategy"; case StrategyType::Constant: return "Constant"; case StrategyType::Center: return "Center"; case StrategyType::Distributed: return "Distributed"; case StrategyType::InwardDistributed: return "InwardDistributed"; case StrategyType::LimitedDistributed: return "LimitedDistributed"; case StrategyType::SingleBead: return "SingleBead"; case StrategyType::OutlineAccuracy: return "OutlineAccuracy"; default: return "unknown_strategy"; } } BeadingStrategy* BeadingStrategyHelper::makeStrategy(StrategyType type, coord_t prefered_bead_width, float transitioning_angle, std::optional<coord_t> min_bead_width, std::optional<coord_t> min_feature_size) { BeadingStrategy* ret = nullptr; switch (type) { case StrategyType::NaiveStrategy: ret = new NaiveBeadingStrategy(prefered_bead_width); break; case StrategyType::Constant: ret = new ConstantBeadingStrategy(prefered_bead_width, 4, .99 * M_PI); break; case StrategyType::Center: ret = new CenterDeviationBeadingStrategy(prefered_bead_width, transitioning_angle); break; case StrategyType::Distributed: ret = new DistributedBeadingStrategy(prefered_bead_width, transitioning_angle); break; case StrategyType::InwardDistributed: ret = new InwardDistributedBeadingStrategy(prefered_bead_width, transitioning_angle, inward_distributed_center_size); break; case StrategyType::LimitedDistributed: ret = new LimitedDistributedBeadingStrategy(prefered_bead_width, max_bead_count, transitioning_angle); break; case StrategyType::SingleBead: ret = new SingleBeadBeadingStrategy(prefered_bead_width, transitioning_angle); break; case StrategyType::OutlineAccuracy: ret = new LimitedBeadingStrategy(max_bead_count, new OutlineAccuracyBeadingStrategy(prefered_bead_width, prefered_bead_width * 3 / 4, prefered_bead_width / 2, transitioning_angle)); break; default: logError("Cannot make strategy!\n"); return nullptr; } if (min_bead_width || min_feature_size) { ret = new WideningBeadingStrategy(ret, min_feature_size.value_or(*min_bead_width), min_bead_width.value_or(*min_feature_size)); } if (max_bead_count > 0) { ret = new LimitedBeadingStrategy(max_bead_count, ret); } return ret; } } // namespace arachne <commit_msg>turn off meta-schemes for Constant strategy<commit_after>//Copyright (c) 2019 Ultimaker B.V. #include "BeadingStrategyHelper.h" namespace arachne { double inward_distributed_center_size = 2; int max_bead_count = -1; StrategyType toStrategyType(char c) { switch (c) { case 'n': return StrategyType::Naive; case 'N': return StrategyType::NaiveStrategy; case 'c': return StrategyType::Constant; case 'r': return StrategyType::Center; case 'd': return StrategyType::Distributed; case 'i': return StrategyType::InwardDistributed; case 's': return StrategyType::SingleBead; case 'l': return StrategyType::LimitedDistributed; case 'o': return StrategyType::OutlineAccuracy; } return StrategyType::COUNT; } std::string to_string(StrategyType type) { switch (type) { case StrategyType::Naive: return "Naive"; case StrategyType::NaiveStrategy: return "NaiveStrategy"; case StrategyType::Constant: return "Constant"; case StrategyType::Center: return "Center"; case StrategyType::Distributed: return "Distributed"; case StrategyType::InwardDistributed: return "InwardDistributed"; case StrategyType::LimitedDistributed: return "LimitedDistributed"; case StrategyType::SingleBead: return "SingleBead"; case StrategyType::OutlineAccuracy: return "OutlineAccuracy"; default: return "unknown_strategy"; } } BeadingStrategy* BeadingStrategyHelper::makeStrategy(StrategyType type, coord_t prefered_bead_width, float transitioning_angle, std::optional<coord_t> min_bead_width, std::optional<coord_t> min_feature_size) { BeadingStrategy* ret = nullptr; switch (type) { case StrategyType::NaiveStrategy: ret = new NaiveBeadingStrategy(prefered_bead_width); break; case StrategyType::Constant: ret = new ConstantBeadingStrategy(prefered_bead_width, 4, .99 * M_PI); break; case StrategyType::Center: ret = new CenterDeviationBeadingStrategy(prefered_bead_width, transitioning_angle); break; case StrategyType::Distributed: ret = new DistributedBeadingStrategy(prefered_bead_width, transitioning_angle); break; case StrategyType::InwardDistributed: ret = new InwardDistributedBeadingStrategy(prefered_bead_width, transitioning_angle, inward_distributed_center_size); break; case StrategyType::LimitedDistributed: ret = new LimitedDistributedBeadingStrategy(prefered_bead_width, max_bead_count, transitioning_angle); break; case StrategyType::SingleBead: ret = new SingleBeadBeadingStrategy(prefered_bead_width, transitioning_angle); break; case StrategyType::OutlineAccuracy: ret = new LimitedBeadingStrategy(max_bead_count, new OutlineAccuracyBeadingStrategy(prefered_bead_width, prefered_bead_width * 3 / 4, prefered_bead_width / 2, transitioning_angle)); break; default: logError("Cannot make strategy!\n"); return nullptr; } if ((min_bead_width || min_feature_size) && type != StrategyType::Constant) { ret = new WideningBeadingStrategy(ret, min_feature_size.value_or(*min_bead_width), min_bead_width.value_or(*min_feature_size)); } if ((max_bead_count > 0) && type != StrategyType::Constant) { ret = new LimitedBeadingStrategy(max_bead_count, ret); } return ret; } } // namespace arachne <|endoftext|>
<commit_before>#include "entity_system.h" #include "enumerate.h" #include "itemdb.h" #include <entt.hpp> #include "components/basic_info.h" #include "components/computed_values.h" #include "components/faction.h" #include "components/graphics.h" #include "components/guild.h" #include "components/hotbar.h" #include "components/inventory.h" #include "components/item.h" #include "components/level.h" #include "components/life.h" #include "components/magic.h" #include "components/npc.h" #include "components/owner.h" #include "components/position.h" #include "components/skills.h" #include "components/stamina.h" #include "components/stats.h" #include "components/status_effects.h" #include "components/wishlist.h" EntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate) { logger = Core::CLog::GetLogger(Core::log_type::NETWORK).lock(); } EntitySystem::~EntitySystem() { work_queue.kill(); } void EntitySystem::add_task(std::function<void(RoseCommon::Registry&, std::chrono::milliseconds)>&& task) { work_queue.push_back(std::move(task)); } void EntitySystem::update(std::chrono::milliseconds dt) { auto start = Core::Time::GetTickCount(); for (auto [res, task] = work_queue.pop_front(); res;) { std::lock_guard<std::mutex> lock(access); task(registry, dt); const std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(Core::Time::GetTickCount() - start); if (diff >= maxTimePerUpdate) { logger->warn("Stopping after {}ms, {} tasks remaining", maxTimePerUpdate.count(), work_queue.size()); break; } auto [tmp_res, tmp_task] = work_queue.pop_front(); res = tmp_res; task = std::move(tmp_task); } } RoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium) { using namespace Component; auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; Core::InventoryTable inventoryTable{}; Core::SkillTable skillsTable{}; Core::WishTable wish{}; auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters)) .from(characters).where(characters.id == charId)); if (static_cast<long>(charRes.front().count) != 1L) { return entt::null; } const auto& charRow = charRes.front(); entt::prototype prototype(registry); auto& basicInfo = prototype.set<BasicInfo>(); basicInfo.name = charRow.name; basicInfo.id = idManager.get_free_id(); basicInfo.tag = basicInfo.id; basicInfo.teamId = basicInfo.id; basicInfo.job = charRow.job; basicInfo.statPoints = charRow.statPoints; basicInfo.skillPoints = charRow.skillPoints; basicInfo.pkFlag = charRow.pkFlag; auto& computedValues = prototype.set<ComputedValues>(); computedValues.command = RoseCommon::Command::STOP; computedValues.isOnMap.store(false); computedValues.moveMode = RoseCommon::MoveMode::WALK; computedValues.runSpeed = 0; computedValues.atkSpeed = 0; computedValues.weightRate = 0; auto& faction = prototype.set<Faction>(); faction.id = charRow.factionid; faction.rank = charRow.factionRank; faction.fame = charRow.fame; faction.factionFame[0] = charRow.factionFame1; faction.factionFame[1] = charRow.factionFame2; faction.points[0] = charRow.factionPoints1; faction.points[1] = charRow.factionPoints2; faction.points[2] = charRow.factionPoints3; auto& graphics = prototype.set<Graphics>(); graphics.face = charRow.face; graphics.hair = charRow.hair; graphics.race = charRow.race; auto& guild = prototype.set<Guild>(); guild.id = charRow.clanid; guild.contribution = charRow.clanContribution; guild.rank = charRow.clanRank; prototype.set<Hotbar>(); auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId)); auto& inventory = prototype.set<Inventory>(); for (const auto& row : invRes) { if (row.slot >= RoseCommon::MAX_ITEMS) { continue; } Item item; item.isCreated = false; item.life = 1000; item.hasSocket = row.socket; item.isAppraised = true; item.refine = row.refine; item.count = row.amount; item.gemOpt = row.gemOpt; item.price = 0; inventory.items[row.slot] = load_item(row.itemtype, row.itemid, item); } auto& level = prototype.set<Level>(); level.xp = charRow.exp; level.level = charRow.level; level.penaltyXp = charRow.penaltyExp; auto& life = prototype.set<Life>(); life.hp = charRow.maxHp / 3; // you only get 30% of your health when login in life.maxHp = charRow.maxHp; auto& magic = prototype.set<Magic>(); magic.mp = charRow.maxMp / 3; magic.maxMp = charRow.maxMp; auto& pos = prototype.set<Position>(); pos.x = charRow.x; pos.y = charRow.y; pos.z = 0; pos.spawn = charRow.reviveMap; pos.map = charRow.map; auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId)); auto& skills = prototype.set<Skills>(); for (const auto& [i, row] : Core::enumerate(skillRes)) { skills.skills[i].set_id(row.id); skills.skills[i].set_level(row.level); } auto& stamina = prototype.set<Stamina>(); stamina.stamina = charRow.stamina; auto& stats = prototype.set<Stats>(); stats.str = charRow.str; stats.dex = charRow.dex; stats.int_ = charRow.int_; stats.con = charRow.con; stats.charm = charRow.charm; stats.sense = charRow.sense; stats.bodySize = 100; stats.headSize = 100; prototype.set<StatusEffects>(); auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId)); auto& wishlist = prototype.set<Wishlist>(); for (const auto& row : wishRes) { if (row.slot >= RoseCommon::MAX_WISHLIST) { continue; } Item item; item.isCreated = false; item.life = 1000; item.hasSocket = row.socket; item.isAppraised = true; item.refine = row.refine; item.count = row.amount; item.gemOpt = row.gemOpt; item.price = row.price; wishlist.items[row.slot] = load_item(row.itemtype, row.itemid, item); } std::lock_guard<std::mutex> lock(access); return prototype(); } void EntitySystem::save_character(RoseCommon::Entity character) const { } RoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) { using namespace Component; entt::prototype prototype(registry); const auto &itemDb = RoseCommon::ItemDatabase::getInstance(); if (!itemDb.itemExists(type, id)) { return entt::null; } const auto& def = itemDb.getItemDef(type, id); auto& item = prototype.set<Item>(); item.isCreated = false; item.life = 1000; item.hasSocket = false; item.isAppraised = false; item.refine = 0; item.count = 0; item.gemOpt = 0; item.price = 0; prototype.set<RoseCommon::ItemDef>(def); std::lock_guard<std::mutex> lock(access); return prototype(); } RoseCommon::Entity EntitySystem::load_item(uint8_t type, uint16_t id, Component::Item item) { auto entity = create_item(type, id); if (entity == entt::null) { return entt::null; } registry.replace<Component::Item>(entity, item); return entity; } void EntitySystem::save_item(RoseCommon::Entity item, RoseCommon::Entity owner) const { } <commit_msg>Update entity_system.cpp<commit_after>#include "entity_system.h" #include "enumerate.h" #include "itemdb.h" #include <entt.hpp> #include "components/basic_info.h" #include "components/computed_values.h" #include "components/faction.h" #include "components/graphics.h" #include "components/guild.h" #include "components/hotbar.h" #include "components/inventory.h" #include "components/item.h" #include "components/level.h" #include "components/life.h" #include "components/magic.h" #include "components/npc.h" #include "components/owner.h" #include "components/position.h" #include "components/skills.h" #include "components/stamina.h" #include "components/stats.h" #include "components/status_effects.h" #include "components/wishlist.h" EntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate) { logger = Core::CLog::GetLogger(Core::log_type::NETWORK).lock(); } EntitySystem::~EntitySystem() { work_queue.kill(); } void EntitySystem::add_task(std::function<void(RoseCommon::Registry&, std::chrono::milliseconds)>&& task) { work_queue.push_back(std::move(task)); } void EntitySystem::update(std::chrono::milliseconds dt) { auto start = Core::Time::GetTickCount(); for (auto [res, task] = work_queue.pop_front(); res;) { std::lock_guard<std::mutex> lock(access); task(registry, dt); const std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(Core::Time::GetTickCount() - start); if (diff >= maxTimePerUpdate) { logger->warn("Stopping after {}ms, {} tasks remaining", maxTimePerUpdate.count(), work_queue.size()); break; } auto [tmp_res, tmp_task] = work_queue.pop_front(); res = tmp_res; task = std::move(tmp_task); } } RoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium) { using namespace Component; auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; Core::InventoryTable inventoryTable{}; Core::SkillTable skillsTable{}; Core::WishTable wish{}; auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters)) .from(characters).where(characters.id == charId)); if (static_cast<long>(charRes.front().count) != 1L) { return entt::null; } const auto& charRow = charRes.front(); entt::prototype prototype(registry); auto& basicInfo = prototype.set<BasicInfo>(); basicInfo.name = charRow.name; basicInfo.id = idManager.get_free_id(); basicInfo.tag = basicInfo.id; basicInfo.teamId = basicInfo.id; basicInfo.job = charRow.job; basicInfo.statPoints = charRow.statPoints; basicInfo.skillPoints = charRow.skillPoints; basicInfo.pkFlag = charRow.pkFlag; basicInfo.stone = charRow.stone; auto& computedValues = prototype.set<ComputedValues>(); computedValues.command = RoseCommon::Command::STOP; computedValues.isOnMap.store(false); computedValues.moveMode = RoseCommon::MoveMode::WALK; computedValues.runSpeed = 0; computedValues.atkSpeed = 0; computedValues.weightRate = 0; auto& faction = prototype.set<Faction>(); faction.id = charRow.factionid; faction.rank = charRow.factionRank; faction.fame = charRow.fame; faction.factionFame[0] = charRow.factionFame1; faction.factionFame[1] = charRow.factionFame2; faction.points[0] = charRow.factionPoints1; faction.points[1] = charRow.factionPoints2; faction.points[2] = charRow.factionPoints3; auto& graphics = prototype.set<Graphics>(); graphics.face = charRow.face; graphics.hair = charRow.hair; graphics.race = charRow.race; auto& guild = prototype.set<Guild>(); guild.id = charRow.clanid; guild.contribution = charRow.clanContribution; guild.rank = charRow.clanRank; prototype.set<Hotbar>(); auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId)); auto& inventory = prototype.set<Inventory>(); for (const auto& row : invRes) { if (row.slot >= RoseCommon::MAX_ITEMS) { continue; } Item item; item.isCreated = false; item.life = 1000; item.hasSocket = row.socket; item.isAppraised = true; item.refine = row.refine; item.count = row.amount; item.gemOpt = row.gemOpt; item.price = 0; inventory.items[row.slot] = load_item(row.itemtype, row.itemid, item); } auto& level = prototype.set<Level>(); level.xp = charRow.exp; level.level = charRow.level; level.penaltyXp = charRow.penaltyExp; auto& life = prototype.set<Life>(); life.hp = charRow.maxHp / 3; // you only get 30% of your health when login in life.maxHp = charRow.maxHp; auto& magic = prototype.set<Magic>(); magic.mp = charRow.maxMp / 3; magic.maxMp = charRow.maxMp; auto& pos = prototype.set<Position>(); pos.x = charRow.x; pos.y = charRow.y; pos.z = 0; pos.spawn = charRow.reviveMap; pos.map = charRow.map; auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId)); auto& skills = prototype.set<Skills>(); for (const auto& [i, row] : Core::enumerate(skillRes)) { skills.skills[i].set_id(row.id); skills.skills[i].set_level(row.level); } auto& stamina = prototype.set<Stamina>(); stamina.stamina = charRow.stamina; auto& stats = prototype.set<Stats>(); stats.str = charRow.str; stats.dex = charRow.dex; stats.int_ = charRow.int_; stats.con = charRow.con; stats.charm = charRow.charm; stats.sense = charRow.sense; stats.bodySize = 100; stats.headSize = 100; prototype.set<StatusEffects>(); auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId)); auto& wishlist = prototype.set<Wishlist>(); for (const auto& row : wishRes) { if (row.slot >= RoseCommon::MAX_WISHLIST) { continue; } Item item; item.isCreated = false; item.life = 1000; item.hasSocket = row.socket; item.isAppraised = true; item.refine = row.refine; item.count = row.amount; item.gemOpt = row.gemOpt; item.price = row.price; wishlist.items[row.slot] = load_item(row.itemtype, row.itemid, item); } std::lock_guard<std::mutex> lock(access); return prototype(); } void EntitySystem::save_character(RoseCommon::Entity character) const { } RoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) { using namespace Component; entt::prototype prototype(registry); const auto &itemDb = RoseCommon::ItemDatabase::getInstance(); if (!itemDb.itemExists(type, id)) { return entt::null; } const auto& def = itemDb.getItemDef(type, id); auto& item = prototype.set<Item>(); item.isCreated = false; item.life = 1000; item.hasSocket = false; item.isAppraised = false; item.refine = 0; item.count = 0; item.gemOpt = 0; item.price = 0; prototype.set<RoseCommon::ItemDef>(def); std::lock_guard<std::mutex> lock(access); return prototype(); } RoseCommon::Entity EntitySystem::load_item(uint8_t type, uint16_t id, Component::Item item) { auto entity = create_item(type, id); if (entity == entt::null) { return entt::null; } registry.replace<Component::Item>(entity, item); return entity; } void EntitySystem::save_item(RoseCommon::Entity item, RoseCommon::Entity owner) const { } <|endoftext|>
<commit_before>#include <boost/filesystem.hpp> #include <boost/ref.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include "Renderer.hpp" #include "AlloShared/StatsUtils.hpp" #include "AlloShared/to_human_readable_byte_count.hpp" #include "AlloShared/CommandHandler.hpp" #include "AlloShared/Console.hpp" #include "AlloShared/Config.hpp" #include "AlloShared/CommandLine.hpp" #include "AlloReceiver/RTSPCubemapSourceClient.hpp" #include "AlloReceiver/AlloReceiver.h" #include "AlloReceiver/Stats.hpp" #include "AlloReceiver/H264CubemapSource.h" #define DEG_DIV_RAD 57.29577951308233 #define RAD_DIV_DEG 0.01745329251994 const unsigned int DEFAULT_SINK_BUFFER_SIZE = 2000000000; static Stats stats; static bool noDisplay; static Renderer renderer; static auto lastStatsTime = boost::chrono::steady_clock::now(); static std::string statsFormat = AlloReceiver::formatStringMaker(); StereoCubemap* onNextCubemap(CubemapSource* source, StereoCubemap* cubemap) { for (int i = 0; i < cubemap->getEye(0)->getFacesCount(); i++) { stats.store(StatsUtils::CubemapFace(i, StatsUtils::CubemapFace::DISPLAYED)); } stats.store(StatsUtils::Cubemap()); return cubemap; } void onReceivedNALU(CubemapSource* source, u_int8_t type, size_t size, int face) { //stats.store(StatsUtils::NALU(type, size, face, StatsUtils::NALU::RECEIVED)); } void onReceivedFrame(CubemapSource* source, u_int8_t type, size_t size, int face) { //stats.store(StatsUtils::Frame(type, size, face, StatsUtils::Frame::RECEIVED)); } void onDecodedFrame(CubemapSource* source, u_int8_t type, size_t size, int face) { //stats.store(StatsUtils::Frame(type, size, face, StatsUtils::Frame::DECODED)); } void onColorConvertedFrame(CubemapSource* source, u_int8_t type, size_t size, int face) { stats.store(StatsUtils::Frame(type, size, face, StatsUtils::Frame::COLOR_CONVERTED)); } void onAddedFrameToCubemap(CubemapSource* source, int face) { //stats.store(StatsUtils::CubemapFace(face, StatsUtils::CubemapFace::ADDED)); } void setOnScheduledFrameInCubemap(CubemapSource* source, int face) { stats.store(StatsUtils::CubemapFace(face, StatsUtils::CubemapFace::SCHEDULED)); } void onDisplayedCubemapFace(Renderer* renderer, int face) { stats.store(StatsUtils::CubemapFace(face, StatsUtils::CubemapFace::DISPLAYED)); } void onDisplayedFrame(Renderer* renderer) { stats.store(StatsUtils::Cubemap()); } void onDidConnect(RTSPCubemapSourceClient* client, CubemapSource* cubemapSource) { H264CubemapSource* h264CubemapSource = dynamic_cast<H264CubemapSource*>(cubemapSource); if (h264CubemapSource) { h264CubemapSource->setOnReceivedNALU (boost::bind(&onReceivedNALU, _1, _2, _3, _4)); h264CubemapSource->setOnReceivedFrame (boost::bind(&onReceivedFrame, _1, _2, _3, _4)); h264CubemapSource->setOnDecodedFrame (boost::bind(&onDecodedFrame, _1, _2, _3, _4)); h264CubemapSource->setOnColorConvertedFrame (boost::bind(&onColorConvertedFrame, _1, _2, _3, _4)); h264CubemapSource->setOnAddedFrameToCubemap (boost::bind(&onAddedFrameToCubemap, _1, _2)); h264CubemapSource->setOnScheduledFrameInCubemap(boost::bind(&setOnScheduledFrameInCubemap, _1, _2)); } if (noDisplay) { cubemapSource->setOnNextCubemap(boost::bind(&onNextCubemap, _1, _2)); } else { renderer.setCubemapSource(cubemapSource); } } int main(int argc, char* argv[]) { noDisplay = false; std::string url = ""; std::string interfaceAddress = "0.0.0.0"; unsigned long bufferSize = DEFAULT_SINK_BUFFER_SIZE; bool matchStereoPairs = false; std::string configFilePath = "AlloPlayer.config"; std::initializer_list<CommandHandler::Command> generalCommands = { { "gamma-min", {"val"}, [](const std::vector<std::string>& values) { renderer.setGammaMin(boost::lexical_cast<float>(values[0])); } }, { "gamma-max", {"val"}, [](const std::vector<std::string>& values) { renderer.setGammaMax(boost::lexical_cast<float>(values[0])); } }, { "gamma-pow", {"val"}, [](const std::vector<std::string>& values) { renderer.setGammaPow(boost::lexical_cast<float>(values[0])); } }, { "for-rotation", {"deg_alpha", "deg_beta", "deg_gamma"}, [](const std::vector<std::string>& values) { renderer.setFORRotation(al::Vec3f(boost::lexical_cast<float>(values[0]) * RAD_DIV_DEG, boost::lexical_cast<float>(values[1]) * RAD_DIV_DEG, boost::lexical_cast<float>(values[2]) * RAD_DIV_DEG)); } }, { "for-angle", {"deg"}, [](const std::vector<std::string>& values) { renderer.setFORAngle(boost::lexical_cast<float>(values[0]) * RAD_DIV_DEG); } }, { "rotation", {"deg_alpha", "deg_beta", "deg_gamma"}, [](const std::vector<std::string>& values) { renderer.setRotation(al::Vec3f(boost::lexical_cast<float>(values[0]) * RAD_DIV_DEG, boost::lexical_cast<float>(values[1]) * RAD_DIV_DEG, boost::lexical_cast<float>(values[2]) * RAD_DIV_DEG)); } } }; std::initializer_list<CommandHandler::Command> commandLineOnlyCommands = { { "config", {"file_path"}, [&configFilePath](const std::vector<std::string>& values) { configFilePath = values[0]; } } }; std::initializer_list<CommandHandler::Command> configCommandLineOnlyCommands = { { "no-display", {}, [](const std::vector<std::string>& values) { noDisplay = true; } }, { "url", {"rtsp_url"}, [&url](const std::vector<std::string>& values) { url = values[0]; } }, { "interface-address", {"ip"}, [&interfaceAddress](const std::vector<std::string>& values) { interfaceAddress = values[0]; } }, { "buffer-size", {"bytes"}, [&bufferSize](const std::vector<std::string>& values) { bufferSize = boost::lexical_cast<unsigned long>(values[0]); } }, { "match-stereo-pairs", {}, [&matchStereoPairs](const std::vector<std::string>& values) { matchStereoPairs = true; } } }; std::initializer_list<CommandHandler::Command> consoleOnlyCommands = { { "stats", {}, [](const std::vector<std::string>& values) { boost::chrono::steady_clock::time_point now = boost::chrono::steady_clock::now(); std::cout << stats.summary(boost::chrono::duration_cast<boost::chrono::microseconds>(now - lastStatsTime), AlloReceiver::statValsMaker, AlloReceiver::postProcessorMaker, statsFormat); lastStatsTime = now; } }, { "quit", {}, [](const std::vector<std::string>& values) { exit(0); } }, { "info", {}, [&bufferSize, &url, &interfaceAddress, &matchStereoPairs](const std::vector<std::string>& values) { al::Vec3f forRotation = renderer.getFORRotation() * DEG_DIV_RAD; al::Vec3f rotation = renderer.getRotation() * DEG_DIV_RAD; std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(1); std::cout << "Display: " << ((noDisplay) ? "no" : "yes") << std::endl; std::cout << "RTSP URL: " << url << std::endl; std::cout << "Interface address: " << interfaceAddress << std::endl; std::cout << "Buffer size: " << to_human_readable_byte_count(bufferSize, false, false) << std::endl; std::cout << "Match stereo pairs: " << ((matchStereoPairs) ? "yes" : "no") << std::endl; std::cout << "Gamma min: " << renderer.getGammaMin() << std::endl; std::cout << "Gamma max: " << renderer.getGammaMax() << std::endl; std::cout << "Gamma pow: " << renderer.getGammaPow() << std::endl; std::cout << "FOR angle: " << renderer.getFORAngle() * DEG_DIV_RAD << "°" << std::endl; std::cout << "FOR rotation: " << "α=" << forRotation[0] << "°\t" << "β=" << forRotation[1] << "°\t" << "γ=" << forRotation[2] << "°" << std::endl; std::cout << "Scene rotation: " << "α=" << rotation[0] << "°\t" << "β=" << rotation[1] << "°\t" << "γ=" << rotation[2] << "°" << std::endl; } } }; CommandHandler consoleCommandHandler({generalCommands, consoleOnlyCommands}); CommandHandler configCommandHandler({generalCommands, configCommandLineOnlyCommands}); CommandHandler commandLineCommandHandler({generalCommands, configCommandLineOnlyCommands, commandLineOnlyCommands}); // The desired behaviour is that command line parameters override config file settings. // So, we would run the config file parser first and then the command line parser. // However, then we cannot pass the config file path as a command line parameter. // The solution here is to run the command line parser twice: // before and after the config file parser. auto commandLineParseResult = CommandLine::parseCommandLine(commandLineCommandHandler, argc, argv); if (!commandLineParseResult.first) { std::cerr << commandLineParseResult.second << std::endl; std::cerr << commandLineCommandHandler.getCommandHelpString(); abort(); } auto configParseResult = Config::parseConfigFile(configCommandHandler, configFilePath); if (!configParseResult.first) { std::cerr << configParseResult.second << std::endl; std::cerr << configCommandHandler.getCommandHelpString(); abort(); } commandLineParseResult = CommandLine::parseCommandLine(commandLineCommandHandler, argc, argv); if (!commandLineParseResult.first) { std::cerr << commandLineParseResult.second << std::endl; std::cerr << commandLineCommandHandler.getCommandHelpString(); abort(); } if (url == "") { std::cerr << "No URL specified." << std::endl; } Console console(consoleCommandHandler); console.start(); RTSPCubemapSourceClient* rtspClient = RTSPCubemapSourceClient::create(url.c_str(), bufferSize, AV_PIX_FMT_YUV420P, matchStereoPairs, interfaceAddress.c_str()); rtspClient->setOnDidConnect(boost::bind(&onDidConnect, _1, _2)); rtspClient->connect(); if (noDisplay) { std::cout << "network only" << std::endl; while(true) { boost::this_thread::yield(); } } else { renderer.setOnDisplayedCubemapFace(boost::bind(&onDisplayedCubemapFace, _1, _2)); renderer.setOnDisplayedFrame(boost::bind(&onDisplayedFrame, _1)); renderer.start(); // does not return } } <commit_msg>AlloPlayer's info prints out path of config file.<commit_after>#include <boost/filesystem.hpp> #include <boost/ref.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include "Renderer.hpp" #include "AlloShared/StatsUtils.hpp" #include "AlloShared/to_human_readable_byte_count.hpp" #include "AlloShared/CommandHandler.hpp" #include "AlloShared/Console.hpp" #include "AlloShared/Config.hpp" #include "AlloShared/CommandLine.hpp" #include "AlloReceiver/RTSPCubemapSourceClient.hpp" #include "AlloReceiver/AlloReceiver.h" #include "AlloReceiver/Stats.hpp" #include "AlloReceiver/H264CubemapSource.h" #define DEG_DIV_RAD 57.29577951308233 #define RAD_DIV_DEG 0.01745329251994 const unsigned int DEFAULT_SINK_BUFFER_SIZE = 2000000000; static Stats stats; static bool noDisplay; static Renderer renderer; static auto lastStatsTime = boost::chrono::steady_clock::now(); static std::string statsFormat = AlloReceiver::formatStringMaker(); StereoCubemap* onNextCubemap(CubemapSource* source, StereoCubemap* cubemap) { for (int i = 0; i < cubemap->getEye(0)->getFacesCount(); i++) { stats.store(StatsUtils::CubemapFace(i, StatsUtils::CubemapFace::DISPLAYED)); } stats.store(StatsUtils::Cubemap()); return cubemap; } void onReceivedNALU(CubemapSource* source, u_int8_t type, size_t size, int face) { //stats.store(StatsUtils::NALU(type, size, face, StatsUtils::NALU::RECEIVED)); } void onReceivedFrame(CubemapSource* source, u_int8_t type, size_t size, int face) { //stats.store(StatsUtils::Frame(type, size, face, StatsUtils::Frame::RECEIVED)); } void onDecodedFrame(CubemapSource* source, u_int8_t type, size_t size, int face) { //stats.store(StatsUtils::Frame(type, size, face, StatsUtils::Frame::DECODED)); } void onColorConvertedFrame(CubemapSource* source, u_int8_t type, size_t size, int face) { stats.store(StatsUtils::Frame(type, size, face, StatsUtils::Frame::COLOR_CONVERTED)); } void onAddedFrameToCubemap(CubemapSource* source, int face) { //stats.store(StatsUtils::CubemapFace(face, StatsUtils::CubemapFace::ADDED)); } void setOnScheduledFrameInCubemap(CubemapSource* source, int face) { stats.store(StatsUtils::CubemapFace(face, StatsUtils::CubemapFace::SCHEDULED)); } void onDisplayedCubemapFace(Renderer* renderer, int face) { stats.store(StatsUtils::CubemapFace(face, StatsUtils::CubemapFace::DISPLAYED)); } void onDisplayedFrame(Renderer* renderer) { stats.store(StatsUtils::Cubemap()); } void onDidConnect(RTSPCubemapSourceClient* client, CubemapSource* cubemapSource) { H264CubemapSource* h264CubemapSource = dynamic_cast<H264CubemapSource*>(cubemapSource); if (h264CubemapSource) { h264CubemapSource->setOnReceivedNALU (boost::bind(&onReceivedNALU, _1, _2, _3, _4)); h264CubemapSource->setOnReceivedFrame (boost::bind(&onReceivedFrame, _1, _2, _3, _4)); h264CubemapSource->setOnDecodedFrame (boost::bind(&onDecodedFrame, _1, _2, _3, _4)); h264CubemapSource->setOnColorConvertedFrame (boost::bind(&onColorConvertedFrame, _1, _2, _3, _4)); h264CubemapSource->setOnAddedFrameToCubemap (boost::bind(&onAddedFrameToCubemap, _1, _2)); h264CubemapSource->setOnScheduledFrameInCubemap(boost::bind(&setOnScheduledFrameInCubemap, _1, _2)); } if (noDisplay) { cubemapSource->setOnNextCubemap(boost::bind(&onNextCubemap, _1, _2)); } else { renderer.setCubemapSource(cubemapSource); } } int main(int argc, char* argv[]) { noDisplay = false; std::string url = ""; std::string interfaceAddress = "0.0.0.0"; unsigned long bufferSize = DEFAULT_SINK_BUFFER_SIZE; bool matchStereoPairs = false; std::string configFilePath = "AlloPlayer.config"; std::initializer_list<CommandHandler::Command> generalCommands = { { "gamma-min", {"val"}, [](const std::vector<std::string>& values) { renderer.setGammaMin(boost::lexical_cast<float>(values[0])); } }, { "gamma-max", {"val"}, [](const std::vector<std::string>& values) { renderer.setGammaMax(boost::lexical_cast<float>(values[0])); } }, { "gamma-pow", {"val"}, [](const std::vector<std::string>& values) { renderer.setGammaPow(boost::lexical_cast<float>(values[0])); } }, { "for-rotation", {"deg_alpha", "deg_beta", "deg_gamma"}, [](const std::vector<std::string>& values) { renderer.setFORRotation(al::Vec3f(boost::lexical_cast<float>(values[0]) * RAD_DIV_DEG, boost::lexical_cast<float>(values[1]) * RAD_DIV_DEG, boost::lexical_cast<float>(values[2]) * RAD_DIV_DEG)); } }, { "for-angle", {"deg"}, [](const std::vector<std::string>& values) { renderer.setFORAngle(boost::lexical_cast<float>(values[0]) * RAD_DIV_DEG); } }, { "rotation", {"deg_alpha", "deg_beta", "deg_gamma"}, [](const std::vector<std::string>& values) { renderer.setRotation(al::Vec3f(boost::lexical_cast<float>(values[0]) * RAD_DIV_DEG, boost::lexical_cast<float>(values[1]) * RAD_DIV_DEG, boost::lexical_cast<float>(values[2]) * RAD_DIV_DEG)); } } }; std::initializer_list<CommandHandler::Command> commandLineOnlyCommands = { { "config", {"file_path"}, [&configFilePath](const std::vector<std::string>& values) { configFilePath = values[0]; } } }; std::initializer_list<CommandHandler::Command> configCommandLineOnlyCommands = { { "no-display", {}, [](const std::vector<std::string>& values) { noDisplay = true; } }, { "url", {"rtsp_url"}, [&url](const std::vector<std::string>& values) { url = values[0]; } }, { "interface-address", {"ip"}, [&interfaceAddress](const std::vector<std::string>& values) { interfaceAddress = values[0]; } }, { "buffer-size", {"bytes"}, [&bufferSize](const std::vector<std::string>& values) { bufferSize = boost::lexical_cast<unsigned long>(values[0]); } }, { "match-stereo-pairs", {}, [&matchStereoPairs](const std::vector<std::string>& values) { matchStereoPairs = true; } } }; std::initializer_list<CommandHandler::Command> consoleOnlyCommands = { { "stats", {}, [](const std::vector<std::string>& values) { boost::chrono::steady_clock::time_point now = boost::chrono::steady_clock::now(); std::cout << stats.summary(boost::chrono::duration_cast<boost::chrono::microseconds>(now - lastStatsTime), AlloReceiver::statValsMaker, AlloReceiver::postProcessorMaker, statsFormat); lastStatsTime = now; } }, { "quit", {}, [](const std::vector<std::string>& values) { exit(0); } }, { "info", {}, [&bufferSize, &url, &interfaceAddress, &matchStereoPairs, &configFilePath](const std::vector<std::string>& values) { al::Vec3f forRotation = renderer.getFORRotation() * DEG_DIV_RAD; al::Vec3f rotation = renderer.getRotation() * DEG_DIV_RAD; std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(1); std::cout << "Display: " << ((noDisplay) ? "no" : "yes") << std::endl; std::cout << "RTSP URL: " << url << std::endl; std::cout << "Interface address: " << interfaceAddress << std::endl; std::cout << "Buffer size: " << to_human_readable_byte_count(bufferSize, false, false) << std::endl; std::cout << "Match stereo pairs: " << ((matchStereoPairs) ? "yes" : "no") << std::endl; std::cout << "Gamma min: " << renderer.getGammaMin() << std::endl; std::cout << "Gamma max: " << renderer.getGammaMax() << std::endl; std::cout << "Gamma pow: " << renderer.getGammaPow() << std::endl; std::cout << "FOR angle: " << renderer.getFORAngle() * DEG_DIV_RAD << "°" << std::endl; std::cout << "FOR rotation: " << "α=" << forRotation[0] << "°\t" << "β=" << forRotation[1] << "°\t" << "γ=" << forRotation[2] << "°" << std::endl; std::cout << "Scene rotation: " << "α=" << rotation[0] << "°\t" << "β=" << rotation[1] << "°\t" << "γ=" << rotation[2] << "°" << std::endl; std::cout << "Config file: " << configFilePath << std::endl; } } }; CommandHandler consoleCommandHandler({generalCommands, consoleOnlyCommands}); CommandHandler configCommandHandler({generalCommands, configCommandLineOnlyCommands}); CommandHandler commandLineCommandHandler({generalCommands, configCommandLineOnlyCommands, commandLineOnlyCommands}); // The desired behaviour is that command line parameters override config file settings. // So, we would run the config file parser first and then the command line parser. // However, then we cannot pass the config file path as a command line parameter. // The solution here is to run the command line parser twice: // before and after the config file parser. auto commandLineParseResult = CommandLine::parseCommandLine(commandLineCommandHandler, argc, argv); if (!commandLineParseResult.first) { std::cerr << commandLineParseResult.second << std::endl; std::cerr << commandLineCommandHandler.getCommandHelpString(); abort(); } auto configParseResult = Config::parseConfigFile(configCommandHandler, configFilePath); if (!configParseResult.first) { std::cerr << configParseResult.second << std::endl; std::cerr << configCommandHandler.getCommandHelpString(); abort(); } commandLineParseResult = CommandLine::parseCommandLine(commandLineCommandHandler, argc, argv); if (!commandLineParseResult.first) { std::cerr << commandLineParseResult.second << std::endl; std::cerr << commandLineCommandHandler.getCommandHelpString(); abort(); } if (url == "") { std::cerr << "No URL specified." << std::endl; } Console console(consoleCommandHandler); console.start(); RTSPCubemapSourceClient* rtspClient = RTSPCubemapSourceClient::create(url.c_str(), bufferSize, AV_PIX_FMT_YUV420P, matchStereoPairs, interfaceAddress.c_str()); rtspClient->setOnDidConnect(boost::bind(&onDidConnect, _1, _2)); rtspClient->connect(); if (noDisplay) { std::cout << "network only" << std::endl; while(true) { boost::this_thread::yield(); } } else { renderer.setOnDisplayedCubemapFace(boost::bind(&onDisplayedCubemapFace, _1, _2)); renderer.setOnDisplayedFrame(boost::bind(&onDisplayedFrame, _1)); renderer.start(); // does not return } } <|endoftext|>
<commit_before>// This code is part of the project "Ligra: A Lightweight Graph Processing // Framework for Shared Memory", presented at Principles and Practice of // Parallel Programming, 2013. // Copyright (c) 2013 Julian Shun and Guy Blelloch // // 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. // Triangle counting code (assumes a symmetric graph, so pass the "-s" // flag). This is not optimized (no ordering heuristic is // used)--for optimized code, see "Multicore Triangle Computations // Without Tuning", ICDE 2015. #include "ligra.h" //assumes sorted neighbor lists template <class vertex> long countCommon(vertex& A, vertex& B, uintE a, uintE b) { uintT i=0,j=0,nA = A.getOutDegree(), nB = B.getOutDegree(); uintE* nghA = A.getOutNeighbors(), *nghB = B.getOutNeighbors(); long ans=0; while (i < nA && j < nB && nghA[i] < a && nghB[j] < b) { //count "directed" triangles if (nghA[i]==nghB[j]) i++, j++, ans++; else if (nghA[i] < nghB[j]) i++; else j++; } return ans; } template <class vertex> struct countF { //for edgeMap vertex* V; long* counts; countF(vertex* _V, long* _counts) : V(_V), counts(_counts) {} inline bool update (uintE s, uintE d) { if(s > d) //only count "directed" triangles writeAdd(&counts[s], countCommon<vertex>(V[s],V[d],s,d)); return 1; } inline bool updateAtomic (uintE s, uintE d) { if (s > d) //only count "directed" triangles writeAdd(&counts[s], countCommon<vertex>(V[s],V[d],s,d)); return 1; } inline bool cond (uintE d) { return cond_true(d); } //does nothing }; struct intLT { bool operator () (uintT a, uintT b) { return a < b; }; }; template <class vertex> struct initF { //for vertexMap to initial counts and sort neighbors for merging vertex* V; long* counts; initF(vertex* _V, long* _counts) : V(_V), counts(_counts) {} inline bool operator () (uintE i) { counts[i] = 0; quickSort(V[i].getOutNeighbors(),V[i].getOutDegree(),intLT()); return 1; } }; template <class vertex> void Compute(graph<vertex>& GA, commandLine P) { uintT n = GA.n; long* counts = newA(long,n); bool* frontier = newA(bool,n); {parallel_for(long i=0;i<n;i++) frontier[i] = 1;} vertexSubset Frontier(n,n,frontier); //frontier contains all vertices vertexMap(Frontier,initF<vertex>(GA.V,counts)); edgeMap(GA,Frontier,countF<vertex>(GA.V,counts)); long count = sequence::plusReduce(counts,n); cout << "triangle count = " << count << endl; Frontier.del(); free(counts); } <commit_msg>change<commit_after>// This code is part of the project "Ligra: A Lightweight Graph Processing // Framework for Shared Memory", presented at Principles and Practice of // Parallel Programming, 2013. // Copyright (c) 2013 Julian Shun and Guy Blelloch // // 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. // Triangle counting code (assumes a symmetric graph, so pass the "-s" // flag). This is not optimized (no ordering heuristic is used)--for // optimized code, see "Multicore Triangle Computations Without // Tuning", ICDE 2015. Currently only works with Ligra, and not // Ligra+. #include "ligra.h" //assumes sorted neighbor lists template <class vertex> long countCommon(vertex& A, vertex& B, uintE a, uintE b) { uintT i=0,j=0,nA = A.getOutDegree(), nB = B.getOutDegree(); uintE* nghA = A.getOutNeighbors(), *nghB = B.getOutNeighbors(); long ans=0; while (i < nA && j < nB && nghA[i] < a && nghB[j] < b) { //count "directed" triangles if (nghA[i]==nghB[j]) i++, j++, ans++; else if (nghA[i] < nghB[j]) i++; else j++; } return ans; } template <class vertex> struct countF { //for edgeMap vertex* V; long* counts; countF(vertex* _V, long* _counts) : V(_V), counts(_counts) {} inline bool update (uintE s, uintE d) { if(s > d) //only count "directed" triangles writeAdd(&counts[s], countCommon<vertex>(V[s],V[d],s,d)); return 1; } inline bool updateAtomic (uintE s, uintE d) { if (s > d) //only count "directed" triangles writeAdd(&counts[s], countCommon<vertex>(V[s],V[d],s,d)); return 1; } inline bool cond (uintE d) { return cond_true(d); } //does nothing }; struct intLT { bool operator () (uintT a, uintT b) { return a < b; }; }; template <class vertex> struct initF { //for vertexMap to initial counts and sort neighbors for merging vertex* V; long* counts; initF(vertex* _V, long* _counts) : V(_V), counts(_counts) {} inline bool operator () (uintE i) { counts[i] = 0; quickSort(V[i].getOutNeighbors(),V[i].getOutDegree(),intLT()); return 1; } }; template <class vertex> void Compute(graph<vertex>& GA, commandLine P) { uintT n = GA.n; long* counts = newA(long,n); bool* frontier = newA(bool,n); {parallel_for(long i=0;i<n;i++) frontier[i] = 1;} vertexSubset Frontier(n,n,frontier); //frontier contains all vertices vertexMap(Frontier,initF<vertex>(GA.V,counts)); edgeMap(GA,Frontier,countF<vertex>(GA.V,counts)); long count = sequence::plusReduce(counts,n); cout << "triangle count = " << count << endl; Frontier.del(); free(counts); } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <ros/callback_queue.h> #ifndef ROS_HELPERS_HPP #define ROS_HELPERS_HPP namespace ROSHelpers { inline Spin(const double loop_rate) { while (ros::ok()) { ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(loop_rate)); } } template <typename T> inline T GetParam(ros::NodeHandle& nh, const std::string& param_name, const T& default_val) { T param_val; if (nh.getParam(param_name, param_val)) { ROS_INFO_STREAM("Setting " << param_name << " to " << param_val); } else { param_val = default_val; ROS_WARN_STREAM(param_name << " not set! Using default of " << param_val); } return param_val; } template <typename T> inline T GetParam(ros::NodeHandle& nh, const std::string& param_name, T&& default_val) { T param_val; if (nh.getParam(param_name, param_val)) { ROS_INFO_STREAM("Setting " << param_name << " to " << param_val); } else { param_val = default_val; ROS_WARN_STREAM(param_name << " not set! Using default of " << param_val); } return param_val; } } #endif // ROS_HELPERS_HPP <commit_msg>Changed variable name.<commit_after>#include <ros/ros.h> #include <ros/callback_queue.h> #ifndef ROS_HELPERS_HPP #define ROS_HELPERS_HPP namespace ROSHelpers { inline Spin(const double loop_period) { while (ros::ok()) { ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(loop_period)); } } template <typename T> inline T GetParam(ros::NodeHandle& nh, const std::string& param_name, const T& default_val) { T param_val; if (nh.getParam(param_name, param_val)) { ROS_INFO_STREAM("Setting " << param_name << " to " << param_val); } else { param_val = default_val; ROS_WARN_STREAM(param_name << " not set! Using default of " << param_val); } return param_val; } template <typename T> inline T GetParam(ros::NodeHandle& nh, const std::string& param_name, T&& default_val) { T param_val; if (nh.getParam(param_name, param_val)) { ROS_INFO_STREAM("Setting " << param_name << " to " << param_val); } else { param_val = default_val; ROS_WARN_STREAM(param_name << " not set! Using default of " << param_val); } return param_val; } } #endif // ROS_HELPERS_HPP <|endoftext|>
<commit_before>/*- * Copyright (c) 2011 Benjamin Close <Benjamin.Close@clearchain.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ // include system headers #include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> // include openGL headers #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <wcl/Exception.h> #include <wcl/camera/CameraFactory.h> using namespace std; using namespace wcl; static Camera *cam; static unsigned int pixelx=-1,pixely=-1; void usage() { printf("selector [devicenode]\n" "Selector takes a image from a camera and displays it to the screen\n" "Once displayed the user can select a pixel and find out it's x,y & other details\n" "\n" "devicenode - the device to use, if not specified the first available camera will be used\n"); } /** * Initialise OpenGL */ GLvoid init() { unsigned char* data; glShadeModel(GL_SMOOTH); glClearColor(0,0,0,0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)]; // create a texture for the image... glTexImage2D(GL_TEXTURE_2D, //target 0, //level of detail 3, //colour components cam->getActiveConfiguration().width, //width cam->getActiveConfiguration().height, //height 0, //border GL_RGB, //image format GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); delete data; } /** * Constantly fetch a new image from the camera to display */ GLvoid idle() { glutPostRedisplay(); } /** * Display Loop. */ GLvoid display() { static int flashstate= 0; glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); const unsigned char* frame = cam->getFrame(Camera::RGB8); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cam->getActiveConfiguration().width, cam->getActiveConfiguration().height, GL_RGB, GL_UNSIGNED_BYTE, frame); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1,0,0); glBegin(GL_QUADS); glTexCoord2f(0,1); glVertex2f(0,0); glTexCoord2f(1,1); glVertex2f(1,0); glTexCoord2f(1,0); glVertex2f(1,1); glTexCoord2f(0,0); glVertex2f(0,1); glEnd(); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,cam->getActiveConfiguration().width,cam->getActiveConfiguration().height,0, 0, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // If a pixel is selected flash the pixel; if(pixelx >= 0 ){ if( flashstate ){ glColor3f(1.0,0.0,0.0); } else { glColor3f(1.0, 1.0, 1.0); } flashstate = !flashstate; glPointSize(2.0); glBegin(GL_POINTS); glVertex2f(pixelx, pixely); glEnd(); } glFlush(); glutSwapBuffers(); // print out any opengl errors to the console GLenum error = glGetError(); if (error != GL_NO_ERROR) { cout << gluErrorString(error) << endl; } } /** * This doesn't do what it is supposed to do! */ GLvoid reshape(int width, int height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1,0,1); glViewport(0,0, (GLsizei)width, (GLsizei)height); glMatrixMode(GL_MODELVIEW); } void keyboard(unsigned char key, int w, int h) { if(key==27) exit(EXIT_SUCCESS); } void mouse(int button, int state, int x, int y) { unsigned char buffer[3]; if(state==1){ pixelx = x; pixely = y; glReadPixels(x,y,1,1,GL_RGB,GL_UNSIGNED_BYTE,&buffer); //these conversion formulas come from wikipedia float r = buffer[0]; float g = buffer[1]; float b = buffer[2]; const float wR = 0.299; const float wG = 0.114; const float wB = 0.587; const float uMax = 0.436; const float vMax = 0.615; float Y = wR* + wG*g + wB*b; float U = uMax * ((b - y)/(1-wB)); float V = vMax * ((r * - y)/(1-wR)); // Display information to console printf("--------------------------\n" "Point: %d x, %d y\n" "RGB: r %f, g %f, b %f\n" "YUV: y %f, u %f, v %f\n", x,y, r,g,b, Y,U,V ); } } int main(int argc, char** argv) { if( argc > 2 || (argc == 2 && strcasecmp(argv[1],"-h") == 0)){ usage(); return 1; } try { std::vector<Camera *> cameras = CameraFactory::getCameras(); if( cameras.size() == 0 ){ cout << "No Camera's found" << endl; return 0; } if( argc ==2 ){ cam = CameraFactory::getCamera(argv[1]); } else { cam = CameraFactory::getCamera(); } if( cam == NULL ){ cout << "Camera not found" << endl; return 1; } // Create GLUT window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height); glutCreateWindow(argv[0]); init(); // register callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutIdleFunc(idle); // GO! glutMainLoop(); } catch (Exception &e) { cout << "Exception Occured: " << e.what() << endl; return 1; } cam->shutdown(); delete cam; return 0; } <commit_msg>examples: Report OpenGL Coordinates as well as camera coordinates<commit_after>/*- * Copyright (c) 2011 Benjamin Close <Benjamin.Close@clearchain.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ // include system headers #include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> // include openGL headers #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <wcl/Exception.h> #include <wcl/camera/CameraFactory.h> using namespace std; using namespace wcl; static Camera *cam; static unsigned int pixelx=-1,pixely=-1; void usage() { printf("selector [devicenode]\n" "Selector takes a image from a camera and displays it to the screen\n" "Once displayed the user can select a pixel and find out it's x,y & other details\n" "\n" "devicenode - the device to use, if not specified the first available camera will be used\n"); } /** * Initialise OpenGL */ GLvoid init() { unsigned char* data; glShadeModel(GL_SMOOTH); glClearColor(0,0,0,0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)]; // create a texture for the image... glTexImage2D(GL_TEXTURE_2D, //target 0, //level of detail 3, //colour components cam->getActiveConfiguration().width, //width cam->getActiveConfiguration().height, //height 0, //border GL_RGB, //image format GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); delete data; } /** * Constantly fetch a new image from the camera to display */ GLvoid idle() { glutPostRedisplay(); } /** * Display Loop. */ GLvoid display() { static int flashstate= 0; glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); const unsigned char* frame = cam->getFrame(Camera::RGB8); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cam->getActiveConfiguration().width, cam->getActiveConfiguration().height, GL_RGB, GL_UNSIGNED_BYTE, frame); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1,0,0); glBegin(GL_QUADS); glTexCoord2f(0,1); glVertex2f(0,0); glTexCoord2f(1,1); glVertex2f(1,0); glTexCoord2f(1,0); glVertex2f(1,1); glTexCoord2f(0,0); glVertex2f(0,1); glEnd(); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,cam->getActiveConfiguration().width,cam->getActiveConfiguration().height,0, 0, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // If a pixel is selected flash the pixel; if(pixelx >= 0 ){ if( flashstate ){ glColor3f(1.0,0.0,0.0); } else { glColor3f(1.0, 1.0, 1.0); } flashstate = !flashstate; glPointSize(2.0); glBegin(GL_POINTS); glVertex2f(pixelx, pixely); glEnd(); } glFlush(); glutSwapBuffers(); // print out any opengl errors to the console GLenum error = glGetError(); if (error != GL_NO_ERROR) { cout << gluErrorString(error) << endl; } } /** * This doesn't do what it is supposed to do! */ GLvoid reshape(int width, int height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1,0,1); glViewport(0,0, (GLsizei)width, (GLsizei)height); glMatrixMode(GL_MODELVIEW); } void keyboard(unsigned char key, int w, int h) { if(key==27) exit(EXIT_SUCCESS); } void mouse(int button, int state, int x, int y) { unsigned char buffer[3]; if(state==1){ pixelx = x; pixely = y; glReadPixels(x,y,1,1,GL_RGB,GL_UNSIGNED_BYTE,&buffer); //these conversion formulas come from wikipedia float r = buffer[0]; float g = buffer[1]; float b = buffer[2]; const float wR = 0.299; const float wG = 0.114; const float wB = 0.587; const float uMax = 0.436; const float vMax = 0.615; float Y = wR* + wG*g + wB*b; float U = uMax * ((b - y)/(1-wB)); float V = vMax * ((r * - y)/(1-wR)); // Display information to console printf("--------------------------\n" "Point: %d x, %d y (OpenGL: %d x, %d y)\n" "RGB: r %f, g %f, b %f\n" "YUV: y %f, u %f, v %f\n", x,y, x, cam->getActiveConfiguration().height-y, r,g,b, Y,U,V ); } } int main(int argc, char** argv) { if( argc > 2 || (argc == 2 && strcasecmp(argv[1],"-h") == 0)){ usage(); return 1; } try { std::vector<Camera *> cameras = CameraFactory::getCameras(); if( cameras.size() == 0 ){ cout << "No Camera's found" << endl; return 0; } if( argc ==2 ){ cam = CameraFactory::getCamera(argv[1]); } else { cam = CameraFactory::getCamera(); } if( cam == NULL ){ cout << "Camera not found" << endl; return 1; } // Create GLUT window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height); glutCreateWindow(argv[0]); init(); // register callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutIdleFunc(idle); // GO! glutMainLoop(); } catch (Exception &e) { cout << "Exception Occured: " << e.what() << endl; return 1; } cam->shutdown(); delete cam; return 0; } <|endoftext|>
<commit_before>#include "pdfium_ruby.h" void Init_pdfium_ruby (void) { VALUE rb_PDFium = rb_define_module("PDFium"); // Define `Document` and `Page` classes Define_Document(); Define_Page(); Define_PageSet(); } <commit_msg>Fix main file's init function for C++, and comment out unimplemented functions.<commit_after>#include "pdfium_ruby.h" extern "C" void Init_pdfium_ruby (void) { // Define `PDFium` module as a namespace for all of our other objects VALUE rb_PDFium = rb_define_module("PDFium"); // Define `Document` and `Page` classes Define_Document(); //Define_Page(); //Define_PageSet(); } <|endoftext|>
<commit_before>/* * Scene.hpp * * Created on: 24.01.2015 * Author: sartz */ #pragma once #include "GameObjectComponent.hpp" #include <SFML/System.hpp> #include <vector> namespace sf{ class Sprite; } class GameObject { public: sf::Sprite * mySprite = 0; const sf::Vector2f& getPosition() const; void setPosition(int x, int y); //GameObject() {}; virtual void update(sf::Time deltaTime) = 0; virtual ~GameObject() {}; /* public: int xPos; int yPos; GameObject(); virtual ~GameObject(); void update(sf::Time deltaT); template<class t> t addComponent(){ if (componentExits<t>()) { return 0; } t* result = new t(this); components.insert(result); return result; } template<class t> bool componentExits(){ int size = components.size(); for(int i = 0;i < size;++i) { if (dynamic_cast<t*>(components[i])) { return true; } } return false; } template<class t> t getComponent(){ int size = components.size(); for(int i = 0;i < size;++i) { if (dynamic_cast<t*>(components[i])) { return components[i]; } } return 0; } template<class t> t removeComponent(){ std::vector<GameObjectComponent*>::iterator it = components.begin(); for( ; it != components.end(); it++) { if (dynamic_cast<t*>(*it)) { it = components.erase(it); } } } private: std::vector<GameObjectComponent*> components;*/ }; <commit_msg>hotfix 2 :)<commit_after>/* * Scene.hpp * * Created on: 24.01.2015 * Author: sartz */ #pragma once #include <SFML/System.hpp> #include <vector> namespace sf{ class Sprite; } class GameObject { public: sf::Sprite * mySprite = 0; const sf::Vector2f& getPosition() const; void setPosition(int x, int y); //GameObject() {}; virtual void update(sf::Time deltaTime) = 0; virtual ~GameObject() {}; /* public: int xPos; int yPos; GameObject(); virtual ~GameObject(); void update(sf::Time deltaT); template<class t> t addComponent(){ if (componentExits<t>()) { return 0; } t* result = new t(this); components.insert(result); return result; } template<class t> bool componentExits(){ int size = components.size(); for(int i = 0;i < size;++i) { if (dynamic_cast<t*>(components[i])) { return true; } } return false; } template<class t> t getComponent(){ int size = components.size(); for(int i = 0;i < size;++i) { if (dynamic_cast<t*>(components[i])) { return components[i]; } } return 0; } template<class t> t removeComponent(){ std::vector<GameObjectComponent*>::iterator it = components.begin(); for( ; it != components.end(); it++) { if (dynamic_cast<t*>(*it)) { it = components.erase(it); } } } private: std::vector<GameObjectComponent*> components;*/ }; <|endoftext|>
<commit_before>// Copyright (c) 2014, Salesforce.com, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // - Neither the name of Salesforce.com nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <distributions/common.hpp> #include <distributions/clustering.hpp> #include <distributions/models/dd.hpp> #include <distributions/models/dpd.hpp> #include <distributions/models/nich.hpp> #include <distributions/models/gp.hpp> #include <distributions/io/schema.pb.h> namespace distributions { namespace protobuf { using namespace ::protobuf::distributions; } //---------------------------------------------------------------------------- // Clustering // FIXME g++ fails if these are made template<count_t> inline void clustering_load ( typename Clustering<int>::PitmanYor & model, const protobuf::Clustering::PitmanYor & message) { model.alpha = message.alpha(); model.d = message.d(); } inline void clustering_load ( typename Clustering<int>::PitmanYor & model, const protobuf::Clustering & message) { clustering_load(model, message.pitman_yor()); } inline void clustering_load ( typename Clustering<int>::LowEntropy & model, const protobuf::Clustering::LowEntropy & message) { model.dataset_size = message.dataset_size(); } template<class count_t> inline void clustering_load ( typename Clustering<int>::LowEntropy & model, const protobuf::Clustering & message) { clustering_load(model, message.low_entropy()); } //---------------------------------------------------------------------------- // Models template<int max_dim> inline void model_load ( DirichletDiscrete<max_dim> & model, const protobuf::DirichletDiscrete & message) { model.dim = message.alphas_size(); DIST_ASSERT(model.dim <= max_dim, "dim is too large: " << model.dim); for (size_t i = 0; i < model.dim; ++i) { model.alphas[i] = message.alphas(i); } } inline void model_load ( DirichletProcessDiscrete & model, const protobuf::DirichletProcessDiscrete & message) { model.gamma = message.gamma(); model.alpha = message.alpha(); model.betas.resize(message.betas_size()); double beta_sum = 0; for (size_t i = 0; i < model.betas.size(); ++i) { beta_sum += model.betas[i] = message.betas(i); } model.beta0 = 1 - beta_sum; } inline void model_load ( GammaPoisson & model, const protobuf::GammaPoisson & message) { model.alpha = message.alpha(); model.inv_beta = message.inv_beta(); } inline void model_load ( NormalInverseChiSq & model, const protobuf::NormalInverseChiSq & message) { model.mu = message.mu(); model.kappa = message.kappa(); model.sigmasq = message.sigmasq(); model.nu = message.nu(); } //---------------------------------------------------------------------------- // Groups template<int max_dim> inline void group_load ( const DirichletDiscrete<max_dim> & model, typename DirichletDiscrete<max_dim>::Group & group, const protobuf::DirichletDiscrete::Group & message) { DIST_ASSERT1( message.counts_size() == model.dim, "bad group message dim: " << message.counts_size()); group.counts_sum = 0; for (size_t i = 0; i < model.dim; ++i) { group.counts_sum += group.counts[i] = message.counts(i); } } template<int max_dim> inline void group_dump ( const DirichletDiscrete<max_dim> & model, const typename DirichletDiscrete<max_dim>::Group & group, protobuf::DirichletDiscrete::Group & message) { message.Clear(); auto & counts = * message.mutable_counts(); for (size_t i = 0; i < model.dim; ++i) { counts.Add(group.counts[i]); } } inline void group_load ( const DirichletProcessDiscrete &, DirichletProcessDiscrete::Group & group, const protobuf::DirichletProcessDiscrete::Group & message) { DIST_ASSERT1( message.keys_size() == message.values_size(), "message keys_size != vals_size"); group.counts.clear(); for (size_t i = 0, size = message.keys_size(); i < size; ++i) { group.counts.add(message.keys(i), message.values(i)); } } inline void group_dump ( const DirichletProcessDiscrete &, const DirichletProcessDiscrete::Group & group, protobuf::DirichletProcessDiscrete::Group & message) { message.Clear(); auto & keys = * message.mutable_keys(); auto & values = * message.mutable_values(); for (const auto & pair : group.counts) { keys.Add(pair.first); values.Add(pair.second); } } inline void group_load ( const GammaPoisson &, GammaPoisson::Group & group, const protobuf::GammaPoisson::Group & message) { group.count = message.count(); group.sum = message.sum(); group.log_prod = message.log_prod(); } inline void group_dump ( const GammaPoisson &, const GammaPoisson::Group & group, protobuf::GammaPoisson::Group & message) { message.set_count(group.count); message.set_sum(group.sum); message.set_log_prod(group.log_prod); } inline void group_load ( const NormalInverseChiSq &, NormalInverseChiSq::Group & group, const protobuf::NormalInverseChiSq::Group & message) { group.count = message.count(); group.mean = message.mean(); group.count_times_variance = message.count_times_variance(); } inline void group_dump ( const NormalInverseChiSq &, const NormalInverseChiSq::Group & group, protobuf::NormalInverseChiSq::Group & message) { message.set_count(group.count); message.set_mean(group.mean); message.set_count_times_variance(group.count_times_variance); } } // namespace distributions <commit_msg>Fix bug in group_load<commit_after>// Copyright (c) 2014, Salesforce.com, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // - Neither the name of Salesforce.com nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <distributions/common.hpp> #include <distributions/clustering.hpp> #include <distributions/models/dd.hpp> #include <distributions/models/dpd.hpp> #include <distributions/models/nich.hpp> #include <distributions/models/gp.hpp> #include <distributions/io/schema.pb.h> namespace distributions { namespace protobuf { using namespace ::protobuf::distributions; } //---------------------------------------------------------------------------- // Clustering // FIXME g++ fails if these are made template<count_t> inline void clustering_load ( typename Clustering<int>::PitmanYor & model, const protobuf::Clustering::PitmanYor & message) { model.alpha = message.alpha(); model.d = message.d(); } inline void clustering_load ( typename Clustering<int>::PitmanYor & model, const protobuf::Clustering & message) { clustering_load(model, message.pitman_yor()); } inline void clustering_load ( typename Clustering<int>::LowEntropy & model, const protobuf::Clustering::LowEntropy & message) { model.dataset_size = message.dataset_size(); } template<class count_t> inline void clustering_load ( typename Clustering<int>::LowEntropy & model, const protobuf::Clustering & message) { clustering_load(model, message.low_entropy()); } //---------------------------------------------------------------------------- // Models template<int max_dim> inline void model_load ( DirichletDiscrete<max_dim> & model, const protobuf::DirichletDiscrete & message) { model.dim = message.alphas_size(); DIST_ASSERT(model.dim <= max_dim, "dim is too large: " << model.dim); for (size_t i = 0; i < model.dim; ++i) { model.alphas[i] = message.alphas(i); } } inline void model_load ( DirichletProcessDiscrete & model, const protobuf::DirichletProcessDiscrete & message) { model.gamma = message.gamma(); model.alpha = message.alpha(); model.betas.resize(message.betas_size()); double beta_sum = 0; for (size_t i = 0; i < model.betas.size(); ++i) { beta_sum += model.betas[i] = message.betas(i); } model.beta0 = 1 - beta_sum; } inline void model_load ( GammaPoisson & model, const protobuf::GammaPoisson & message) { model.alpha = message.alpha(); model.inv_beta = message.inv_beta(); } inline void model_load ( NormalInverseChiSq & model, const protobuf::NormalInverseChiSq & message) { model.mu = message.mu(); model.kappa = message.kappa(); model.sigmasq = message.sigmasq(); model.nu = message.nu(); } //---------------------------------------------------------------------------- // Groups template<int max_dim> inline void group_load ( const DirichletDiscrete<max_dim> & model, typename DirichletDiscrete<max_dim>::Group & group, const protobuf::DirichletDiscrete::Group & message) { DIST_ASSERT1( message.counts_size() == model.dim, "bad group message dim: " << message.counts_size()); group.count_sum = 0; for (size_t i = 0; i < model.dim; ++i) { group.count_sum += group.counts[i] = message.counts(i); } } template<int max_dim> inline void group_dump ( const DirichletDiscrete<max_dim> & model, const typename DirichletDiscrete<max_dim>::Group & group, protobuf::DirichletDiscrete::Group & message) { message.Clear(); auto & counts = * message.mutable_counts(); for (size_t i = 0; i < model.dim; ++i) { counts.Add(group.counts[i]); } } inline void group_load ( const DirichletProcessDiscrete &, DirichletProcessDiscrete::Group & group, const protobuf::DirichletProcessDiscrete::Group & message) { DIST_ASSERT1( message.keys_size() == message.values_size(), "message keys_size != vals_size"); group.counts.clear(); for (size_t i = 0, size = message.keys_size(); i < size; ++i) { group.counts.add(message.keys(i), message.values(i)); } } inline void group_dump ( const DirichletProcessDiscrete &, const DirichletProcessDiscrete::Group & group, protobuf::DirichletProcessDiscrete::Group & message) { message.Clear(); auto & keys = * message.mutable_keys(); auto & values = * message.mutable_values(); for (const auto & pair : group.counts) { keys.Add(pair.first); values.Add(pair.second); } } inline void group_load ( const GammaPoisson &, GammaPoisson::Group & group, const protobuf::GammaPoisson::Group & message) { group.count = message.count(); group.sum = message.sum(); group.log_prod = message.log_prod(); } inline void group_dump ( const GammaPoisson &, const GammaPoisson::Group & group, protobuf::GammaPoisson::Group & message) { message.set_count(group.count); message.set_sum(group.sum); message.set_log_prod(group.log_prod); } inline void group_load ( const NormalInverseChiSq &, NormalInverseChiSq::Group & group, const protobuf::NormalInverseChiSq::Group & message) { group.count = message.count(); group.mean = message.mean(); group.count_times_variance = message.count_times_variance(); } inline void group_dump ( const NormalInverseChiSq &, const NormalInverseChiSq::Group & group, protobuf::NormalInverseChiSq::Group & message) { message.set_count(group.count); message.set_mean(group.mean); message.set_count_times_variance(group.count_times_variance); } } // namespace distributions <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_EVALUATE_INTO_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_EVALUATE_INTO_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/kernel_generator/operation.hpp> #include <stan/math/opencl/kernel_generator/as_operation.hpp> #include <stan/math/opencl/kernel_generator/is_valid_expression.hpp> #include <cl.hpp> #include <utility> #include <string> #include <set> namespace stan { namespace math { template <typename Derived, typename ReturnScalar> template <typename T_lhs> void operation<Derived, ReturnScalar>::evaluate_into(T_lhs&& lhs) const { using enable = enable_if_all_valid_expressions<T_lhs>; using cache = operation<Derived, ReturnScalar>::cache<T_lhs>; auto lhs_expression = as_operation(std::forward<T_lhs>(lhs)); int n_rows = derived().rows(); int n_cols = derived().cols(); const char* function = "evaluate_into"; if (n_rows != dynamic) { check_size_match(function, "Rows of ", "*this", n_rows, "rows of ", "lhs_expression", lhs_expression.rows()); } if (n_cols != dynamic) { check_size_match(function, "Columns of ", "*this", n_cols, "columns of ", "lhs_expression", lhs_expression.cols()); } try { std::set<int> generated; if (cache::kernel() == NULL) { name_generator ng; kernel_parts parts = derived().generate(generated, ng, "i", "j"); kernel_parts out_parts = lhs_expression.generate_lhs(generated, ng, "i", "j"); std::string src = "kernel void calculate(" + parts.args + out_parts.args.substr(0, out_parts.args.size() - 2) + "){\n" "int i = get_global_id(0);" "int j = get_global_id(1);\n" + parts.body + out_parts.body + " = " + var_name + ";}"; auto opts = opencl_context.base_opts(); cache::kernel = opencl_kernels::compile_kernel( "calculate", {view_kernel_helpers, src.c_str()}, opts); generated.clear(); } int arg_num = 0; derived().set_args(generated, cache::kernel, arg_num); lhs_expression.set_args(generated, cache::kernel, arg_num); cl::Event e; opencl_context.queue().enqueueNDRangeKernel(cache::kernel, cl::NullRange, cl::NDRange(n_rows, n_cols), cl::NullRange, nullptr, &e); derived().add_event(e); lhs_expression.add_write_event(e); } catch (cl::Error e) { check_opencl_error("operation.evaluate_into", e); } } } // namespace math } // namespace stan #endif #endif <commit_msg>split long line2<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_EVALUATE_INTO_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_EVALUATE_INTO_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/kernel_generator/operation.hpp> #include <stan/math/opencl/kernel_generator/as_operation.hpp> #include <stan/math/opencl/kernel_generator/is_valid_expression.hpp> #include <cl.hpp> #include <utility> #include <string> #include <set> namespace stan { namespace math { template <typename Derived, typename ReturnScalar> template <typename T_lhs> void operation<Derived, ReturnScalar>::evaluate_into(T_lhs&& lhs) const { using enable = enable_if_all_valid_expressions<T_lhs>; using cache = operation<Derived, ReturnScalar>::cache<T_lhs>; auto lhs_expression = as_operation(std::forward<T_lhs>(lhs)); int n_rows = derived().rows(); int n_cols = derived().cols(); const char* function = "evaluate_into"; if (n_rows != dynamic) { check_size_match(function, "Rows of ", "*this", n_rows, "rows of ", "lhs_expression", lhs_expression.rows()); } if (n_cols != dynamic) { check_size_match(function, "Columns of ", "*this", n_cols, "columns of ", "lhs_expression", lhs_expression.cols()); } try { std::set<int> generated; if (cache::kernel() == NULL) { name_generator ng; kernel_parts parts = derived().generate(generated, ng, "i", "j"); kernel_parts out_parts = lhs_expression.generate_lhs(generated, ng, "i", "j"); std::string src = "kernel void calculate(" + parts.args + out_parts.args.substr(0, out_parts.args.size() - 2) + "){\n" "int i = get_global_id(0);" "int j = get_global_id(1);\n" + parts.body + out_parts.body + " = " + var_name + ";}"; auto opts = opencl_context.base_opts(); cache::kernel = opencl_kernels::compile_kernel( "calculate", {view_kernel_helpers, src.c_str()}, opts); generated.clear(); } int arg_num = 0; derived().set_args(generated, cache::kernel, arg_num); lhs_expression.set_args(generated, cache::kernel, arg_num); cl::Event e; opencl_context.queue().enqueueNDRangeKernel(cache::kernel, cl::NullRange, cl::NDRange(n_rows, n_cols), cl::NullRange, nullptr, &e); derived().add_event(e); lhs_expression.add_write_event(e); } catch (cl::Error e) { check_opencl_error("operation.evaluate_into", e); } } } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>#pragma once #include "params.hpp" #include "math/tune.hpp" #include "math/momentum.hpp" namespace nano { /// /// \brief hyper-parameter tuning for stochastic optimizers. /// inline auto make_alpha0s() { return nano::make_finite_space(1e-4, 1e-3, 1e-2, 1e-1, 1e+0); } inline auto make_decays() { return nano::make_finite_space(0.10, 0.25, 0.50, 0.75, 1.00); } inline auto make_momenta() { return nano::make_finite_space(0.10, 0.25, 0.50, 0.90, 0.95); } inline auto make_epsilons() { return nano::make_finite_space(1e-4, 1e-6, 1e-8); } /// /// \brief stochastic optimization loop. /// template < typename tproblem, ///< optimization problem typename toperator ///< operator to call for each optimization iteration > auto stoch_loop( const tproblem& problem, const stoch_params_t<tproblem>& params, const typename stoch_params_t<tproblem>::tstate& istate, const toperator& op, const typename stoch_params_t<tproblem>::tconfig& config) { // current state auto cstate = istate; // average state auto astate = istate; const typename tproblem::tscalar momentum = 0.90; momentum_vector_t<typename tproblem::tvector> xavg(momentum, istate.x.size()); // best state auto bstate = istate; // for each epoch ... for (std::size_t e = 0, k = 1; e < params.m_epochs; ++ e) { // for each iteration ... for (std::size_t i = 0; i < params.m_epoch_size; ++ i, ++ k) { op(cstate, k); xavg.update(cstate.x); } // log the current state & check the stopping criteria astate.update(problem, xavg.value()); if (params.tuning()) { astate.f = params.tlog(astate, config); } else if (!params.ulog(astate, config)) { break; } // update the best state bstate.update(astate); } // OK return bstate; } } <commit_msg>fix tuning of stochastic optimizers (bstate was not updated correctly)<commit_after>#pragma once #include "params.hpp" #include "math/tune.hpp" #include "math/momentum.hpp" namespace nano { /// /// \brief hyper-parameter tuning for stochastic optimizers. /// inline auto make_alpha0s() { return nano::make_finite_space(1e-4, 1e-3, 1e-2, 1e-1, 1e+0); } inline auto make_decays() { return nano::make_log10_space(-3.0, -1.0, 0.1); } inline auto make_momenta() { return nano::make_finite_space(0.10, 0.25, 0.50, 0.90, 0.95); } inline auto make_epsilons() { return nano::make_finite_space(1e-4, 1e-6, 1e-8); } /// /// \brief stochastic optimization loop. /// template < typename tproblem, ///< optimization problem typename toperator ///< operator to call for each optimization iteration > auto stoch_loop( const tproblem& problem, const stoch_params_t<tproblem>& params, const typename stoch_params_t<tproblem>::tstate& istate, const toperator& op, const typename stoch_params_t<tproblem>::tconfig& config) { // current state auto cstate = istate; // average state auto astate = istate; const typename tproblem::tscalar momentum = 0.90; momentum_vector_t<typename tproblem::tvector> xavg(momentum, istate.x.size()); // best state auto bstate = istate; bstate.f = std::numeric_limits<typename tproblem::tscalar>::max(); // for each epoch ... for (std::size_t e = 0, k = 1; e < params.m_epochs; ++ e) { // for each iteration ... for (std::size_t i = 0; i < params.m_epoch_size; ++ i, ++ k) { op(cstate, k); xavg.update(cstate.x); } // log the current state & check the stopping criteria astate.update(problem, xavg.value()); if (params.tuning()) { astate.f = params.tlog(astate, config); } else if (!params.ulog(astate, config)) { break; } // update the best state bstate.update(astate); } // OK return bstate; } } <|endoftext|>
<commit_before><commit_msg>trying to fix teleport bug<commit_after><|endoftext|>
<commit_before>// Throttle /tf bandwidth // Author: Max Schwarz <max.schwarz@uni-bonn.de> #include <ros/init.h> #include <ros/node_handle.h> #include <tf/transform_listener.h> #include <boost/foreach.hpp> boost::scoped_ptr<tf::TransformListener> g_tf; ros::Publisher pub; void sendTransforms() { std::vector<std::string> frames; g_tf->getFrameStrings(frames); tf::tfMessage msg; msg.transforms.reserve(frames.size()); ros::Time now = ros::Time::now(); BOOST_FOREACH(std::string frame, frames) { std::string parentFrame; if(!g_tf->getParent(frame, ros::Time(0), parentFrame)) continue; tf::StampedTransform transform; try { g_tf->lookupTransform( parentFrame, frame, ros::Time(0), transform ); } catch(tf::TransformException&) { continue; } geometry_msgs::TransformStamped m; tf::transformStampedTFToMsg(transform, m); msg.transforms.push_back(m); } pub.publish(msg); } int main(int argc, char** argv) { ros::init(argc, argv, "tf_throttle"); ros::NodeHandle nh("~"); g_tf.reset(new tf::TransformListener(nh, ros::Duration(10.0))); double rate; nh.param("rate", rate, 4.0); ros::Timer timer = nh.createTimer( ros::Duration(1.0 / rate), boost::bind(&sendTransforms) ); pub = nh.advertise<tf::tfMessage>("tf", 1); ros::spin(); return 0; } <commit_msg>tf_throttle: use tf2 message type<commit_after>// Throttle /tf bandwidth // Author: Max Schwarz <max.schwarz@uni-bonn.de> #include <ros/init.h> #include <ros/node_handle.h> #include <tf/transform_listener.h> #include <tf2_msgs/TFMessage.h> #include <boost/foreach.hpp> boost::scoped_ptr<tf::TransformListener> g_tf; ros::Publisher pub; void sendTransforms() { std::vector<std::string> frames; g_tf->getFrameStrings(frames); tf2_msgs::TFMessage msg; msg.transforms.reserve(frames.size()); ros::Time now = ros::Time::now(); BOOST_FOREACH(std::string frame, frames) { std::string parentFrame; if(!g_tf->getParent(frame, ros::Time(0), parentFrame)) continue; tf::StampedTransform transform; try { g_tf->lookupTransform( parentFrame, frame, ros::Time(0), transform ); } catch(tf::TransformException&) { continue; } geometry_msgs::TransformStamped m; tf::transformStampedTFToMsg(transform, m); msg.transforms.push_back(m); } pub.publish(msg); } int main(int argc, char** argv) { ros::init(argc, argv, "tf_throttle"); ros::NodeHandle nh("~"); g_tf.reset(new tf::TransformListener(nh, ros::Duration(10.0))); double rate; nh.param("rate", rate, 4.0); ros::Timer timer = nh.createTimer( ros::Duration(1.0 / rate), boost::bind(&sendTransforms) ); pub = nh.advertise<tf2_msgs::TFMessage>("tf", 1); ros::spin(); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2017, Vadim Malyshev, lboss75@gmail.com All rights reserved */ #include "stdafx.h" #include "vds_cmd_app.h" #include "http_router.h" #include "user_manager.h" #include "tcp_network_socket.h" #include "http_request.h" #include "http_serializer.h" #include "http_client.h" #include "http_response.h" #include "http_multipart_request.h" #include "http_mimetype.h" #include <iomanip> namespace vds { class http_multipart_request; } vds::vds_cmd_app::vds_cmd_app() : file_upload_cmd_set_("Upload file", "Upload file on the network", "upload", "file"), file_download_cmd_set_("Download file", "Download file from the network", "download", "file"), channel_list_cmd_set_("Channel list", "List user channels", "list", "channel"), channel_create_cmd_set_("Channel create", "Create new channel", "create", "channel"), user_login_( "l", "login", "Login", "User login"), user_password_( "p", "password", "Password", "User password"), server_( "s", "server", "Server URL", "Server URL to connect"), channel_id_( "c", "channel", "Channel ID", "Channel identifier to send message"), message_( "m", "message", "Message", "Message"), attachment_( "a", "attachment", "File(s) names", "Comma separated file names"), output_folder_( "o", "output", "output folder", "Folder to store files"), output_format_( "f", "format", "Output format", "Output format (json)" ), channel_name_( "cn", "channel-name", "Channel name", "Name of channel"), channel_type_( "ct", "channel-type", "Channel type", "Type of channel") { } void vds::vds_cmd_app::main(const service_provider * sp) { if (this->current_command_set_ == &this->file_upload_cmd_set_) { const auto session = this->login(sp); this->upload_file(sp, session); } else if(this->current_command_set_ == &this->channel_list_cmd_set_) { const auto session = this->login(sp); this->channel_list(sp, session); } else if (this->current_command_set_ == &this->channel_create_cmd_set_) { const auto session = this->login(sp); this->channel_create(sp, session); } } void vds::vds_cmd_app::register_services(vds::service_registrator& registrator) { base_class::register_services(registrator); registrator.add(this->mt_service_); registrator.add(this->task_manager_); registrator.add(this->network_service_); } void vds::vds_cmd_app::register_command_line(command_line & cmd_line) { base_class::register_command_line(cmd_line); cmd_line.add_command_set(this->file_upload_cmd_set_); this->file_upload_cmd_set_.required(this->user_login_); this->file_upload_cmd_set_.required(this->user_password_); this->file_upload_cmd_set_.optional(this->server_); this->file_upload_cmd_set_.required(this->channel_id_); this->file_upload_cmd_set_.optional(this->message_); this->file_upload_cmd_set_.required(this->attachment_); this->file_upload_cmd_set_.optional(this->output_folder_); cmd_line.add_command_set(this->file_download_cmd_set_); this->file_download_cmd_set_.required(this->user_login_); this->file_download_cmd_set_.required(this->user_password_); this->file_download_cmd_set_.optional(this->server_); this->file_download_cmd_set_.required(this->channel_id_); this->file_download_cmd_set_.optional(this->message_); this->file_download_cmd_set_.required(this->attachment_); this->file_download_cmd_set_.optional(this->output_folder_); cmd_line.add_command_set(this->channel_list_cmd_set_); this->channel_list_cmd_set_.required(this->user_login_); this->channel_list_cmd_set_.required(this->user_password_); this->channel_list_cmd_set_.optional(this->server_); this->channel_list_cmd_set_.optional(this->output_format_); cmd_line.add_command_set(this->channel_create_cmd_set_); this->channel_create_cmd_set_.required(this->user_login_); this->channel_create_cmd_set_.required(this->user_password_); this->channel_create_cmd_set_.optional(this->server_); this->channel_create_cmd_set_.optional(this->channel_name_); this->channel_create_cmd_set_.optional(this->channel_type_); //cmd_line.add_command_set(this->server_init_command_set_); //this->server_init_command_set_.required(this->user_login_); //this->server_init_command_set_.required(this->user_password_); //this->server_init_command_set_.optional(this->node_name_); //this->server_init_command_set_.optional(this->port_); } void vds::vds_cmd_app::start_services(service_registrator & registrator, service_provider * sp) { base_class::start_services(registrator, sp); } bool vds::vds_cmd_app::need_demonize() { return false; } std::string vds::vds_cmd_app::login(const service_provider * sp) { auto server = this->server_.value().empty() ? "tcp://localhost:8050" : this->server_.value(); auto s = tcp_network_socket::connect(sp, network_address::parse(server)); auto[reader, writer] = s->start(sp); auto client = std::make_shared<http_client>(); client->start(reader, writer).detach(); std::string session; client->send(http_request::create( "GET", "/api/login?login=" + url_encode::encode(this->user_login_.value()) + "&password=" + url_encode::encode(this->user_password_.value())).get_message(), [server, &session](const http_message response) -> async_task<void> { http_response login_response(response); if (login_response.code() != http_response::HTTP_OK) { throw std::runtime_error("Login failed"); } auto body = json_parser::parse( server + "/api/login", co_await response.body()->read_all()); auto body_object = dynamic_cast<const json_object *>(body.get()); std::string value; body_object->get_property("state", value); if ("successful" != value) { throw std::runtime_error("Login failed " + value); } body_object->get_property("session", session); }).get(); return session; } void vds::vds_cmd_app::upload_file(const service_provider * sp, const std::string & session) { auto server = this->server_.value().empty() ? "tcp://localhost:8050" : this->server_.value(); auto s = tcp_network_socket::connect(sp, network_address::parse(server)); auto[reader, writer] = s->start(sp); auto client = std::make_shared<http_client>(); client->start(reader, writer).detach(); http_multipart_request request( "POST", "/api/upload?session=" + url_encode::encode(session)); request.add_string("channel_id", this->channel_id_.value()); if (!this->message_.value().empty()) { request.add_string("message", this->message_.value()); } filename fn(this->attachment_.value()); auto mimetype = http_mimetype::mimetype(fn); if(mimetype.empty()) { mimetype = "application/octet-stream"; } request.add_file("attachment", fn, fn.name(), mimetype); client->send(request.get_message(), [server](const http_message response) -> async_task<void> { if (http_response(response).code() != http_response::HTTP_OK) { throw std::runtime_error("Upload failed " + http_response(response).comment()); } co_return; }).get(); } void vds::vds_cmd_app::channel_list(const service_provider* sp, const std::string& session) { auto server = this->server_.value().empty() ? "tcp://localhost:8050" : this->server_.value(); auto s = tcp_network_socket::connect(sp, network_address::parse(server)); auto[reader, writer] = s->start(sp); auto client = std::make_shared<http_client>(); client->start(reader, writer).detach(); auto request = http_request::create( "GET", "/api/channels?session=" + url_encode::encode(session)).get_message(); client->send(request, [server, this](const http_message response) -> async_task<void> { if (http_response(response).code() != http_response::HTTP_OK) { throw std::runtime_error("Query channels failed " + http_response(response).comment()); } return this->channel_list_out(server, response); }).get(); } void vds::vds_cmd_app::channel_create(const service_provider* sp, const std::string& session) { auto server = this->server_.value().empty() ? "tcp://localhost:8050" : this->server_.value(); auto s = tcp_network_socket::connect(sp, network_address::parse(server)); auto[reader, writer] = s->start(sp); auto client = std::make_shared<http_client>(); client->start(reader, writer).detach(); client->send(http_request::create( "POST", "/api/channels?session=" + url_encode::encode(session) + "&name=" + url_encode::encode(this->channel_name_.value()) + "&type=" + url_encode::encode(this->channel_type_.value()) ).get_message(), [server, this](const http_message response) -> async_task<void> { if (http_response(response).code() != http_response::HTTP_OK) { throw std::runtime_error("Create channel failed"); } co_return; }).get(); } vds::async_task<void> vds::vds_cmd_app::channel_list_out(const std::string& server, const http_message response) { if (this->output_format_.value() == "json") { std::cout << co_await response.body()->read_all() << std::endl; } else { auto body = json_parser::parse( server + "/api/channels", co_await response.body()->read_all()); std::cout << std::setw(44) << std::left << "ID" << "|" << std::setw(15) << std::left << "Type" << "|" << "Name" << std::endl; auto body_array = dynamic_cast<const json_array *>(body.get()); for (size_t i = 0; i < body_array->size(); ++i) { auto item = dynamic_cast<const json_object *>(body_array->get(i).get()); std::string value; item->get_property("object_id", value); std::cout << std::setw(44) << value << "|"; item->get_property("type", value); std::cout << std::setw(15) << std::left << value << "|"; item->get_property("name", value); std::cout << value << std::endl; } } co_return; } <commit_msg>add messages cmd<commit_after>/* Copyright (c) 2017, Vadim Malyshev, lboss75@gmail.com All rights reserved */ #include "stdafx.h" #include "vds_cmd_app.h" #include "http_router.h" #include "user_manager.h" #include "tcp_network_socket.h" #include "http_request.h" #include "http_serializer.h" #include "http_client.h" #include "http_response.h" #include "http_multipart_request.h" #include "http_mimetype.h" #include <iomanip> namespace vds { class http_multipart_request; } vds::vds_cmd_app::vds_cmd_app() : file_upload_cmd_set_("Upload file", "Upload file on the network", "upload", "file"), file_download_cmd_set_("Download file", "Download file from the network", "download", "file"), channel_list_cmd_set_("Channel list", "List user channels", "list", "channel"), channel_create_cmd_set_("Channel create", "Create new channel", "create", "channel"), user_login_( "l", "login", "Login", "User login"), user_password_( "p", "password", "Password", "User password"), server_( "s", "server", "Server URL", "Server URL to connect"), channel_id_( "c", "channel", "Channel ID", "Channel identifier to send message"), message_( "m", "message", "Message", "Message"), attachment_( "a", "attachment", "File(s) names", "Comma separated file names"), output_folder_( "o", "output", "output folder", "Folder to store files"), output_format_( "f", "format", "Output format", "Output format (json)" ), channel_name_( "cn", "channel-name", "Channel name", "Name of channel"), channel_type_( "ct", "channel-type", "Channel type", "Type of channel") { } void vds::vds_cmd_app::main(const service_provider * sp) { if (this->current_command_set_ == &this->file_upload_cmd_set_) { const auto session = this->login(sp); this->upload_file(sp, session); } else if(this->current_command_set_ == &this->channel_list_cmd_set_) { const auto session = this->login(sp); this->channel_list(sp, session); } else if (this->current_command_set_ == &this->channel_create_cmd_set_) { const auto session = this->login(sp); this->channel_create(sp, session); } } void vds::vds_cmd_app::register_services(vds::service_registrator& registrator) { base_class::register_services(registrator); registrator.add(this->mt_service_); registrator.add(this->task_manager_); registrator.add(this->network_service_); } void vds::vds_cmd_app::register_command_line(command_line & cmd_line) { base_class::register_command_line(cmd_line); cmd_line.add_command_set(this->file_upload_cmd_set_); this->file_upload_cmd_set_.required(this->user_login_); this->file_upload_cmd_set_.required(this->user_password_); this->file_upload_cmd_set_.optional(this->server_); this->file_upload_cmd_set_.required(this->channel_id_); this->file_upload_cmd_set_.optional(this->message_); this->file_upload_cmd_set_.required(this->attachment_); this->file_upload_cmd_set_.optional(this->output_folder_); cmd_line.add_command_set(this->file_download_cmd_set_); this->file_download_cmd_set_.required(this->user_login_); this->file_download_cmd_set_.required(this->user_password_); this->file_download_cmd_set_.optional(this->server_); this->file_download_cmd_set_.required(this->channel_id_); this->file_download_cmd_set_.optional(this->message_); this->file_download_cmd_set_.required(this->attachment_); this->file_download_cmd_set_.optional(this->output_folder_); cmd_line.add_command_set(this->channel_list_cmd_set_); this->channel_list_cmd_set_.required(this->user_login_); this->channel_list_cmd_set_.required(this->user_password_); this->channel_list_cmd_set_.optional(this->server_); this->channel_list_cmd_set_.optional(this->output_format_); cmd_line.add_command_set(this->channel_create_cmd_set_); this->channel_create_cmd_set_.required(this->user_login_); this->channel_create_cmd_set_.required(this->user_password_); this->channel_create_cmd_set_.optional(this->server_); this->channel_create_cmd_set_.optional(this->channel_name_); this->channel_create_cmd_set_.optional(this->channel_type_); //cmd_line.add_command_set(this->server_init_command_set_); //this->server_init_command_set_.required(this->user_login_); //this->server_init_command_set_.required(this->user_password_); //this->server_init_command_set_.optional(this->node_name_); //this->server_init_command_set_.optional(this->port_); } void vds::vds_cmd_app::start_services(service_registrator & registrator, service_provider * sp) { base_class::start_services(registrator, sp); } bool vds::vds_cmd_app::need_demonize() { return false; } std::string vds::vds_cmd_app::login(const service_provider * sp) { auto server = this->server_.value().empty() ? "tcp://localhost:8050" : this->server_.value(); std::cout << "Logging in into " << server << "..." << std::endl; auto s = tcp_network_socket::connect(sp, network_address::parse(server)); auto[reader, writer] = s->start(sp); auto client = std::make_shared<http_client>(); client->start(reader, writer).detach(); std::string session; client->send(http_request::create( "GET", "/api/login?login=" + url_encode::encode(this->user_login_.value()) + "&password=" + url_encode::encode(this->user_password_.value())).get_message(), [server, &session](const http_message response) -> async_task<void> { http_response login_response(response); if (login_response.code() != http_response::HTTP_OK) { throw std::runtime_error("Login failed"); } auto body = json_parser::parse( server + "/api/login", co_await response.body()->read_all()); auto body_object = dynamic_cast<const json_object *>(body.get()); std::string value; body_object->get_property("state", value); if ("successful" != value) { throw std::runtime_error("Login failed " + value); } body_object->get_property("session", session); }).get(); std::cout << "Login successful" << std::endl; return session; } void vds::vds_cmd_app::upload_file(const service_provider * sp, const std::string & session) { auto server = this->server_.value().empty() ? "tcp://localhost:8050" : this->server_.value(); filename fn(this->attachment_.value()); std::cout << "Uploading " << fn.name() << "(" << file::length(fn) << "bytes) to " << server << std::endl; auto s = tcp_network_socket::connect(sp, network_address::parse(server)); auto[reader, writer] = s->start(sp); auto client = std::make_shared<http_client>(); client->start(reader, writer).detach(); http_multipart_request request( "POST", "/api/upload?session=" + url_encode::encode(session)); request.add_string("channel_id", this->channel_id_.value()); if (!this->message_.value().empty()) { request.add_string("message", this->message_.value()); } auto mimetype = http_mimetype::mimetype(fn); if(mimetype.empty()) { mimetype = "application/octet-stream"; } request.add_file("attachment", fn, fn.name(), mimetype); client->send(request.get_message(), [server](const http_message response) -> async_task<void> { if (http_response(response).code() != http_response::HTTP_OK) { throw std::runtime_error("Upload failed " + http_response(response).comment()); } co_return; }).get(); std::cout << "Upload completed" << std::endl; } void vds::vds_cmd_app::channel_list(const service_provider* sp, const std::string& session) { auto server = this->server_.value().empty() ? "tcp://localhost:8050" : this->server_.value(); auto s = tcp_network_socket::connect(sp, network_address::parse(server)); auto[reader, writer] = s->start(sp); auto client = std::make_shared<http_client>(); client->start(reader, writer).detach(); auto request = http_request::create( "GET", "/api/channels?session=" + url_encode::encode(session)).get_message(); client->send(request, [server, this](const http_message response) -> async_task<void> { if (http_response(response).code() != http_response::HTTP_OK) { throw std::runtime_error("Query channels failed " + http_response(response).comment()); } return this->channel_list_out(server, response); }).get(); } void vds::vds_cmd_app::channel_create(const service_provider* sp, const std::string& session) { auto server = this->server_.value().empty() ? "tcp://localhost:8050" : this->server_.value(); auto s = tcp_network_socket::connect(sp, network_address::parse(server)); auto[reader, writer] = s->start(sp); auto client = std::make_shared<http_client>(); client->start(reader, writer).detach(); client->send(http_request::create( "POST", "/api/channels?session=" + url_encode::encode(session) + "&name=" + url_encode::encode(this->channel_name_.value()) + "&type=" + url_encode::encode(this->channel_type_.value()) ).get_message(), [server, this](const http_message response) -> async_task<void> { if (http_response(response).code() != http_response::HTTP_OK) { throw std::runtime_error("Create channel failed"); } co_return; }).get(); } vds::async_task<void> vds::vds_cmd_app::channel_list_out(const std::string& server, const http_message response) { if (this->output_format_.value() == "json") { std::cout << co_await response.body()->read_all() << std::endl; } else { auto body = json_parser::parse( server + "/api/channels", co_await response.body()->read_all()); std::cout << std::setw(44) << std::left << "ID" << "|" << std::setw(15) << std::left << "Type" << "|" << "Name" << std::endl; auto body_array = dynamic_cast<const json_array *>(body.get()); for (size_t i = 0; i < body_array->size(); ++i) { auto item = dynamic_cast<const json_object *>(body_array->get(i).get()); std::string value; item->get_property("object_id", value); std::cout << std::setw(44) << value << "|"; item->get_property("type", value); std::cout << std::setw(15) << std::left << value << "|"; item->get_property("name", value); std::cout << value << std::endl; } } co_return; } <|endoftext|>
<commit_before>#include <Core/Utils/StackTrace.hpp> namespace Ra { namespace Core { namespace Utils { #ifndef OS_WINDOWS // A C++ function that will produce a stack trace with demangled function and method names. # include <cxxabi.h> // for __cxa_demangle # include <dlfcn.h> // for dladdr # include <execinfo.h> // for backtrace # include <sstream> # include <string> # if defined( COMPILER_CLANG ) # pragma clang diagnostic ignored "-Wformat" # pragma clang diagnostic ignored "-Wformat-extra-args" # elif defined( COMPILER_GCC ) # pragma GCC diagnostic ignored "-Wformat" # pragma GCC diagnostic ignored "-Wformat-extra-args" # endif std::string StackTrace( int skip ) { void* callstack[128]; const int nMaxFrames = sizeof( callstack ) / sizeof( callstack[0] ); char buf[1024]; int nFrames = backtrace( callstack, nMaxFrames ); std::ostringstream trace_buf; for ( int i = skip; i < nFrames; i++ ) { Dl_info info; if ( dladdr( callstack[i], &info ) ) { char* demangled = nullptr; int status; demangled = abi::__cxa_demangle( info.dli_sname, NULL, 0, &status ); snprintf( buf, sizeof( buf ), "%-3d %*0p %s + %td\n", i, int( 2 + sizeof( void* ) * 2 ), callstack[i], status == 0 ? demangled : info.dli_sname, (char*)callstack[i] - (char*)info.dli_saddr ); free( demangled ); } else { snprintf( buf, sizeof( buf ), "%-3d %*0p\n", i, int( 2 + sizeof( void* ) * 2 ), callstack[i] ); } trace_buf << buf; } if ( nFrames == nMaxFrames ) trace_buf << " [truncated]\n"; return trace_buf.str(); } #else inline std::string Backtrace( int skip = 1 ) { return "No execution stack trace on windows."; } #endif } // namespace Utils } // namespace Core } // namespace Ra <commit_msg>fix issue #628<commit_after>#include <Core/Utils/StackTrace.hpp> #ifndef OS_WINDOWS // A C++ function that will produce a stack trace with demangled function and method names. # include <cxxabi.h> // for __cxa_demangle # include <dlfcn.h> // for dladdr # include <execinfo.h> // for backtrace # include <sstream> # if defined( COMPILER_CLANG ) # pragma clang diagnostic ignored "-Wformat" # pragma clang diagnostic ignored "-Wformat-extra-args" # elif defined( COMPILER_GCC ) # pragma GCC diagnostic ignored "-Wformat" # pragma GCC diagnostic ignored "-Wformat-extra-args" # endif #endif namespace Ra { namespace Core { namespace Utils { std::string StackTrace( int skip ) { #ifndef OS_WINDOWS void* callstack[128]; const int nMaxFrames = sizeof( callstack ) / sizeof( callstack[0] ); char buf[1024]; int nFrames = backtrace( callstack, nMaxFrames ); std::ostringstream trace_buf; for ( int i = skip; i < nFrames; i++ ) { Dl_info info; if ( dladdr( callstack[i], &info ) ) { char* demangled = nullptr; int status; demangled = abi::__cxa_demangle( info.dli_sname, NULL, 0, &status ); snprintf( buf, sizeof( buf ), "%-3d %*0p %s + %td\n", i, int( 2 + sizeof( void* ) * 2 ), callstack[i], status == 0 ? demangled : info.dli_sname, (char*)callstack[i] - (char*)info.dli_saddr ); free( demangled ); } else { snprintf( buf, sizeof( buf ), "%-3d %*0p\n", i, int( 2 + sizeof( void* ) * 2 ), callstack[i] ); } trace_buf << buf; } if ( nFrames == nMaxFrames ) trace_buf << " [truncated]\n"; return trace_buf.str(); #else return "No execution stack trace on windows."; #endif } } // namespace Utils } // namespace Core } // namespace Ra <|endoftext|>
<commit_before>// template<typename Content> // class CollectionsDriver : public virtual Root { // public: template<typename Content> typename CollectionsDriver<Content>::CollectionPtr* CollectionsDriver<Content>::empty() { return new CollectionsDriver<Content>::CollectionPtr( new CollectionsDriver<Content>::Collection() ); } template<typename Content> typename CollectionsDriver<Content>::CollectionPtr* CollectionsDriver<Content>::create( typename CollectionsDriver<Content>::ContentPtr* element ) { CollectionsDriver<Content>::CollectionPtr* collection = empty(); (*collection)->push_back(*element); return collection; } template<typename Content> typename CollectionsDriver<Content>::CollectionPtr* CollectionsDriver<Content>::insert( typename CollectionsDriver<Content>::ContentPtr* element, typename CollectionsDriver<Content>::CollectionPtr* collection ) { (*collection)->push_back(*element); return collection; } template<typename Content> Message CollectionsDriver<Content>::toString() { return Message("CollectionsDriver"); } // }; /* END class CollectionsDriver */ <commit_msg>* Fixed memory access error caused by not allocating new memory.<commit_after>// template<typename Content> // class CollectionsDriver : public virtual Root { // public: template<typename Content> typename CollectionsDriver<Content>::CollectionPtr* CollectionsDriver<Content>::empty() { return new CollectionsDriver<Content>::CollectionPtr( new CollectionsDriver<Content>::Collection() ); } template<typename Content> typename CollectionsDriver<Content>::CollectionPtr* CollectionsDriver<Content>::create( typename CollectionsDriver<Content>::ContentPtr* element ) { CollectionsDriver<Content>::CollectionPtr* collection = empty(); (*collection)->push_back(*element); return collection; } template<typename Content> typename CollectionsDriver<Content>::CollectionPtr* CollectionsDriver<Content>::insert( typename CollectionsDriver<Content>::ContentPtr* element, typename CollectionsDriver<Content>::CollectionPtr* collection ) { (*collection)->push_back(*element); return new CollectionsDriver<Content>::CollectionPtr( *collection ); } template<typename Content> Message CollectionsDriver<Content>::toString() { return Message("CollectionsDriver"); } // }; /* END class CollectionsDriver */ <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CREATE_TORRENT_HPP_INCLUDED #define TORRENT_CREATE_TORRENT_HPP_INCLUDED #include "libtorrent/bencode.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/file_storage.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/config.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/hasher.hpp" #include <vector> #include <string> #include <utility> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/optional.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/scoped_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { namespace fs = boost::filesystem; namespace pt = boost::posix_time; struct TORRENT_EXPORT create_torrent { create_torrent(file_storage& fs, int piece_size); create_torrent(file_storage& fs); entry generate() const; file_storage const& files() const { return m_files; } void set_comment(char const* str); void set_creator(char const* str); void set_hash(int index, sha1_hash const& h); void add_url_seed(std::string const& url); void add_node(std::pair<std::string, int> const& node); void add_tracker(std::string const& url, int tier = 0); int num_pieces() const { return m_files.num_pieces(); } int piece_length() const { return m_files.piece_length(); } int piece_size(int i) const { return m_files.piece_size(i); } private: file_storage& m_files; // the urls to the trackers typedef std::pair<std::string, int> announce_entry; std::vector<announce_entry> m_urls; std::vector<std::string> m_url_seeds; std::vector<sha1_hash> m_piece_hash; // dht nodes to add to the routing table/bootstrap from typedef std::vector<std::pair<std::string, int> > nodes_t; nodes_t m_nodes; // the hash that identifies this torrent // is mutable because it's calculated // lazily mutable sha1_hash m_info_hash; // if a creation date is found in the torrent file // this will be set to that, otherwise it'll be // 1970, Jan 1 pt::ptime m_creation_date; // if a comment is found in the torrent file // this will be set to that comment std::string m_comment; // an optional string naming the software used // to create the torrent file std::string m_created_by; // this is used when creating a torrent. If there's // only one file there are cases where it's impossible // to know if it should be written as a multifile torrent // or not. e.g. test/test there's one file and one directory // and they have the same name. bool m_multifile; // this is true if the torrent is private. i.e., is should not // be announced on the dht bool m_private; }; namespace detail { inline bool default_pred(boost::filesystem::path const&) { return true; } inline void nop(int i) {} template <class Pred> void add_files_impl(file_storage& fs, boost::filesystem::path const& p , boost::filesystem::path const& l, Pred pred) { using boost::filesystem::path; using boost::filesystem::directory_iterator; std::string const& leaf = l.leaf(); if (leaf == ".." || leaf == ".") return; if (!pred(l)) return; path f(p / l); if (is_directory(f)) { for (directory_iterator i(f), end; i != end; ++i) add_files_impl(fs, p, l / i->leaf(), pred); } else { fs.add_file(l, file_size(f)); } } } template <class Pred> void add_files(file_storage& fs, boost::filesystem::path const& file, Pred p) { detail::add_files_impl(fs, complete(file).branch_path(), file.leaf(), p); } inline void add_files(file_storage& fs, boost::filesystem::path const& file) { detail::add_files_impl(fs, complete(file).branch_path(), file.leaf(), detail::default_pred); } template <class Fun> void set_piece_hashes(create_torrent& t, boost::filesystem::path const& p, Fun f) { file_pool fp; boost::scoped_ptr<storage_interface> st( default_storage_constructor(const_cast<file_storage&>(t.files()), p, fp)); // calculate the hash for all pieces int num = t.num_pieces(); std::vector<char> buf(t.piece_length()); for (int i = 0; i < num; ++i) { // read hits the disk and will block. Progress should // be updated in between reads st->read(&buf[0], i, 0, t.piece_size(i)); hasher h(&buf[0], t.piece_size(i)); t.set_hash(i, h.final()); f(i); } } inline void set_piece_hashes(create_torrent& t, boost::filesystem::path const& p) { set_piece_hashes(t, p, detail::nop); } } #endif <commit_msg>add set_priv and priv to create_torrent<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CREATE_TORRENT_HPP_INCLUDED #define TORRENT_CREATE_TORRENT_HPP_INCLUDED #include "libtorrent/bencode.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/file_storage.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/config.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/hasher.hpp" #include <vector> #include <string> #include <utility> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/optional.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/scoped_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { namespace fs = boost::filesystem; namespace pt = boost::posix_time; struct TORRENT_EXPORT create_torrent { create_torrent(file_storage& fs, int piece_size); create_torrent(file_storage& fs); entry generate() const; file_storage const& files() const { return m_files; } void set_comment(char const* str); void set_creator(char const* str); void set_hash(int index, sha1_hash const& h); void add_url_seed(std::string const& url); void add_node(std::pair<std::string, int> const& node); void add_tracker(std::string const& url, int tier = 0); void set_priv(bool p) const { return m_private = p; } int num_pieces() const { return m_files.num_pieces(); } int piece_length() const { return m_files.piece_length(); } int piece_size(int i) const { return m_files.piece_size(i); } bool priv() const { return m_private; } private: file_storage& m_files; // the urls to the trackers typedef std::pair<std::string, int> announce_entry; std::vector<announce_entry> m_urls; std::vector<std::string> m_url_seeds; std::vector<sha1_hash> m_piece_hash; // dht nodes to add to the routing table/bootstrap from typedef std::vector<std::pair<std::string, int> > nodes_t; nodes_t m_nodes; // the hash that identifies this torrent // is mutable because it's calculated // lazily mutable sha1_hash m_info_hash; // if a creation date is found in the torrent file // this will be set to that, otherwise it'll be // 1970, Jan 1 pt::ptime m_creation_date; // if a comment is found in the torrent file // this will be set to that comment std::string m_comment; // an optional string naming the software used // to create the torrent file std::string m_created_by; // this is used when creating a torrent. If there's // only one file there are cases where it's impossible // to know if it should be written as a multifile torrent // or not. e.g. test/test there's one file and one directory // and they have the same name. bool m_multifile; // this is true if the torrent is private. i.e., is should not // be announced on the dht bool m_private; }; namespace detail { inline bool default_pred(boost::filesystem::path const&) { return true; } inline void nop(int i) {} template <class Pred> void add_files_impl(file_storage& fs, boost::filesystem::path const& p , boost::filesystem::path const& l, Pred pred) { using boost::filesystem::path; using boost::filesystem::directory_iterator; std::string const& leaf = l.leaf(); if (leaf == ".." || leaf == ".") return; if (!pred(l)) return; path f(p / l); if (is_directory(f)) { for (directory_iterator i(f), end; i != end; ++i) add_files_impl(fs, p, l / i->leaf(), pred); } else { fs.add_file(l, file_size(f)); } } } template <class Pred> void add_files(file_storage& fs, boost::filesystem::path const& file, Pred p) { detail::add_files_impl(fs, complete(file).branch_path(), file.leaf(), p); } inline void add_files(file_storage& fs, boost::filesystem::path const& file) { detail::add_files_impl(fs, complete(file).branch_path(), file.leaf(), detail::default_pred); } template <class Fun> void set_piece_hashes(create_torrent& t, boost::filesystem::path const& p, Fun f) { file_pool fp; boost::scoped_ptr<storage_interface> st( default_storage_constructor(const_cast<file_storage&>(t.files()), p, fp)); // calculate the hash for all pieces int num = t.num_pieces(); std::vector<char> buf(t.piece_length()); for (int i = 0; i < num; ++i) { // read hits the disk and will block. Progress should // be updated in between reads st->read(&buf[0], i, 0, t.piece_size(i)); hasher h(&buf[0], t.piece_size(i)); t.set_hash(i, h.final()); f(i); } } inline void set_piece_hashes(create_torrent& t, boost::filesystem::path const& p) { set_piece_hashes(t, p, detail::nop); } } #endif <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include "bh_matmul.h" template <typename Type> bh_error do_matmul(bh_view *A, bh_view *B, bh_view *C){ Type* A_data; Type* B_data; Type* C_data; bh_data_get(A, (bh_data_ptr*) &A_data); bh_data_get(B, (bh_data_ptr*) &B_data); bh_data_get(C, (bh_data_ptr*) &C_data); bh_intp M = A->shape[0]; bh_intp N = B->shape[1]; bh_intp K = A->shape[1]; for(bh_intp i = 0; i < M; i++){ for(bh_intp j = 0; j < N; j++){ C_data[C->start + i*C->stride[0]+j*C->stride[1]] = 0; for(bh_intp k = 0; k < K; k++){ C_data[C->start + i*C->stride[0]+j*C->stride[1]] += \ A_data[A->start + i*A->stride[0]+k*A->stride[1]] * \ B_data[B->start + k*B->stride[0]+j*B->stride[1]]; } } } return BH_SUCCESS; } /* Implements matrix multiplication */ bh_error bh_matmul(bh_instruction *instr, void* arg) { bh_view *C = &instr->operand[0]; bh_view *A = &instr->operand[1]; bh_view *B = &instr->operand[2]; //Make sure that the arrays memory are allocated. if(bh_data_malloc(A->base) != BH_SUCCESS) return BH_OUT_OF_MEMORY; if(bh_data_malloc(B->base) != BH_SUCCESS) return BH_OUT_OF_MEMORY; if(bh_data_malloc(C->base) != BH_SUCCESS) return BH_OUT_OF_MEMORY; switch (bh_base_array(C)->type) { case BH_INT8: return do_matmul<bh_int8>(A, B, C); case BH_INT16: return do_matmul<bh_int16>(A, B, C); case BH_INT32: return do_matmul<bh_int32>(A, B, C); case BH_INT64: return do_matmul<bh_int64>(A, B, C); case BH_UINT8: return do_matmul<bh_uint8>(A, B, C); case BH_UINT16: return do_matmul<bh_uint16>(A, B, C); case BH_UINT32: return do_matmul<bh_uint32>(A, B, C); case BH_UINT64: return do_matmul<bh_uint64>(A, B, C); case BH_FLOAT32: return do_matmul<bh_float32>(A, B, C); case BH_FLOAT64: return do_matmul<bh_float64>(A, B, C); default: return BH_TYPE_NOT_SUPPORTED; } } <commit_msg>ext: Added support for complex numbers in matmul ext, this fixes issue<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include "bh_matmul.h" #include <complex> template <typename Type> bh_error do_matmul(bh_view *A, bh_view *B, bh_view *C){ Type* A_data; Type* B_data; Type* C_data; bh_data_get(A, (bh_data_ptr*) &A_data); bh_data_get(B, (bh_data_ptr*) &B_data); bh_data_get(C, (bh_data_ptr*) &C_data); bh_intp M = A->shape[0]; bh_intp N = B->shape[1]; bh_intp K = A->shape[1]; for(bh_intp i = 0; i < M; i++){ for(bh_intp j = 0; j < N; j++){ C_data[C->start + i*C->stride[0]+j*C->stride[1]] = 0; for(bh_intp k = 0; k < K; k++){ C_data[C->start + i*C->stride[0]+j*C->stride[1]] += \ A_data[A->start + i*A->stride[0]+k*A->stride[1]] * \ B_data[B->start + k*B->stride[0]+j*B->stride[1]]; } } } return BH_SUCCESS; } /* Implements matrix multiplication */ bh_error bh_matmul(bh_instruction *instr, void* arg) { bh_view *C = &instr->operand[0]; bh_view *A = &instr->operand[1]; bh_view *B = &instr->operand[2]; //Make sure that the arrays memory are allocated. if(bh_data_malloc(A->base) != BH_SUCCESS) return BH_OUT_OF_MEMORY; if(bh_data_malloc(B->base) != BH_SUCCESS) return BH_OUT_OF_MEMORY; if(bh_data_malloc(C->base) != BH_SUCCESS) return BH_OUT_OF_MEMORY; switch (bh_base_array(C)->type) { case BH_INT8: return do_matmul<bh_int8>(A, B, C); case BH_INT16: return do_matmul<bh_int16>(A, B, C); case BH_INT32: return do_matmul<bh_int32>(A, B, C); case BH_INT64: return do_matmul<bh_int64>(A, B, C); case BH_UINT8: return do_matmul<bh_uint8>(A, B, C); case BH_UINT16: return do_matmul<bh_uint16>(A, B, C); case BH_UINT32: return do_matmul<bh_uint32>(A, B, C); case BH_UINT64: return do_matmul<bh_uint64>(A, B, C); case BH_FLOAT32: return do_matmul<bh_float32>(A, B, C); case BH_FLOAT64: return do_matmul<bh_float64>(A, B, C); case BH_COMPLEX64: return do_matmul<std::complex<float> >(A, B, C); case BH_COMPLEX128: return do_matmul<std::complex<double> >(A, B, C); default: return BH_TYPE_NOT_SUPPORTED; } } <|endoftext|>
<commit_before>/*$Id$ * * This source file is a part of the Fresco Project. * Copyright (C) 2001 Stefan Seefeld <stefan@fresco.org> * http://www.fresco.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #include <Prague/Sys/Tracer.hh> #include <Prague/Sys/GetOpt.hh> #include <Prague/Sys/Path.hh> #include <Prague/Sys/Directory.hh> #include <Prague/Sys/Plugin.hh> #include "Berlin/Logger.hh" #include "Berlin/RCManager.hh" #include "Berlin/Console.hh" using namespace Prague; using namespace Berlin; namespace { Plugin<Console::Loader> *plugin = 0; } // --------------------------------------------------------------- // class Console // --------------------------------------------------------------- Console *Console::my_console = 0; Console::Reaper::~Reaper() { delete Console::my_console; delete plugin; } Console::console_list_t Console::my_available_consoles; void Console::cache_available_consoles() { static bool cached = false; if (cached) return; Prague::Path path = RCManager::get_path("modulepath"); for (Prague::Path::iterator path_elt = path.begin(), path_end = path.end(); path_elt != path_end; ++path_elt) { Directory dir(*path_elt + "/Console", Directory::alpha, "\\.so$"); for (Directory::iterator file = dir.begin(), last_file = dir.end(); file != last_file; ++file) { try { plugin = new Plugin<Console::Loader>((*file)->long_name());} catch (const std::runtime_error &e) { Logger::log(Logger::loader) << "Plugin '" << (*file)->name() << "' is not loadable [" << e.what() << "]" << std::endl; continue; } delete plugin; plugin = 0; std::string name = (*file)->name(); unsigned const dotpos = name.find(".so"); // FIXME: breaks if in middle ? name = name.substr(0,dotpos); my_available_consoles.insert(std::make_pair(name, (*file)->long_name())); } } cached = true; } void Console::list_available(std::ostream & o) { cache_available_consoles(); for (console_list_t::const_iterator iter = my_available_consoles.begin(), end = my_available_consoles.end(); iter != end; ++iter) { o << iter->first << " (" << iter->second << ")" << std::endl; } } bool Console::is_available(std::string const &console) { cache_available_consoles(); if (my_available_consoles.find(console) != my_available_consoles.end()) return true; return false; } int Console::open(const std::string &console, int argc, char **argv, PortableServer::POA_ptr poa, Fresco::PixelCoord x, Fresco::PixelCoord y) throw(std::runtime_error) { cache_available_consoles(); if (my_available_consoles.size()==0) { throw std::runtime_error("No valid consoles found in modulepath"); } if (!console.empty()) { // Console name given: Load exactly the one specified if (!is_available(console)) { std::string const msg = "No console named \"" + console + "\" found in modulepath."; throw std::runtime_error(msg); } else plugin = new Plugin<Console::Loader>(my_available_consoles[console]); } else { // No specific console requested: load the one which is found first std::string const & console_name = my_available_consoles.begin()->first; try { plugin = new Plugin<Console::Loader>(my_available_consoles[console_name]); } catch (std::runtime_error const &) { std::string const msg = "Previously-found console " + console_name + " not available."; throw std::runtime_error(msg); } } my_console = (*plugin)->load(argc, argv, x, y); my_console->my_poa = PortableServer::POA::_duplicate(poa); return argc; } Console *Console::instance() { return my_console; } PortableServer::Servant Console::reference_to_servant(Fresco::Drawable_ptr drawable) { Trace trace("Console::reference_to_servant"); try { return my_poa->reference_to_servant(drawable); } catch (const PortableServer::POA::ObjectNotActive &) { } catch (const PortableServer::POA::WrongAdapter &) { } catch (const CORBA::OBJECT_NOT_EXIST &) { } return 0; } Fresco::Drawable_ptr Console::activate_drawable(Console::Drawable *d) { Trace trace("Console::activate_drawable"); PortableServer::ObjectId_var oid = my_poa->activate_object(d); d->_remove_ref(); return d->_this(); } <commit_msg>Only find the last ".so" as suggested by cow.<commit_after>/*$Id$ * * This source file is a part of the Fresco Project. * Copyright (C) 2001 Stefan Seefeld <stefan@fresco.org> * http://www.fresco.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #include <Prague/Sys/Tracer.hh> #include <Prague/Sys/GetOpt.hh> #include <Prague/Sys/Path.hh> #include <Prague/Sys/Directory.hh> #include <Prague/Sys/Plugin.hh> #include "Berlin/Logger.hh" #include "Berlin/RCManager.hh" #include "Berlin/Console.hh" using namespace Prague; using namespace Berlin; namespace { Plugin<Console::Loader> *plugin = 0; } // --------------------------------------------------------------- // class Console // --------------------------------------------------------------- Console *Console::my_console = 0; Console::Reaper::~Reaper() { delete Console::my_console; delete plugin; } Console::console_list_t Console::my_available_consoles; void Console::cache_available_consoles() { static bool cached = false; if (cached) return; Prague::Path path = RCManager::get_path("modulepath"); for (Prague::Path::iterator path_elt = path.begin(), path_end = path.end(); path_elt != path_end; ++path_elt) { Directory dir(*path_elt + "/Console", Directory::alpha, "\\.so$"); for (Directory::iterator file = dir.begin(), last_file = dir.end(); file != last_file; ++file) { try { plugin = new Plugin<Console::Loader>((*file)->long_name());} catch (const std::runtime_error &e) { Logger::log(Logger::loader) << "Plugin '" << (*file)->name() << "' is not loadable [" << e.what() << "]" << std::endl; continue; } delete plugin; plugin = 0; std::string name = (*file)->name(); unsigned const dotpos = name.rfind(".so"); name = name.substr(0,dotpos); my_available_consoles.insert(std::make_pair(name, (*file)->long_name())); } } cached = true; } void Console::list_available(std::ostream & o) { cache_available_consoles(); for (console_list_t::const_iterator iter = my_available_consoles.begin(), end = my_available_consoles.end(); iter != end; ++iter) { o << iter->first << " (" << iter->second << ")" << std::endl; } } bool Console::is_available(std::string const &console) { cache_available_consoles(); if (my_available_consoles.find(console) != my_available_consoles.end()) return true; return false; } int Console::open(const std::string &console, int argc, char **argv, PortableServer::POA_ptr poa, Fresco::PixelCoord x, Fresco::PixelCoord y) throw(std::runtime_error) { cache_available_consoles(); if (my_available_consoles.size()==0) { throw std::runtime_error("No valid consoles found in modulepath"); } if (!console.empty()) { // Console name given: Load exactly the one specified if (!is_available(console)) { std::string const msg = "No console named \"" + console + "\" found in modulepath."; throw std::runtime_error(msg); } else plugin = new Plugin<Console::Loader>(my_available_consoles[console]); } else { // No specific console requested: load the one which is found first std::string const & console_name = my_available_consoles.begin()->first; try { plugin = new Plugin<Console::Loader>(my_available_consoles[console_name]); } catch (std::runtime_error const &) { std::string const msg = "Previously-found console " + console_name + " not available."; throw std::runtime_error(msg); } } my_console = (*plugin)->load(argc, argv, x, y); my_console->my_poa = PortableServer::POA::_duplicate(poa); return argc; } Console *Console::instance() { return my_console; } PortableServer::Servant Console::reference_to_servant(Fresco::Drawable_ptr drawable) { Trace trace("Console::reference_to_servant"); try { return my_poa->reference_to_servant(drawable); } catch (const PortableServer::POA::ObjectNotActive &) { } catch (const PortableServer::POA::WrongAdapter &) { } catch (const CORBA::OBJECT_NOT_EXIST &) { } return 0; } Fresco::Drawable_ptr Console::activate_drawable(Console::Drawable *d) { Trace trace("Console::activate_drawable"); PortableServer::ObjectId_var oid = my_poa->activate_object(d); d->_remove_ref(); return d->_this(); } <|endoftext|>
<commit_before>/** * @copyright * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * @endcopyright * * @file ClientContext.cpp * @brief Implementation of the class ClientContext */ #include "svn_client.h" #include "private/svn_wc_private.h" #include "svn_private_config.h" #include "ClientContext.h" #include "JNIUtil.h" #include "JNICriticalSection.h" #include "Prompter.h" #include "CreateJ.h" #include "EnumMapper.h" #include "CommitMessage.h" ClientContext::ClientContext(jobject jsvnclient, SVN::Pool &pool) : RaSharedContext(pool) { static jfieldID ctxFieldID = 0; attachJavaObject(jsvnclient, "L"JAVA_PACKAGE"/SVNClient$ClientContext;", "clientContext", &ctxFieldID); SVN_JNI_ERR(svn_client_create_context(&m_context, pool.getPool()), ); /* Clear the wc_ctx as we don't want to maintain this unconditionally for compatibility reasons */ SVN_JNI_ERR(svn_wc_context_destroy(m_context->wc_ctx), ); m_context->wc_ctx = NULL; /* None of the following members change during the lifetime of this object. */ m_context->notify_func = NULL; m_context->notify_baton = NULL; m_context->log_msg_func3 = CommitMessage::callback; m_context->log_msg_baton3 = NULL; m_context->cancel_func = checkCancel; m_context->cancel_baton = this; m_context->notify_func2= notify; m_context->notify_baton2 = m_jctx; m_context->progress_func = progress; m_context->progress_baton = m_jctx; m_context->conflict_func2 = resolve; m_context->conflict_baton2 = m_jctx; m_context->client_name = getClientName(); } ClientContext::~ClientContext() { } /* Helper function to make sure that we don't keep dangling pointers in ctx. Note that this function might be called multiple times if getContext() is called on the same pool. The use of this function assumes a proper subpool behavior by its user, (read: SVNClient) usually per request. */ extern "C" { struct clearctx_baton_t { svn_client_ctx_t *ctx; svn_client_ctx_t *backup; }; static apr_status_t clear_ctx_ptrs(void *ptr) { clearctx_baton_t *bt = (clearctx_baton_t*)ptr; /* Reset all values to those before overwriting by getContext. */ *bt->ctx = *bt->backup; return APR_SUCCESS; } }; svn_client_ctx_t * ClientContext::getContext(CommitMessage *message, SVN::Pool &in_pool) { apr_pool_t *pool = in_pool.getPool(); svn_client_ctx_t *ctx = m_context; /* Make a temporary copy of ctx to restore at pool cleanup to avoid leaving references to dangling pointers. Note that this allows creating a stack of context changes if the function is invoked multiple times with different pools. */ clearctx_baton_t *bt = (clearctx_baton_t *)apr_pcalloc(pool, sizeof(*bt)); bt->ctx = ctx; bt->backup = (svn_client_ctx_t*)apr_pmemdup(pool, ctx, sizeof(*ctx)); apr_pool_cleanup_register(in_pool.getPool(), bt, clear_ctx_ptrs, clear_ctx_ptrs); if (!ctx->config) { apr_hash_t * configData = getConfigData(); ctx->config = configData; bt->backup->config = ctx->config; } ctx->auth_baton = getAuthBaton(in_pool); ctx->log_msg_baton3 = message; resetCancelRequest(); SVN_JNI_ERR(svn_wc_context_create(&ctx->wc_ctx, NULL, in_pool.getPool(), in_pool.getPool()), NULL); return ctx; } void ClientContext::notify(void *baton, const svn_wc_notify_t *notify, apr_pool_t *pool) { jobject jctx = (jobject) baton; JNIEnv *env = JNIUtil::getEnv(); static jmethodID mid = 0; if (mid == 0) { jclass clazz = env->GetObjectClass(jctx); if (JNIUtil::isJavaExceptionThrown()) return; mid = env->GetMethodID(clazz, "onNotify", "(L"JAVA_PACKAGE"/ClientNotifyInformation;)V"); if (JNIUtil::isJavaExceptionThrown() || mid == 0) return; env->DeleteLocalRef(clazz); } jobject jInfo = CreateJ::ClientNotifyInformation(notify); if (JNIUtil::isJavaExceptionThrown()) return; env->CallVoidMethod(jctx, mid, jInfo); if (JNIUtil::isJavaExceptionThrown()) return; env->DeleteLocalRef(jInfo); } svn_error_t * ClientContext::resolve(svn_wc_conflict_result_t **result, const svn_wc_conflict_description2_t *desc, void *baton, apr_pool_t *result_pool, apr_pool_t *scratch_pool) { jobject jctx = (jobject) baton; JNIEnv *env = JNIUtil::getEnv(); // Create a local frame for our references env->PushLocalFrame(LOCAL_FRAME_SIZE); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; static jmethodID mid = 0; if (mid == 0) { jclass clazz = env->GetObjectClass(jctx); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN(SVN_NO_ERROR); mid = env->GetMethodID(clazz, "resolve", "(L"JAVA_PACKAGE"/ConflictDescriptor;)" "L"JAVA_PACKAGE"/ConflictResult;"); if (JNIUtil::isJavaExceptionThrown() || mid == 0) POP_AND_RETURN(SVN_NO_ERROR); } // Create an instance of the conflict descriptor. jobject jdesc = CreateJ::ConflictDescriptor(desc); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN(SVN_NO_ERROR); // Invoke the Java conflict resolver callback method using the descriptor. jobject jresult = env->CallObjectMethod(jctx, mid, jdesc); if (JNIUtil::isJavaExceptionThrown()) { // If an exception is thrown by our conflict resolver, remove it // from the JNI env, and convert it into a Subversion error. SVN::Pool tmpPool(scratch_pool); const char *msg = JNIUtil::thrownExceptionToCString(tmpPool); svn_error_t *err = svn_error_create(SVN_ERR_WC_CONFLICT_RESOLVER_FAILURE, NULL, msg); env->PopLocalFrame(NULL); return err; } *result = javaResultToC(jresult, result_pool); if (*result == NULL) { // Unable to convert the result into a C representation. env->PopLocalFrame(NULL); return svn_error_create(SVN_ERR_WC_CONFLICT_RESOLVER_FAILURE, NULL, NULL); } env->PopLocalFrame(NULL); return SVN_NO_ERROR; } svn_wc_conflict_result_t * ClientContext::javaResultToC(jobject jresult, apr_pool_t *pool) { JNIEnv *env = JNIUtil::getEnv(); // Create a local frame for our references env->PushLocalFrame(LOCAL_FRAME_SIZE); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; static jmethodID getChoice = 0; static jmethodID getMergedPath = 0; jclass clazz = NULL; if (getChoice == 0 || getMergedPath == 0) { clazz = env->FindClass(JAVA_PACKAGE "/ConflictResult"); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN_NULL; } if (getChoice == 0) { getChoice = env->GetMethodID(clazz, "getChoice", "()L"JAVA_PACKAGE"/ConflictResult$Choice;"); if (JNIUtil::isJavaExceptionThrown() || getChoice == 0) POP_AND_RETURN_NULL; } if (getMergedPath == 0) { getMergedPath = env->GetMethodID(clazz, "getMergedPath", "()Ljava/lang/String;"); if (JNIUtil::isJavaExceptionThrown() || getMergedPath == 0) POP_AND_RETURN_NULL; } jobject jchoice = env->CallObjectMethod(jresult, getChoice); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN_NULL; jstring jmergedPath = (jstring) env->CallObjectMethod(jresult, getMergedPath); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN_NULL; JNIStringHolder mergedPath(jmergedPath); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN_NULL; svn_wc_conflict_result_t *result = svn_wc_create_conflict_result(EnumMapper::toConflictChoice(jchoice), mergedPath.pstrdup(pool), pool); env->PopLocalFrame(NULL); return result; } <commit_msg>On the javahl-ra branch:<commit_after>/** * @copyright * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * @endcopyright * * @file ClientContext.cpp * @brief Implementation of the class ClientContext */ #include "svn_client.h" #include "private/svn_wc_private.h" #include "svn_private_config.h" #include "ClientContext.h" #include "JNIUtil.h" #include "JNICriticalSection.h" #include "Prompter.h" #include "CreateJ.h" #include "EnumMapper.h" #include "CommitMessage.h" ClientContext::ClientContext(jobject jsvnclient, SVN::Pool &pool) : RaSharedContext(pool) { static jfieldID ctxFieldID = 0; attachJavaObject(jsvnclient, "L"JAVA_PACKAGE"/SVNClient$ClientContext;", "clientContext", &ctxFieldID); SVN_JNI_ERR(svn_client_create_context2(&m_context, NULL, pool.getPool()), ); /* Clear the wc_ctx as we don't want to maintain this unconditionally for compatibility reasons */ SVN_JNI_ERR(svn_wc_context_destroy(m_context->wc_ctx), ); m_context->wc_ctx = NULL; /* None of the following members change during the lifetime of this object. */ m_context->notify_func = NULL; m_context->notify_baton = NULL; m_context->log_msg_func3 = CommitMessage::callback; m_context->log_msg_baton3 = NULL; m_context->cancel_func = checkCancel; m_context->cancel_baton = this; m_context->notify_func2= notify; m_context->notify_baton2 = m_jctx; m_context->progress_func = progress; m_context->progress_baton = m_jctx; m_context->conflict_func2 = resolve; m_context->conflict_baton2 = m_jctx; m_context->client_name = getClientName(); } ClientContext::~ClientContext() { } /* Helper function to make sure that we don't keep dangling pointers in ctx. Note that this function might be called multiple times if getContext() is called on the same pool. The use of this function assumes a proper subpool behavior by its user, (read: SVNClient) usually per request. */ extern "C" { struct clearctx_baton_t { svn_client_ctx_t *ctx; svn_client_ctx_t *backup; }; static apr_status_t clear_ctx_ptrs(void *ptr) { clearctx_baton_t *bt = (clearctx_baton_t*)ptr; /* Reset all values to those before overwriting by getContext. */ *bt->ctx = *bt->backup; return APR_SUCCESS; } }; svn_client_ctx_t * ClientContext::getContext(CommitMessage *message, SVN::Pool &in_pool) { apr_pool_t *pool = in_pool.getPool(); svn_client_ctx_t *ctx = m_context; /* Make a temporary copy of ctx to restore at pool cleanup to avoid leaving references to dangling pointers. Note that this allows creating a stack of context changes if the function is invoked multiple times with different pools. */ clearctx_baton_t *bt = (clearctx_baton_t *)apr_pcalloc(pool, sizeof(*bt)); bt->ctx = ctx; bt->backup = (svn_client_ctx_t*)apr_pmemdup(pool, ctx, sizeof(*ctx)); apr_pool_cleanup_register(in_pool.getPool(), bt, clear_ctx_ptrs, clear_ctx_ptrs); if (!ctx->config) { apr_hash_t * configData = getConfigData(); ctx->config = configData; bt->backup->config = ctx->config; } ctx->auth_baton = getAuthBaton(in_pool); ctx->log_msg_baton3 = message; resetCancelRequest(); SVN_JNI_ERR(svn_wc_context_create(&ctx->wc_ctx, NULL, in_pool.getPool(), in_pool.getPool()), NULL); return ctx; } void ClientContext::notify(void *baton, const svn_wc_notify_t *notify, apr_pool_t *pool) { jobject jctx = (jobject) baton; JNIEnv *env = JNIUtil::getEnv(); static jmethodID mid = 0; if (mid == 0) { jclass clazz = env->GetObjectClass(jctx); if (JNIUtil::isJavaExceptionThrown()) return; mid = env->GetMethodID(clazz, "onNotify", "(L"JAVA_PACKAGE"/ClientNotifyInformation;)V"); if (JNIUtil::isJavaExceptionThrown() || mid == 0) return; env->DeleteLocalRef(clazz); } jobject jInfo = CreateJ::ClientNotifyInformation(notify); if (JNIUtil::isJavaExceptionThrown()) return; env->CallVoidMethod(jctx, mid, jInfo); if (JNIUtil::isJavaExceptionThrown()) return; env->DeleteLocalRef(jInfo); } svn_error_t * ClientContext::resolve(svn_wc_conflict_result_t **result, const svn_wc_conflict_description2_t *desc, void *baton, apr_pool_t *result_pool, apr_pool_t *scratch_pool) { jobject jctx = (jobject) baton; JNIEnv *env = JNIUtil::getEnv(); // Create a local frame for our references env->PushLocalFrame(LOCAL_FRAME_SIZE); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; static jmethodID mid = 0; if (mid == 0) { jclass clazz = env->GetObjectClass(jctx); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN(SVN_NO_ERROR); mid = env->GetMethodID(clazz, "resolve", "(L"JAVA_PACKAGE"/ConflictDescriptor;)" "L"JAVA_PACKAGE"/ConflictResult;"); if (JNIUtil::isJavaExceptionThrown() || mid == 0) POP_AND_RETURN(SVN_NO_ERROR); } // Create an instance of the conflict descriptor. jobject jdesc = CreateJ::ConflictDescriptor(desc); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN(SVN_NO_ERROR); // Invoke the Java conflict resolver callback method using the descriptor. jobject jresult = env->CallObjectMethod(jctx, mid, jdesc); if (JNIUtil::isJavaExceptionThrown()) { // If an exception is thrown by our conflict resolver, remove it // from the JNI env, and convert it into a Subversion error. SVN::Pool tmpPool(scratch_pool); const char *msg = JNIUtil::thrownExceptionToCString(tmpPool); svn_error_t *err = svn_error_create(SVN_ERR_WC_CONFLICT_RESOLVER_FAILURE, NULL, msg); env->PopLocalFrame(NULL); return err; } *result = javaResultToC(jresult, result_pool); if (*result == NULL) { // Unable to convert the result into a C representation. env->PopLocalFrame(NULL); return svn_error_create(SVN_ERR_WC_CONFLICT_RESOLVER_FAILURE, NULL, NULL); } env->PopLocalFrame(NULL); return SVN_NO_ERROR; } svn_wc_conflict_result_t * ClientContext::javaResultToC(jobject jresult, apr_pool_t *pool) { JNIEnv *env = JNIUtil::getEnv(); // Create a local frame for our references env->PushLocalFrame(LOCAL_FRAME_SIZE); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; static jmethodID getChoice = 0; static jmethodID getMergedPath = 0; jclass clazz = NULL; if (getChoice == 0 || getMergedPath == 0) { clazz = env->FindClass(JAVA_PACKAGE "/ConflictResult"); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN_NULL; } if (getChoice == 0) { getChoice = env->GetMethodID(clazz, "getChoice", "()L"JAVA_PACKAGE"/ConflictResult$Choice;"); if (JNIUtil::isJavaExceptionThrown() || getChoice == 0) POP_AND_RETURN_NULL; } if (getMergedPath == 0) { getMergedPath = env->GetMethodID(clazz, "getMergedPath", "()Ljava/lang/String;"); if (JNIUtil::isJavaExceptionThrown() || getMergedPath == 0) POP_AND_RETURN_NULL; } jobject jchoice = env->CallObjectMethod(jresult, getChoice); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN_NULL; jstring jmergedPath = (jstring) env->CallObjectMethod(jresult, getMergedPath); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN_NULL; JNIStringHolder mergedPath(jmergedPath); if (JNIUtil::isJavaExceptionThrown()) POP_AND_RETURN_NULL; svn_wc_conflict_result_t *result = svn_wc_create_conflict_result(EnumMapper::toConflictChoice(jchoice), mergedPath.pstrdup(pool), pool); env->PopLocalFrame(NULL); return result; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. All rights reserved. // Copyright (c) 2012-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "tbb/tbb.h" #include "IECore/Exception.h" #include "IECore/BoxOps.h" #include "IECore/BoxAlgo.h" #include "Gaffer/Context.h" #include "GafferImage/ImagePlug.h" #include "GafferImage/FormatPlug.h" using namespace std; using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferImage; using namespace tbb; IE_CORE_DEFINERUNTIMETYPED( ImagePlug ); ////////////////////////////////////////////////////////////////////////// // Implementation of CopyTiles: // A simple class for multithreading the copying of // image tiles from an input plug to an output plug. ////////////////////////////////////////////////////////////////////////// namespace GafferImage { namespace Detail { class CopyTiles { public: CopyTiles( const vector<float *> &imageChannelData, const vector<string> &channelNames, const Gaffer::FloatVectorDataPlug *channelDataPlug, const Box2i& dataWindow, const Context *context, const int tileSize ) : m_imageChannelData( imageChannelData ), m_channelNames( channelNames ), m_channelDataPlug( channelDataPlug ), m_dataWindow( dataWindow ), m_parentContext( context ), m_tileSize( tileSize ) {} void operator()( const blocked_range2d<size_t>& r ) const { ContextPtr context = new Context( *m_parentContext ); const Box2i operationWindow( V2i( r.rows().begin()+m_dataWindow.min.x, r.cols().begin()+m_dataWindow.min.y ), V2i( r.rows().end()+m_dataWindow.min.x-1, r.cols().end()+m_dataWindow.min.y-1 ) ); V2i minTileOrigin = ImagePlug::tileOrigin( operationWindow.min ); V2i maxTileOrigin = ImagePlug::tileOrigin( operationWindow.max ); size_t imageStride = m_dataWindow.size().x + 1; for( int tileOriginY = minTileOrigin.y; tileOriginY <= maxTileOrigin.y; tileOriginY += m_tileSize ) { for( int tileOriginX = minTileOrigin.x; tileOriginX <= maxTileOrigin.x; tileOriginX += m_tileSize ) { for( vector<string>::const_iterator it = m_channelNames.begin(), eIt = m_channelNames.end(); it != eIt; it++ ) { context->set( ImagePlug::channelNameContextName, *it ); context->set( ImagePlug::tileOriginContextName, V2i( tileOriginX, tileOriginY ) ); Context::Scope scope( context ); Box2i tileBound( V2i( tileOriginX, tileOriginY ), V2i( tileOriginX + m_tileSize - 1, tileOriginY + m_tileSize - 1 ) ); Box2i b = boxIntersection( tileBound, operationWindow ); ConstFloatVectorDataPtr tileData = m_channelDataPlug->getValue(); for( int y = b.min.y; y<=b.max.y; y++ ) { const float *tilePtr = &(tileData->readable()[0]) + (y - tileOriginY) * m_tileSize + (b.min.x - tileOriginX); float *channelPtr = m_imageChannelData[it-m_channelNames.begin()] + ( y - m_dataWindow.min.y ) * imageStride + (b.min.x - m_dataWindow.min.x); for( int x = b.min.x; x <= b.max.x; x++ ) { *channelPtr++ = *tilePtr++; } } } } } } private: const vector<float *> &m_imageChannelData; const vector<string> &m_channelNames; const Gaffer::FloatVectorDataPlug *m_channelDataPlug; const Box2i &m_dataWindow; const Context *m_parentContext; const int m_tileSize; }; }; }; ////////////////////////////////////////////////////////////////////////// // Implementation of ImagePlug ////////////////////////////////////////////////////////////////////////// const IECore::InternedString ImagePlug::channelNameContextName = "image:channelName"; const IECore::InternedString ImagePlug::tileOriginContextName = "image:tileOrigin"; size_t ImagePlug::g_firstPlugIndex = 0; ImagePlug::ImagePlug( const std::string &name, Direction direction, unsigned flags ) : CompoundPlug( name, direction, flags ) { storeIndexOfNextChild( g_firstPlugIndex ); // we don't want the children to be serialised in any way - we always create // them ourselves in this constructor so they aren't Dynamic, and we don't ever // want to store their values because they are meaningless without an input // connection, so they aren't Serialisable either. unsigned childFlags = flags & ~(Dynamic | Serialisable); addChild( new FormatPlug( "format", direction, Format(), childFlags ) ); addChild( new AtomicBox2iPlug( "dataWindow", direction, Imath::Box2i(), childFlags ) ); IECore::StringVectorDataPtr channelStrVectorData( new IECore::StringVectorData() ); std::vector<std::string> &channelStrVector( channelStrVectorData->writable() ); channelStrVector.push_back("R"); channelStrVector.push_back("G"); channelStrVector.push_back("B"); addChild( new StringVectorDataPlug( "channelNames", direction, channelStrVectorData, childFlags ) ); addChild( new FloatVectorDataPlug( "channelData", direction, blackTile(), childFlags ) ); } ImagePlug::~ImagePlug() { } const IECore::FloatVectorData *ImagePlug::whiteTile() { static IECore::ConstFloatVectorDataPtr g_whiteTile( new IECore::FloatVectorData( std::vector<float>( ImagePlug::tileSize()*ImagePlug::tileSize(), 1. ) ) ); return g_whiteTile.get(); }; const IECore::FloatVectorData *ImagePlug::blackTile() { static IECore::ConstFloatVectorDataPtr g_blackTile( new IECore::FloatVectorData( std::vector<float>( ImagePlug::tileSize()*ImagePlug::tileSize(), 0. ) ) ); return g_blackTile.get(); }; bool ImagePlug::acceptsChild( const GraphComponent *potentialChild ) const { return children().size() != 4; } bool ImagePlug::acceptsInput( const Gaffer::Plug *input ) const { if( !CompoundPlug::acceptsInput( input ) ) { return false; } if( input ) { return input->isInstanceOf( staticTypeId() ); } return true; } Gaffer::PlugPtr ImagePlug::createCounterpart( const std::string &name, Direction direction ) const { return new ImagePlug( name, direction, getFlags() ); } GafferImage::FormatPlug *ImagePlug::formatPlug() { return getChild<FormatPlug>( g_firstPlugIndex ); } const GafferImage::FormatPlug *ImagePlug::formatPlug() const { return getChild<FormatPlug>( g_firstPlugIndex ); } Gaffer::AtomicBox2iPlug *ImagePlug::dataWindowPlug() { return getChild<AtomicBox2iPlug>( g_firstPlugIndex+1 ); } const Gaffer::AtomicBox2iPlug *ImagePlug::dataWindowPlug() const { return getChild<AtomicBox2iPlug>( g_firstPlugIndex+1 ); } Gaffer::StringVectorDataPlug *ImagePlug::channelNamesPlug() { return getChild<StringVectorDataPlug>( g_firstPlugIndex+2 ); } const Gaffer::StringVectorDataPlug *ImagePlug::channelNamesPlug() const { return getChild<StringVectorDataPlug>( g_firstPlugIndex+2 ); } Gaffer::FloatVectorDataPlug *ImagePlug::channelDataPlug() { return getChild<FloatVectorDataPlug>( g_firstPlugIndex+3 ); } const Gaffer::FloatVectorDataPlug *ImagePlug::channelDataPlug() const { return getChild<FloatVectorDataPlug>( g_firstPlugIndex+3 ); } IECore::ConstFloatVectorDataPtr ImagePlug::channelData( const std::string &channelName, const Imath::V2i &tile ) const { if( direction()==In && !getInput<Plug>() ) { return channelDataPlug()->defaultValue(); } ContextPtr tmpContext = new Context( *Context::current() ); tmpContext->set( ImagePlug::channelNameContextName, channelName ); tmpContext->set( ImagePlug::tileOriginContextName, tile ); Context::Scope scopedContext( tmpContext ); return channelDataPlug()->getValue(); } IECore::MurmurHash ImagePlug::channelDataHash( const std::string &channelName, const Imath::V2i &tile ) const { if( direction()==In && !getInput<Plug>() ) { throw IECore::Exception( "ImagePlug::channelData called on unconnected input plug" ); } ContextPtr tmpContext = new Context( *Context::current() ); tmpContext->set( ImagePlug::channelNameContextName, channelName ); tmpContext->set( ImagePlug::tileOriginContextName, tile ); Context::Scope scopedContext( tmpContext ); return channelDataPlug()->hash(); } IECore::ImagePrimitivePtr ImagePlug::image() const { Box2i format = formatPlug()->getValue().getDisplayWindow(); Box2i dataWindow = dataWindowPlug()->getValue(); if( dataWindow.isEmpty() ) { dataWindow = Box2i( Imath::V2i(0) ); } ImagePrimitivePtr result = new ImagePrimitive( dataWindow, format ); ConstStringVectorDataPtr channelNamesData = channelNamesPlug()->getValue(); const vector<string> &channelNames = channelNamesData->readable(); vector<float *> imageChannelData; for( vector<string>::const_iterator it = channelNames.begin(), eIt = channelNames.end(); it!=eIt; it++ ) { FloatVectorDataPtr cd = new FloatVectorData; vector<float> &c = cd->writable(); c.resize( result->variableSize( PrimitiveVariable::Vertex ), 0.0f ); result->variables[*it] = PrimitiveVariable( PrimitiveVariable::Vertex, cd ); imageChannelData.push_back( &(c[0]) ); } parallel_for( blocked_range2d<size_t>( 0, dataWindow.size().x+1, tileSize(), 0, dataWindow.size().y+1, tileSize() ), GafferImage::Detail::CopyTiles( imageChannelData, channelNames, channelDataPlug(), dataWindow, Context::current(), tileSize()) ); return result; } IECore::MurmurHash ImagePlug::imageHash() const { const Box2i dataWindow = dataWindowPlug()->getValue(); ConstStringVectorDataPtr channelNamesData = channelNamesPlug()->getValue(); const vector<string> &channelNames = channelNamesData->readable(); MurmurHash result = formatPlug()->hash(); result.append( dataWindowPlug()->hash() ); result.append( channelNamesPlug()->hash() ); V2i minTileOrigin = tileOrigin( dataWindow.min ); V2i maxTileOrigin = tileOrigin( dataWindow.max ); ContextPtr context = new Context( *Context::current() ); for( vector<string>::const_iterator it = channelNames.begin(), eIt = channelNames.end(); it!=eIt; it++ ) { for( int tileOriginY = minTileOrigin.y; tileOriginY<=maxTileOrigin.y; tileOriginY += tileSize() ) { for( int tileOriginX = minTileOrigin.x; tileOriginX<=maxTileOrigin.x; tileOriginX += tileSize() ) { for( vector<string>::const_iterator it = channelNames.begin(), eIt = channelNames.end(); it!=eIt; it++ ) { context->set( ImagePlug::channelNameContextName, *it ); context->set( ImagePlug::tileOriginContextName, V2i( tileOriginX, tileOriginY ) ); Context::Scope scope( context ); channelDataPlug()->hash( result ); } } } } return result; } <commit_msg>Removed an invalid sanity check within GafferImage::ImagePlug.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. All rights reserved. // Copyright (c) 2012-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "tbb/tbb.h" #include "IECore/Exception.h" #include "IECore/BoxOps.h" #include "IECore/BoxAlgo.h" #include "Gaffer/Context.h" #include "GafferImage/ImagePlug.h" #include "GafferImage/FormatPlug.h" using namespace std; using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferImage; using namespace tbb; IE_CORE_DEFINERUNTIMETYPED( ImagePlug ); ////////////////////////////////////////////////////////////////////////// // Implementation of CopyTiles: // A simple class for multithreading the copying of // image tiles from an input plug to an output plug. ////////////////////////////////////////////////////////////////////////// namespace GafferImage { namespace Detail { class CopyTiles { public: CopyTiles( const vector<float *> &imageChannelData, const vector<string> &channelNames, const Gaffer::FloatVectorDataPlug *channelDataPlug, const Box2i& dataWindow, const Context *context, const int tileSize ) : m_imageChannelData( imageChannelData ), m_channelNames( channelNames ), m_channelDataPlug( channelDataPlug ), m_dataWindow( dataWindow ), m_parentContext( context ), m_tileSize( tileSize ) {} void operator()( const blocked_range2d<size_t>& r ) const { ContextPtr context = new Context( *m_parentContext ); const Box2i operationWindow( V2i( r.rows().begin()+m_dataWindow.min.x, r.cols().begin()+m_dataWindow.min.y ), V2i( r.rows().end()+m_dataWindow.min.x-1, r.cols().end()+m_dataWindow.min.y-1 ) ); V2i minTileOrigin = ImagePlug::tileOrigin( operationWindow.min ); V2i maxTileOrigin = ImagePlug::tileOrigin( operationWindow.max ); size_t imageStride = m_dataWindow.size().x + 1; for( int tileOriginY = minTileOrigin.y; tileOriginY <= maxTileOrigin.y; tileOriginY += m_tileSize ) { for( int tileOriginX = minTileOrigin.x; tileOriginX <= maxTileOrigin.x; tileOriginX += m_tileSize ) { for( vector<string>::const_iterator it = m_channelNames.begin(), eIt = m_channelNames.end(); it != eIt; it++ ) { context->set( ImagePlug::channelNameContextName, *it ); context->set( ImagePlug::tileOriginContextName, V2i( tileOriginX, tileOriginY ) ); Context::Scope scope( context ); Box2i tileBound( V2i( tileOriginX, tileOriginY ), V2i( tileOriginX + m_tileSize - 1, tileOriginY + m_tileSize - 1 ) ); Box2i b = boxIntersection( tileBound, operationWindow ); ConstFloatVectorDataPtr tileData = m_channelDataPlug->getValue(); for( int y = b.min.y; y<=b.max.y; y++ ) { const float *tilePtr = &(tileData->readable()[0]) + (y - tileOriginY) * m_tileSize + (b.min.x - tileOriginX); float *channelPtr = m_imageChannelData[it-m_channelNames.begin()] + ( y - m_dataWindow.min.y ) * imageStride + (b.min.x - m_dataWindow.min.x); for( int x = b.min.x; x <= b.max.x; x++ ) { *channelPtr++ = *tilePtr++; } } } } } } private: const vector<float *> &m_imageChannelData; const vector<string> &m_channelNames; const Gaffer::FloatVectorDataPlug *m_channelDataPlug; const Box2i &m_dataWindow; const Context *m_parentContext; const int m_tileSize; }; }; }; ////////////////////////////////////////////////////////////////////////// // Implementation of ImagePlug ////////////////////////////////////////////////////////////////////////// const IECore::InternedString ImagePlug::channelNameContextName = "image:channelName"; const IECore::InternedString ImagePlug::tileOriginContextName = "image:tileOrigin"; size_t ImagePlug::g_firstPlugIndex = 0; ImagePlug::ImagePlug( const std::string &name, Direction direction, unsigned flags ) : CompoundPlug( name, direction, flags ) { storeIndexOfNextChild( g_firstPlugIndex ); // we don't want the children to be serialised in any way - we always create // them ourselves in this constructor so they aren't Dynamic, and we don't ever // want to store their values because they are meaningless without an input // connection, so they aren't Serialisable either. unsigned childFlags = flags & ~(Dynamic | Serialisable); addChild( new FormatPlug( "format", direction, Format(), childFlags ) ); addChild( new AtomicBox2iPlug( "dataWindow", direction, Imath::Box2i(), childFlags ) ); IECore::StringVectorDataPtr channelStrVectorData( new IECore::StringVectorData() ); std::vector<std::string> &channelStrVector( channelStrVectorData->writable() ); channelStrVector.push_back("R"); channelStrVector.push_back("G"); channelStrVector.push_back("B"); addChild( new StringVectorDataPlug( "channelNames", direction, channelStrVectorData, childFlags ) ); addChild( new FloatVectorDataPlug( "channelData", direction, blackTile(), childFlags ) ); } ImagePlug::~ImagePlug() { } const IECore::FloatVectorData *ImagePlug::whiteTile() { static IECore::ConstFloatVectorDataPtr g_whiteTile( new IECore::FloatVectorData( std::vector<float>( ImagePlug::tileSize()*ImagePlug::tileSize(), 1. ) ) ); return g_whiteTile.get(); }; const IECore::FloatVectorData *ImagePlug::blackTile() { static IECore::ConstFloatVectorDataPtr g_blackTile( new IECore::FloatVectorData( std::vector<float>( ImagePlug::tileSize()*ImagePlug::tileSize(), 0. ) ) ); return g_blackTile.get(); }; bool ImagePlug::acceptsChild( const GraphComponent *potentialChild ) const { return children().size() != 4; } bool ImagePlug::acceptsInput( const Gaffer::Plug *input ) const { if( !CompoundPlug::acceptsInput( input ) ) { return false; } if( input ) { return input->isInstanceOf( staticTypeId() ); } return true; } Gaffer::PlugPtr ImagePlug::createCounterpart( const std::string &name, Direction direction ) const { return new ImagePlug( name, direction, getFlags() ); } GafferImage::FormatPlug *ImagePlug::formatPlug() { return getChild<FormatPlug>( g_firstPlugIndex ); } const GafferImage::FormatPlug *ImagePlug::formatPlug() const { return getChild<FormatPlug>( g_firstPlugIndex ); } Gaffer::AtomicBox2iPlug *ImagePlug::dataWindowPlug() { return getChild<AtomicBox2iPlug>( g_firstPlugIndex+1 ); } const Gaffer::AtomicBox2iPlug *ImagePlug::dataWindowPlug() const { return getChild<AtomicBox2iPlug>( g_firstPlugIndex+1 ); } Gaffer::StringVectorDataPlug *ImagePlug::channelNamesPlug() { return getChild<StringVectorDataPlug>( g_firstPlugIndex+2 ); } const Gaffer::StringVectorDataPlug *ImagePlug::channelNamesPlug() const { return getChild<StringVectorDataPlug>( g_firstPlugIndex+2 ); } Gaffer::FloatVectorDataPlug *ImagePlug::channelDataPlug() { return getChild<FloatVectorDataPlug>( g_firstPlugIndex+3 ); } const Gaffer::FloatVectorDataPlug *ImagePlug::channelDataPlug() const { return getChild<FloatVectorDataPlug>( g_firstPlugIndex+3 ); } IECore::ConstFloatVectorDataPtr ImagePlug::channelData( const std::string &channelName, const Imath::V2i &tile ) const { if( direction()==In && !getInput<Plug>() ) { return channelDataPlug()->defaultValue(); } ContextPtr tmpContext = new Context( *Context::current() ); tmpContext->set( ImagePlug::channelNameContextName, channelName ); tmpContext->set( ImagePlug::tileOriginContextName, tile ); Context::Scope scopedContext( tmpContext ); return channelDataPlug()->getValue(); } IECore::MurmurHash ImagePlug::channelDataHash( const std::string &channelName, const Imath::V2i &tile ) const { ContextPtr tmpContext = new Context( *Context::current() ); tmpContext->set( ImagePlug::channelNameContextName, channelName ); tmpContext->set( ImagePlug::tileOriginContextName, tile ); Context::Scope scopedContext( tmpContext ); return channelDataPlug()->hash(); } IECore::ImagePrimitivePtr ImagePlug::image() const { Box2i format = formatPlug()->getValue().getDisplayWindow(); Box2i dataWindow = dataWindowPlug()->getValue(); if( dataWindow.isEmpty() ) { dataWindow = Box2i( Imath::V2i(0) ); } ImagePrimitivePtr result = new ImagePrimitive( dataWindow, format ); ConstStringVectorDataPtr channelNamesData = channelNamesPlug()->getValue(); const vector<string> &channelNames = channelNamesData->readable(); vector<float *> imageChannelData; for( vector<string>::const_iterator it = channelNames.begin(), eIt = channelNames.end(); it!=eIt; it++ ) { FloatVectorDataPtr cd = new FloatVectorData; vector<float> &c = cd->writable(); c.resize( result->variableSize( PrimitiveVariable::Vertex ), 0.0f ); result->variables[*it] = PrimitiveVariable( PrimitiveVariable::Vertex, cd ); imageChannelData.push_back( &(c[0]) ); } parallel_for( blocked_range2d<size_t>( 0, dataWindow.size().x+1, tileSize(), 0, dataWindow.size().y+1, tileSize() ), GafferImage::Detail::CopyTiles( imageChannelData, channelNames, channelDataPlug(), dataWindow, Context::current(), tileSize()) ); return result; } IECore::MurmurHash ImagePlug::imageHash() const { const Box2i dataWindow = dataWindowPlug()->getValue(); ConstStringVectorDataPtr channelNamesData = channelNamesPlug()->getValue(); const vector<string> &channelNames = channelNamesData->readable(); MurmurHash result = formatPlug()->hash(); result.append( dataWindowPlug()->hash() ); result.append( channelNamesPlug()->hash() ); V2i minTileOrigin = tileOrigin( dataWindow.min ); V2i maxTileOrigin = tileOrigin( dataWindow.max ); ContextPtr context = new Context( *Context::current() ); for( vector<string>::const_iterator it = channelNames.begin(), eIt = channelNames.end(); it!=eIt; it++ ) { for( int tileOriginY = minTileOrigin.y; tileOriginY<=maxTileOrigin.y; tileOriginY += tileSize() ) { for( int tileOriginX = minTileOrigin.x; tileOriginX<=maxTileOrigin.x; tileOriginX += tileSize() ) { for( vector<string>::const_iterator it = channelNames.begin(), eIt = channelNames.end(); it!=eIt; it++ ) { context->set( ImagePlug::channelNameContextName, *it ); context->set( ImagePlug::tileOriginContextName, V2i( tileOriginX, tileOriginY ) ); Context::Scope scope( context ); channelDataPlug()->hash( result ); } } } } return result; } <|endoftext|>
<commit_before>#include "Genes/Look_Ahead_Gene.h" #include <cmath> #include <cassert> #include <memory> #include "Genes/Gene.h" #include "Utility.h" #include "Game/Board.h" #include "Game/Clock.h" #include "Moves/Move.h" Look_Ahead_Gene::Look_Ahead_Gene() : mean_game_length(50), game_length_uncertainty(0.5), speculation_constant(1.0), capturing_speculation_constant(1.0) { } void Look_Ahead_Gene::reset_properties() const { properties["Mean Game Length"] = mean_game_length; properties["Game Length Uncertainty"] = game_length_uncertainty; properties["Speculation Constant"] = speculation_constant; properties["Capturing Speculation Constant"] = capturing_speculation_constant; } void Look_Ahead_Gene::load_properties() { mean_game_length = properties["Mean Game Length"]; game_length_uncertainty = properties["Game Length Uncertainty"]; speculation_constant = properties["Speculation Constant"]; capturing_speculation_constant = properties["Capturing Speculation Constant"]; } double Look_Ahead_Gene::time_to_examine(const Board& board, const Clock& clock) const { auto time_left = clock.time_left(board.whose_turn()); auto moves_to_reset = clock.moves_to_reset(board.whose_turn()); auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player auto moves_left = Math::average_moves_left(mean_game_length, game_length_uncertainty, moves_so_far); return time_left/std::min(moves_left, double(moves_to_reset)); } void Look_Ahead_Gene::gene_specific_mutation() { switch(Random::random_integer(1, 4)) { case 1: mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0)); break; case 2: game_length_uncertainty = std::abs(game_length_uncertainty + Random::random_normal(0.05)); break; case 3: speculation_constant += Random::random_normal(0.001); break; case 4: capturing_speculation_constant += Random::random_normal(0.001); break; default: assert(false); // If here, random_integer() called with wrong parameters break; } } std::unique_ptr<Gene> Look_Ahead_Gene::duplicate() const { return std::make_unique<Look_Ahead_Gene>(*this); } std::string Look_Ahead_Gene::name() const { return "Look Ahead Gene"; } double Look_Ahead_Gene::score_board(const Board&) const { return 0.0; } double Look_Ahead_Gene::speculation_time_factor(const Board& board) const { return board.capture_possible() ? capturing_speculation_constant : speculation_constant; } <commit_msg>Increase mutation rate of speculation constants<commit_after>#include "Genes/Look_Ahead_Gene.h" #include <cmath> #include <cassert> #include <memory> #include "Genes/Gene.h" #include "Utility.h" #include "Game/Board.h" #include "Game/Clock.h" #include "Moves/Move.h" Look_Ahead_Gene::Look_Ahead_Gene() : mean_game_length(50), game_length_uncertainty(0.5), speculation_constant(1.0), capturing_speculation_constant(1.0) { } void Look_Ahead_Gene::reset_properties() const { properties["Mean Game Length"] = mean_game_length; properties["Game Length Uncertainty"] = game_length_uncertainty; properties["Speculation Constant"] = speculation_constant; properties["Capturing Speculation Constant"] = capturing_speculation_constant; } void Look_Ahead_Gene::load_properties() { mean_game_length = properties["Mean Game Length"]; game_length_uncertainty = properties["Game Length Uncertainty"]; speculation_constant = properties["Speculation Constant"]; capturing_speculation_constant = properties["Capturing Speculation Constant"]; } double Look_Ahead_Gene::time_to_examine(const Board& board, const Clock& clock) const { auto time_left = clock.time_left(board.whose_turn()); auto moves_to_reset = clock.moves_to_reset(board.whose_turn()); auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player auto moves_left = Math::average_moves_left(mean_game_length, game_length_uncertainty, moves_so_far); return time_left/std::min(moves_left, double(moves_to_reset)); } void Look_Ahead_Gene::gene_specific_mutation() { switch(Random::random_integer(1, 4)) { case 1: mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0)); break; case 2: game_length_uncertainty = std::abs(game_length_uncertainty + Random::random_normal(0.05)); break; case 3: speculation_constant += Random::random_normal(0.01); break; case 4: capturing_speculation_constant += Random::random_normal(0.01); break; default: assert(false); // If here, random_integer() called with wrong parameters break; } } std::unique_ptr<Gene> Look_Ahead_Gene::duplicate() const { return std::make_unique<Look_Ahead_Gene>(*this); } std::string Look_Ahead_Gene::name() const { return "Look Ahead Gene"; } double Look_Ahead_Gene::score_board(const Board&) const { return 0.0; } double Look_Ahead_Gene::speculation_time_factor(const Board& board) const { return board.capture_possible() ? capturing_speculation_constant : speculation_constant; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2011, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" // this must come first! #include "IECore/MemoryIndexedIO.h" #include "IECore/HexConversion.h" #include "IECorePython/ScopedGILLock.h" #include "IECoreNuke/ObjectKnob.h" using namespace IECoreNuke; using namespace DD::Image; using namespace boost::python; ObjectKnob::ObjectKnob( DD::Image::Knob_Closure *f, IECore::ObjectPtr *storage, const char *name, const char *label ) : DD::Image::Knob( f, name, label ), m_defaultValue( 0 ), m_value( 0 ) { set_flag( NO_ANIMATION ); if( storage && *storage ) { m_defaultValue = (*storage)->copy(); m_value = m_defaultValue; } // set up the object that will provide the python binding IECorePython::ScopedGILLock gilLock; Detail::PythonObjectKnobPtr pythonKnob = new Detail::PythonObjectKnob; pythonKnob->objectKnob = this; object pythonKnobObject( pythonKnob ); Py_INCREF( pythonKnobObject.ptr() ); setPyObject( pythonKnobObject.ptr() ); } ObjectKnob::~ObjectKnob() { // tidy up the object for the python binding IECorePython::ScopedGILLock gilLock; object pythonKnobObject( handle<>( borrowed( (PyObject *)pyObject() ) ) ); Detail::PythonObjectKnobPtr pythonKnob = extract<Detail::PythonObjectKnobPtr>( pythonKnobObject ); pythonKnob->objectKnob = 0; Py_DECREF( pythonKnobObject.ptr() ); } bool ObjectKnob::setValue( IECore::ConstObjectPtr value ) { if( !valuesEqual( m_value, value ) ) { new_undo(); m_value = value ? value->copy() : 0; changed(); return true; } return false; } IECore::ConstObjectPtr ObjectKnob::getValue() const { return m_value; } ObjectKnob *ObjectKnob::objectKnob( DD::Image::Knob_Callback f, IECore::ObjectPtr *storage, const char *name, const char *label ) { return CustomKnob2( ObjectKnob, f, storage, name, label ); } const char *ObjectKnob::Class() const { return "ObjectKnob"; } void ObjectKnob::to_script( std::ostream &os, const DD::Image::OutputContext *context, bool quote ) const { if( quote ) { os << "{"; } if( m_value ) { IECore::MemoryIndexedIOPtr io = new IECore::MemoryIndexedIO( IECore::ConstCharVectorDataPtr(), "/", IECore::IndexedIO::Exclusive | IECore::IndexedIO::Write ); m_value->save( io, "object" ); IECore::ConstCharVectorDataPtr buffer = io->buffer(); os << IECore::decToHex( buffer->readable().begin(), buffer->readable().end() ); } if( quote ) { os << "}"; } } bool ObjectKnob::from_script( const char *value ) { IECore::ObjectPtr object = m_defaultValue; if( value && strlen( value ) ) { size_t n = strlen( value ); IECore::CharVectorDataPtr buffer = new IECore::CharVectorData; buffer->writable().resize( n / 2 ); IECore::hexToDec<char>( value, value + n, buffer->writable().begin() ); try { IECore::MemoryIndexedIOPtr io = new IECore::MemoryIndexedIO( buffer, "/", IECore::IndexedIO::Exclusive | IECore::IndexedIO::Read ); object = IECore::Object::load( io, "object" ); } catch( std::exception &e ) { error( e.what() ); } } return setValue( object ); } bool ObjectKnob::not_default() const { return !valuesEqual( m_value, m_defaultValue ); } void ObjectKnob::store( DD::Image::StoreType storeType, void *storage, DD::Image::Hash &hash, const DD::Image::OutputContext &context ) { assert( storeType == DD::Image::Custom ); if( storage ) { *((IECore::ObjectPtr *)storage) = m_value; } } bool ObjectKnob::valuesEqual( const IECore::Object *value1, const IECore::Object *value2 ) const { bool equal = true; if( value2 ) { equal = value1 && value1->isEqualTo( value2 ); } else { equal = !value1; } return equal; } <commit_msg>Fixing compiling problems when APP=nuke.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" // this must come first! #include "IECore/MemoryIndexedIO.h" #include "IECore/HexConversion.h" #include "IECorePython/ScopedGILLock.h" #include "IECoreNuke/ObjectKnob.h" using namespace IECoreNuke; using namespace DD::Image; using namespace boost::python; ObjectKnob::ObjectKnob( DD::Image::Knob_Closure *f, IECore::ObjectPtr *storage, const char *name, const char *label ) : DD::Image::Knob( f, name, label ), m_defaultValue( 0 ), m_value( 0 ) { set_flag( NO_ANIMATION ); if( storage && *storage ) { m_defaultValue = (*storage)->copy(); m_value = m_defaultValue; } // set up the object that will provide the python binding IECorePython::ScopedGILLock gilLock; Detail::PythonObjectKnobPtr pythonKnob = new Detail::PythonObjectKnob; pythonKnob->objectKnob = this; object pythonKnobObject( pythonKnob ); Py_INCREF( pythonKnobObject.ptr() ); setPyObject( pythonKnobObject.ptr() ); } ObjectKnob::~ObjectKnob() { // tidy up the object for the python binding IECorePython::ScopedGILLock gilLock; object pythonKnobObject( handle<>( borrowed( (PyObject *)pyObject() ) ) ); Detail::PythonObjectKnobPtr pythonKnob = extract<Detail::PythonObjectKnobPtr>( pythonKnobObject ); pythonKnob->objectKnob = 0; Py_DECREF( pythonKnobObject.ptr() ); } bool ObjectKnob::setValue( IECore::ConstObjectPtr value ) { if( !valuesEqual( m_value, value ) ) { new_undo(); m_value = value ? value->copy() : 0; changed(); return true; } return false; } IECore::ConstObjectPtr ObjectKnob::getValue() const { return m_value; } ObjectKnob *ObjectKnob::objectKnob( DD::Image::Knob_Callback f, IECore::ObjectPtr *storage, const char *name, const char *label ) { return CustomKnob2( ObjectKnob, f, storage, name, label ); } const char *ObjectKnob::Class() const { return "ObjectKnob"; } void ObjectKnob::to_script( std::ostream &os, const DD::Image::OutputContext *context, bool quote ) const { if( quote ) { os << "{"; } if( m_value ) { IECore::MemoryIndexedIOPtr io = new IECore::MemoryIndexedIO( IECore::ConstCharVectorDataPtr(), IECore::IndexedIO::rootPath, IECore::IndexedIO::Exclusive | IECore::IndexedIO::Write ); m_value->save( io, "object" ); IECore::ConstCharVectorDataPtr buffer = io->buffer(); os << IECore::decToHex( buffer->readable().begin(), buffer->readable().end() ); } if( quote ) { os << "}"; } } bool ObjectKnob::from_script( const char *value ) { IECore::ObjectPtr object = m_defaultValue; if( value && strlen( value ) ) { size_t n = strlen( value ); IECore::CharVectorDataPtr buffer = new IECore::CharVectorData; buffer->writable().resize( n / 2 ); IECore::hexToDec<char>( value, value + n, buffer->writable().begin() ); try { IECore::MemoryIndexedIOPtr io = new IECore::MemoryIndexedIO( buffer, IECore::IndexedIO::rootPath, IECore::IndexedIO::Exclusive | IECore::IndexedIO::Read ); object = IECore::Object::load( io, "object" ); } catch( std::exception &e ) { error( e.what() ); } } return setValue( object ); } bool ObjectKnob::not_default() const { return !valuesEqual( m_value, m_defaultValue ); } void ObjectKnob::store( DD::Image::StoreType storeType, void *storage, DD::Image::Hash &hash, const DD::Image::OutputContext &context ) { assert( storeType == DD::Image::Custom ); if( storage ) { *((IECore::ObjectPtr *)storage) = m_value; } } bool ObjectKnob::valuesEqual( const IECore::Object *value1, const IECore::Object *value2 ) const { bool equal = true; if( value2 ) { equal = value1 && value1->isEqualTo( value2 ); } else { equal = !value1; } return equal; } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "IndexWriter.h" #include <fnord-fts/AnalyzerAdapter.h> using namespace fnord; namespace cm { RefPtr<IndexWriter> IndexWriter::openIndex( const String& index_path, const String& conf_path) { if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) { RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path); } /* set up feature schema */ FeatureSchema feature_schema; feature_schema.registerFeature("shop_id", 1, 1); feature_schema.registerFeature("category1", 2, 1); feature_schema.registerFeature("category2", 3, 1); feature_schema.registerFeature("category3", 4, 1); feature_schema.registerFeature("price_cents", 8, 1); feature_schema.registerFeature("title~de", 5, 2); feature_schema.registerFeature("description~de", 6, 2); feature_schema.registerFeature("size_description~de", 14, 2); feature_schema.registerFeature("material_description~de", 15, 2); feature_schema.registerFeature("basic_attributes~de", 16, 2); feature_schema.registerFeature("tags_as_text~de", 7, 2); feature_schema.registerFeature("title~pl", 18, 2); feature_schema.registerFeature("description~pl", 19, 2); feature_schema.registerFeature("size_description~pl", 20, 2); feature_schema.registerFeature("material_description~pl", 21, 2); feature_schema.registerFeature("basic_attributes~pl", 22, 2); feature_schema.registerFeature("tags_as_text~pl", 23, 2); feature_schema.registerFeature("image_filename", 24, 2); feature_schema.registerFeature("cm_clicked_terms", 31, 2); feature_schema.registerFeature("shop_name", 26, 3); feature_schema.registerFeature("shop_platform", 27, 3); feature_schema.registerFeature("shop_country", 28, 3); feature_schema.registerFeature("shop_rating_alt", 9, 3); feature_schema.registerFeature("shop_rating_alt2", 15, 3); feature_schema.registerFeature("shop_products_count", 10, 3); feature_schema.registerFeature("shop_orders_count", 11, 3); feature_schema.registerFeature("shop_rating_count", 12, 3); feature_schema.registerFeature("shop_rating_avg", 13, 3); feature_schema.registerFeature("cm_views", 29, 3); feature_schema.registerFeature("cm_clicks", 30, 3); feature_schema.registerFeature("cm_ctr", 32, 3); feature_schema.registerFeature("cm_ctr_norm", 33, 3); feature_schema.registerFeature("cm_ctr_std", 34, 3); feature_schema.registerFeature("cm_ctr_norm_std", 35, 3); /* open mdb */ auto db_path = FileUtil::joinPaths(index_path, "db"); FileUtil::mkdir_p(db_path); auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB /* open lucene */ RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path)); auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer); auto fts_path = FileUtil::joinPaths(index_path, "fts"); bool create = false; if (!FileUtil::exists(fts_path)) { FileUtil::mkdir_p(fts_path); create = true; } auto fts = fts::newLucene<fts::IndexWriter>( fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)), adapter, create, fts::IndexWriter::MaxFieldLengthLIMITED); return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts)); } IndexWriter::IndexWriter( FeatureSchema schema, RefPtr<mdb::MDB> db, std::shared_ptr<fts::IndexWriter> fts) : schema_(schema), db_(db), db_txn_(db_->startTransaction()), feature_idx_(new FeatureIndexWriter(&schema_)), fts_(fts) {} IndexWriter::~IndexWriter() { if (db_txn_.get()) { db_txn_->commit(); } fts_->close(); } void IndexWriter::updateDocument(const IndexRequest& index_request) { stat_documents_indexed_total_.incr(1); auto docid = index_request.item.docID(); feature_idx_->updateDocument(index_request, db_txn_.get()); auto doc = feature_idx_->findDocument(docid, db_txn_.get()); rebuildFTS(doc); stat_documents_indexed_success_.incr(1); } void IndexWriter::commit() { db_txn_->commit(); db_txn_ = db_->startTransaction(); fts_->commit(); } void IndexWriter::rebuildFTS(DocID docid) { auto doc = feature_idx_->findDocument(docid, db_txn_.get()); doc->debugPrint(); rebuildFTS(doc); } void IndexWriter::rebuildFTS(RefPtr<Document> doc) { stat_documents_indexed_fts_.incr(1); auto fts_doc = fts::newLucene<fts::Document>(); fts_doc->add( fts::newLucene<fts::Field>( L"_docid", StringUtil::convertUTF8To16(doc->docID().docid), fts::Field::STORE_YES, fts::Field::INDEX_NOT_ANALYZED_NO_NORMS)); double boost = 1.0; double cm_clicks = 0; double cm_views = 0; double cm_ctr_norm_std = 1.0; HashMap<String, String> fts_fields_anal; for (const auto& f : doc->fields()) { /* title~LANG */ if (StringUtil::beginsWith(f.first, "title~")) { auto k = f.first; StringUtil::replaceAll(&k, "title~","title~"); fts_fields_anal[k] += " " + f.second; } /* description~LANG */ else if (StringUtil::beginsWith(f.first, "description~")) { auto k = f.first; StringUtil::replaceAll(&k, "description~","text~"); fts_fields_anal[k] += " " + f.second; } /* size_description~LANG */ else if (StringUtil::beginsWith(f.first, "size_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "size_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* material_description~LANG */ else if (StringUtil::beginsWith(f.first, "material_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "material_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* manufacturing_description~LANG */ else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "manufacturing_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* tags_as_text~LANG */ else if (StringUtil::beginsWith(f.first, "tags_as_text~")) { fts_fields_anal["tags"] += " " + f.second; } /* shop_name */ else if (f.first == "shop_name") { fts_fields_anal["tags"] += " " + f.second; } /* cm_clicked_terms */ else if (f.first == "cm_clicked_terms") { fts_doc->add( fts::newLucene<fts::Field>( L"cm_clicked_terms", StringUtil::convertUTF8To16(f.second), fts::Field::STORE_NO, fts::Field::INDEX_ANALYZED)); } else if (f.first == "cm_ctr_norm_std") { cm_ctr_norm_std = std::stod(f.second); } else if (f.first == "cm_clicks") { cm_clicks = std::stod(f.second); } else if (f.first == "cm_views") { cm_views = std::stod(f.second); } } for (const auto& f : fts_fields_anal) { fts_doc->add( fts::newLucene<fts::Field>( StringUtil::convertUTF8To16(f.first), StringUtil::convertUTF8To16(f.second), fts::Field::STORE_NO, fts::Field::INDEX_ANALYZED)); } if (cm_views > 2000) { boost = cm_ctr_norm_std; } fts_doc->setBoost(boost); fnord::logDebug( "cm.indexwriter", "Rebuilding FTS Index for docid=$0 boost=$1", doc->docID().docid, boost); auto del_term = fts::newLucene<fts::Term>( L"_docid", StringUtil::convertUTF8To16(doc->docID().docid)); fts_->updateDocument(del_term, fts_doc); } void IndexWriter::rebuildFTS() { //docs_->listDocuments([this] (const DocID& docid) -> bool { // rebuildFTS(docid); // return true; //}); } RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() { return db_txn_; } void IndexWriter::exportStats(const String& prefix) { exportStat( StringUtil::format("$0/documents_indexed_total", prefix), &stat_documents_indexed_total_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_success", prefix), &stat_documents_indexed_success_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_error", prefix), &stat_documents_indexed_error_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_fts", prefix), &stat_documents_indexed_fts_, fnord::stats::ExportMode::EXPORT_DELTA); } } // namespace cm <commit_msg>adjust thresholds<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "IndexWriter.h" #include <fnord-fts/AnalyzerAdapter.h> using namespace fnord; namespace cm { RefPtr<IndexWriter> IndexWriter::openIndex( const String& index_path, const String& conf_path) { if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) { RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path); } /* set up feature schema */ FeatureSchema feature_schema; feature_schema.registerFeature("shop_id", 1, 1); feature_schema.registerFeature("category1", 2, 1); feature_schema.registerFeature("category2", 3, 1); feature_schema.registerFeature("category3", 4, 1); feature_schema.registerFeature("price_cents", 8, 1); feature_schema.registerFeature("title~de", 5, 2); feature_schema.registerFeature("description~de", 6, 2); feature_schema.registerFeature("size_description~de", 14, 2); feature_schema.registerFeature("material_description~de", 15, 2); feature_schema.registerFeature("basic_attributes~de", 16, 2); feature_schema.registerFeature("tags_as_text~de", 7, 2); feature_schema.registerFeature("title~pl", 18, 2); feature_schema.registerFeature("description~pl", 19, 2); feature_schema.registerFeature("size_description~pl", 20, 2); feature_schema.registerFeature("material_description~pl", 21, 2); feature_schema.registerFeature("basic_attributes~pl", 22, 2); feature_schema.registerFeature("tags_as_text~pl", 23, 2); feature_schema.registerFeature("image_filename", 24, 2); feature_schema.registerFeature("cm_clicked_terms", 31, 2); feature_schema.registerFeature("shop_name", 26, 3); feature_schema.registerFeature("shop_platform", 27, 3); feature_schema.registerFeature("shop_country", 28, 3); feature_schema.registerFeature("shop_rating_alt", 9, 3); feature_schema.registerFeature("shop_rating_alt2", 15, 3); feature_schema.registerFeature("shop_products_count", 10, 3); feature_schema.registerFeature("shop_orders_count", 11, 3); feature_schema.registerFeature("shop_rating_count", 12, 3); feature_schema.registerFeature("shop_rating_avg", 13, 3); feature_schema.registerFeature("cm_views", 29, 3); feature_schema.registerFeature("cm_clicks", 30, 3); feature_schema.registerFeature("cm_ctr", 32, 3); feature_schema.registerFeature("cm_ctr_norm", 33, 3); feature_schema.registerFeature("cm_ctr_std", 34, 3); feature_schema.registerFeature("cm_ctr_norm_std", 35, 3); /* open mdb */ auto db_path = FileUtil::joinPaths(index_path, "db"); FileUtil::mkdir_p(db_path); auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB /* open lucene */ RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path)); auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer); auto fts_path = FileUtil::joinPaths(index_path, "fts"); bool create = false; if (!FileUtil::exists(fts_path)) { FileUtil::mkdir_p(fts_path); create = true; } auto fts = fts::newLucene<fts::IndexWriter>( fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)), adapter, create, fts::IndexWriter::MaxFieldLengthLIMITED); return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts)); } IndexWriter::IndexWriter( FeatureSchema schema, RefPtr<mdb::MDB> db, std::shared_ptr<fts::IndexWriter> fts) : schema_(schema), db_(db), db_txn_(db_->startTransaction()), feature_idx_(new FeatureIndexWriter(&schema_)), fts_(fts) {} IndexWriter::~IndexWriter() { if (db_txn_.get()) { db_txn_->commit(); } fts_->close(); } void IndexWriter::updateDocument(const IndexRequest& index_request) { stat_documents_indexed_total_.incr(1); auto docid = index_request.item.docID(); feature_idx_->updateDocument(index_request, db_txn_.get()); auto doc = feature_idx_->findDocument(docid, db_txn_.get()); rebuildFTS(doc); stat_documents_indexed_success_.incr(1); } void IndexWriter::commit() { db_txn_->commit(); db_txn_ = db_->startTransaction(); fts_->commit(); } void IndexWriter::rebuildFTS(DocID docid) { auto doc = feature_idx_->findDocument(docid, db_txn_.get()); doc->debugPrint(); rebuildFTS(doc); } void IndexWriter::rebuildFTS(RefPtr<Document> doc) { stat_documents_indexed_fts_.incr(1); auto fts_doc = fts::newLucene<fts::Document>(); fts_doc->add( fts::newLucene<fts::Field>( L"_docid", StringUtil::convertUTF8To16(doc->docID().docid), fts::Field::STORE_YES, fts::Field::INDEX_NOT_ANALYZED_NO_NORMS)); double boost = 1.0; double cm_clicks = 0; double cm_views = 0; double cm_ctr_norm_std = 1.0; HashMap<String, String> fts_fields_anal; for (const auto& f : doc->fields()) { /* title~LANG */ if (StringUtil::beginsWith(f.first, "title~")) { auto k = f.first; StringUtil::replaceAll(&k, "title~","title~"); fts_fields_anal[k] += " " + f.second; } /* description~LANG */ else if (StringUtil::beginsWith(f.first, "description~")) { auto k = f.first; StringUtil::replaceAll(&k, "description~","text~"); fts_fields_anal[k] += " " + f.second; } /* size_description~LANG */ else if (StringUtil::beginsWith(f.first, "size_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "size_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* material_description~LANG */ else if (StringUtil::beginsWith(f.first, "material_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "material_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* manufacturing_description~LANG */ else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "manufacturing_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* tags_as_text~LANG */ else if (StringUtil::beginsWith(f.first, "tags_as_text~")) { fts_fields_anal["tags"] += " " + f.second; } /* shop_name */ else if (f.first == "shop_name") { fts_fields_anal["tags"] += " " + f.second; } /* cm_clicked_terms */ else if (f.first == "cm_clicked_terms") { fts_doc->add( fts::newLucene<fts::Field>( L"cm_clicked_terms", StringUtil::convertUTF8To16(f.second), fts::Field::STORE_NO, fts::Field::INDEX_ANALYZED)); } else if (f.first == "cm_ctr_norm_std") { cm_ctr_norm_std = std::stod(f.second); } else if (f.first == "cm_clicks") { cm_clicks = std::stod(f.second); } else if (f.first == "cm_views") { cm_views = std::stod(f.second); } } for (const auto& f : fts_fields_anal) { fts_doc->add( fts::newLucene<fts::Field>( StringUtil::convertUTF8To16(f.first), StringUtil::convertUTF8To16(f.second), fts::Field::STORE_NO, fts::Field::INDEX_ANALYZED)); } if (cm_views > 1000 && cm_clicks > 15) { boost = cm_ctr_norm_std; } fts_doc->setBoost(boost); fnord::logDebug( "cm.indexwriter", "Rebuilding FTS Index for docid=$0 boost=$1", doc->docID().docid, boost); auto del_term = fts::newLucene<fts::Term>( L"_docid", StringUtil::convertUTF8To16(doc->docID().docid)); fts_->updateDocument(del_term, fts_doc); } void IndexWriter::rebuildFTS() { //docs_->listDocuments([this] (const DocID& docid) -> bool { // rebuildFTS(docid); // return true; //}); } RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() { return db_txn_; } void IndexWriter::exportStats(const String& prefix) { exportStat( StringUtil::format("$0/documents_indexed_total", prefix), &stat_documents_indexed_total_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_success", prefix), &stat_documents_indexed_success_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_error", prefix), &stat_documents_indexed_error_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_fts", prefix), &stat_documents_indexed_fts_, fnord::stats::ExportMode::EXPORT_DELTA); } } // namespace cm <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_JSON_ERROR_HANDLER_HPP #define MAPNIK_JSON_ERROR_HANDLER_HPP #include <string> #include <sstream> #include <boost/spirit/home/support/info.hpp> namespace mapnik { namespace json { template <typename Iterator> struct error_handler { using result_type = void; void operator() ( Iterator, Iterator last, Iterator err_pos, boost::spirit::info const& what) const { std::stringstream s; auto start = err_pos; std::advance(err_pos,16); auto end = err_pos; s << what << " expected but got: " << std::string(start, end); throw std::runtime_error(s.str()); } }; }} #endif // MAPNIK_JSON_ERROR_HANDLER_HPP <commit_msg>json error handler: fix -Wunused-parameter warning<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_JSON_ERROR_HANDLER_HPP #define MAPNIK_JSON_ERROR_HANDLER_HPP #include <string> #include <sstream> #include <boost/spirit/home/support/info.hpp> namespace mapnik { namespace json { template <typename Iterator> struct error_handler { using result_type = void; void operator() ( Iterator, Iterator, Iterator err_pos, boost::spirit::info const& what) const { std::stringstream s; auto start = err_pos; std::advance(err_pos,16); auto end = err_pos; s << what << " expected but got: " << std::string(start, end); throw std::runtime_error(s.str()); } }; }} #endif // MAPNIK_JSON_ERROR_HANDLER_HPP <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <string> #include <array> #include <forward_list> #include <sstream> #include <memory> #include <utility> #include <chrono> #include <iomanip> #include <functional> #include <stdexcept> namespace wonder_rabbit_project { namespace log { enum class level_e : std::uint8_t { none = 0 , debug = 1 , info = 2 , warn = 3 , error = 4 , fatal = 5 }; static auto to_string(level_e a) -> std::string { switch(a) { case level_e::none : return "none"; case level_e::debug: return "debug"; case level_e::info : return "info"; case level_e::warn : return "warn"; case level_e::error: return "error"; case level_e::fatal: return "fatal"; } throw std::logic_error("unknown level_e value"); } class log_stream_t; struct log_line_t { std::chrono::time_point<std::chrono::high_resolution_clock> time; level_e level; std::string message; auto to_string() const -> std::string { std::ostringstream r; r << std::chrono::duration_cast<std::chrono::nanoseconds>(time.time_since_epoch()).count() << "\t" << std::setw(11) << std::left << wonder_rabbit_project::log::to_string(level) << "\t" << message << "\n" ; return r.str(); } }; class log_t { friend class log_stream_t; public: using data_type = std::forward_list<log_line_t>; using hook_type = std::function<log_line_t&(log_line_t&)>; using destruct_hook_type = std::function<void(const data_type&)>; class log_stream_t { log_t& _master; level_e _level; const std::shared_ptr<std::ostringstream> _stream; public: template<class T> auto operator<<(const T& a) -> log_stream_t& { (*_stream) << a; return *this; } explicit log_stream_t(log_t& a, level_e b) : _master(a) , _level(b) , _stream(new std::ostringstream()) { } ~log_stream_t() { _master._append ( { std::chrono::high_resolution_clock::now() , _level , _stream->str() } ); } }; protected: data_type _log; level_e _default_level; level_e _keep_level; level_e _hook_level; hook_type _hook; destruct_hook_type _at_destruct_hook; auto _append(log_line_t&& line) -> void { if(std::uint8_t(line.level) >= std::uint8_t(_hook_level)) _hook(line); if(std::uint8_t(line.level) >= std::uint8_t(_keep_level)) _log.emplace_front( std::move(line) ); } public: log_t() : _default_level(level_e::info) , _keep_level(level_e::debug) , _hook_level(level_e::none) , _hook( [](log_line_t& line) -> log_line_t& { return line; } ) , _at_destruct_hook( [](const data_type&){} ) { } ~log_t() { _at_destruct_hook(_log); } auto operator()() -> log_stream_t { return (*this)(_default_level); } auto operator()(level_e level) -> log_stream_t { return log_stream_t(*this, level); } auto clear() -> void { _log.clear(); } auto begin() -> decltype(data_type().begin()) { return _log.begin(); } auto end() -> decltype(data_type().end()) { return _log.end(); } auto cbegin() -> decltype(data_type().cbegin()) { return _log.cbegin(); } auto cend() -> decltype(data_type().cend()) { return _log.cend(); } auto str() -> std::string { std::ostringstream r; for(auto line: _log) r << line.to_string(); return r.str(); } auto default_level(level_e level) -> void { _default_level = level; } auto keep_level(level_e level) -> void { _keep_level = level; } auto hook_level(level_e level) -> void { _hook_level = level; } auto hook(hook_type&& h) -> void { _hook = std::move(h); } auto at_destruct(destruct_hook_type&& h) -> void { _at_destruct_hook = std::move(h); } }; static auto hook_tie(std::ostream& s) -> log_t::hook_type { return [&s](log_line_t& log_line) -> log_line_t& { s << log_line.to_string(); return log_line; }; } } }<commit_msg>anti-warning<commit_after>#pragma once #include <cstdint> #include <string> #include <array> #include <forward_list> #include <sstream> #include <memory> #include <utility> #include <chrono> #include <iomanip> #include <functional> #include <stdexcept> namespace wonder_rabbit_project { namespace log { enum class level_e : std::uint8_t { none = 0 , debug = 1 , info = 2 , warn = 3 , error = 4 , fatal = 5 }; static auto to_string(level_e a) -> std::string { switch(a) { case level_e::none : return "none"; case level_e::debug: return "debug"; case level_e::info : return "info"; case level_e::warn : return "warn"; case level_e::error: return "error"; case level_e::fatal: return "fatal"; } throw std::logic_error("unknown level_e value"); } class log_stream_t; struct log_line_t { std::chrono::time_point<std::chrono::high_resolution_clock> time; level_e level; std::string message; auto to_string() const -> std::string { std::ostringstream r; r << std::chrono::duration_cast<std::chrono::nanoseconds>(time.time_since_epoch()).count() << "\t" << std::setw(11) << std::left << wonder_rabbit_project::log::to_string(level) << "\t" << message << "\n" ; return r.str(); } }; class log_t { friend class log_stream_t; public: using data_type = std::forward_list<log_line_t>; using hook_type = std::function<log_line_t&(log_line_t&)>; using destruct_hook_type = std::function<void(const data_type&)>; class log_stream_t { log_t& _master; level_e _level; const std::shared_ptr<std::ostringstream> _stream; public: template<class T> auto operator<<(const T& a) -> log_stream_t& { (*_stream) << a; return *this; } explicit log_stream_t(log_t& a, level_e b) : _master(a) , _level(b) , _stream(new std::ostringstream()) { } ~log_stream_t() { _master._append ( { std::chrono::high_resolution_clock::now() , _level , _stream->str() } ); } }; protected: data_type _log; level_e _default_level; level_e _keep_level; level_e _hook_level; hook_type _hook; destruct_hook_type _at_destruct_hook; auto _append(log_line_t&& line) -> void { if(std::uint8_t(line.level) >= std::uint8_t(_hook_level)) _hook(line); if(std::uint8_t(line.level) >= std::uint8_t(_keep_level)) _log.emplace_front( std::move(line) ); } public: log_t() : _default_level(level_e::info) , _keep_level(level_e::debug) , _hook_level(level_e::none) , _hook( [](log_line_t& line) -> log_line_t& { return line; } ) , _at_destruct_hook( [](const data_type&){} ) { } ~log_t() { _at_destruct_hook(_log); } auto operator()() -> log_stream_t { return (*this)(_default_level); } auto operator()(level_e level) -> log_stream_t { return log_stream_t(*this, level); } auto clear() -> void { _log.clear(); } auto begin() -> decltype(data_type().begin()) { return _log.begin(); } auto end() -> decltype(data_type().end()) { return _log.end(); } auto cbegin() -> decltype(data_type().cbegin()) { return _log.cbegin(); } auto cend() -> decltype(data_type().cend()) { return _log.cend(); } auto str() -> std::string { std::ostringstream r; for(auto line: _log) r << line.to_string(); return r.str(); } auto default_level(level_e level) -> void { _default_level = level; } auto keep_level(level_e level) -> void { _keep_level = level; } auto hook_level(level_e level) -> void { _hook_level = level; } auto hook(hook_type&& h) -> void { _hook = std::move(h); } auto at_destruct(destruct_hook_type&& h) -> void { _at_destruct_hook = std::move(h); } }; template<class T = void> static auto hook_tie(std::ostream& s) -> log_t::hook_type { return [&s](log_line_t& log_line) -> log_line_t& { s << log_line.to_string(); return log_line; }; } } }<|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_CONFIG_HPP #define XSIMD_CONFIG_HPP #include "xsimd_align.hpp" #define XSIMD_VERSION_MAJOR 7 #define XSIMD_VERSION_MINOR 2 #define XSIMD_VERSION_PATCH 3 #ifndef XSIMD_DEFAULT_ALLOCATOR #if XSIMD_X86_INSTR_SET_AVAILABLE #define XSIMD_DEFAULT_ALLOCATOR(T) xsimd::aligned_allocator<T, XSIMD_DEFAULT_ALIGNMENT> #else #define XSIMD_DEFAULT_ALLOCATOR(T) std::allocator<T> #endif #endif #ifndef XSIMD_STACK_ALLOCATION_LIMIT #define XSIMD_STACK_ALLOCATION_LIMIT 20000 #endif #if defined(__LP64__) || defined(_WIN64) #define XSIMD_64_BIT_ABI #else #define XSIMD_32_BIT_ABI #endif #endif <commit_msg>Release 7.2.4<commit_after>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_CONFIG_HPP #define XSIMD_CONFIG_HPP #include "xsimd_align.hpp" #define XSIMD_VERSION_MAJOR 7 #define XSIMD_VERSION_MINOR 2 #define XSIMD_VERSION_PATCH 4 #ifndef XSIMD_DEFAULT_ALLOCATOR #if XSIMD_X86_INSTR_SET_AVAILABLE #define XSIMD_DEFAULT_ALLOCATOR(T) xsimd::aligned_allocator<T, XSIMD_DEFAULT_ALIGNMENT> #else #define XSIMD_DEFAULT_ALLOCATOR(T) std::allocator<T> #endif #endif #ifndef XSIMD_STACK_ALLOCATION_LIMIT #define XSIMD_STACK_ALLOCATION_LIMIT 20000 #endif #if defined(__LP64__) || defined(_WIN64) #define XSIMD_64_BIT_ABI #else #define XSIMD_32_BIT_ABI #endif #endif <|endoftext|>
<commit_before>#ifndef ORG_EEROS_SEQUENCER_SEQUENCE_HPP_ #define ORG_EEROS_SEQUENCER_SEQUENCE_HPP_ #include <string> #include <map> #include <functional> #include <vector> #include <eeros/core/Runnable.hpp> #include <eeros/sequencer/SequenceException.hpp> #include <eeros/logger/Logger.hpp> #include <eeros/logger/LogWriter.hpp> namespace eeros { namespace sequencer { enum SequenceState { kSequenceRunning, kSequenceFinished, kSequenceNotStarted, kSequenceException }; class Sequence : public Runnable { public: Sequence(std::string name); virtual ~Sequence(); virtual std::string getName(); virtual int getState(); virtual void run(); virtual void init(); virtual bool checkPreCondition(); virtual bool checkPostCondition(); virtual void exit(); virtual void reset(); void callSubSequence(Sequence* sequence); void startParallelSequence(Sequence* sequence); static Sequence* getSequence(std::string name); eeros::logger::Logger<eeros::logger::LogWriter> log; protected: virtual void addStep(std::function<void(void)> action); SequenceState state; uint32_t currentStep; std::string name; std::vector<std::function<void(void)>> actionList; uint32_t exceptionRetryCounter; private: static std::map<std::string, Sequence*> allSequences; }; // class Sequence }; // namespace sequencer }; // namespace eeros #endif // ORG_EEROS_SEQUENCER_SEQUENCE_HPP_<commit_msg>subsequences can now be called with parameters<commit_after>#ifndef ORG_EEROS_SEQUENCER_SEQUENCE_HPP_ #define ORG_EEROS_SEQUENCER_SEQUENCE_HPP_ #include <string> #include <map> #include <functional> #include <vector> #include <eeros/core/Runnable.hpp> #include <eeros/sequencer/SequenceException.hpp> #include <eeros/logger/Logger.hpp> #include <eeros/logger/LogWriter.hpp> namespace eeros { namespace sequencer { enum SequenceState { kSequenceRunning, kSequenceFinished, kSequenceNotStarted, kSequenceException }; class Sequence : public Runnable { public: Sequence(std::string name); virtual ~Sequence(); virtual std::string getName(); virtual int getState(); virtual void run(); virtual void init(); virtual bool checkPreCondition(); virtual bool checkPostCondition(); virtual void exit(); virtual void reset(); void callSubSequence(Sequence* sequence); template < typename T, typename ... Targs > void callSubSequence(T& sequence, Targs ... args) { sequence.run(args...); } void startParallelSequence(Sequence* sequence); static Sequence* getSequence(std::string name); eeros::logger::Logger<eeros::logger::LogWriter> log; protected: virtual void addStep(std::function<void(void)> action); SequenceState state; uint32_t currentStep; std::string name; std::vector<std::function<void(void)>> actionList; uint32_t exceptionRetryCounter; private: static std::map<std::string, Sequence*> allSequences; }; // class Sequence }; // namespace sequencer }; // namespace eeros #endif // ORG_EEROS_SEQUENCER_SEQUENCE_HPP_<|endoftext|>
<commit_before>#include "menu/option_adventure.h" #include "util/keyboard.h" #include "util/load_exception.h" #include "util/token.h" #include "util/funcs.h" #include "object/player.h" #include "object/object.h" #include "game.h" #include "globals.h" #include <iostream> using namespace std; OptionAdventure::OptionAdventure(Token *token) throw( LoadException ): MenuOption(event){ if ( *token != "adventure" ){ throw LoadException("Not an adventure"); } while ( token->hasTokens() ){ try{ Token * tok; *token >> tok; if ( *tok == "name" ){ // Create an image and push it back on to vector std::string temp; *tok >> temp; this->setText(temp); } else { Global::debug( 3 ) <<"Unhandled menu attribute: "<<endl; tok->print(" "); } } catch ( const TokenException & ex ) { // delete current; string m( "Menu parse error: " ); m += ex.getReason(); throw LoadException( m ); } } if ( getText().empty() ){ throw LoadException("No name set, this option should have a name!"); } } OptionAdventure::~OptionAdventure(){ // Nothing } void OptionAdventure::logic(){ } void OptionAdventure::draw(Bitmap *work){ } void OptionAdventure::run(bool &endGame){ Keyboard key; Object * player = NULL; try{ string level = Game::selectLevelSet( Util::getDataPath() + "/levels" ); key.wait(); player = Game::selectPlayer( false ); ((Player *)player)->setLives( 10 ); vector< Object * > players; players.push_back( player ); Game::realGame( players, level ); } catch ( const LoadException & le ){ Global::debug( 0 ) << "Error while loading: " << le.getReason() << endl; } catch ( const ReturnException & r ){ key.wait(); } if ( player != NULL ){ delete player; } } <commit_msg>use invincibility and lives in game<commit_after>#include "menu/option_adventure.h" #include "menu/menu_global.h" #include "util/keyboard.h" #include "util/load_exception.h" #include "util/token.h" #include "util/funcs.h" #include "object/player.h" #include "object/object.h" #include "game.h" #include "globals.h" #include <iostream> using namespace std; OptionAdventure::OptionAdventure(Token *token) throw( LoadException ): MenuOption(event){ if ( *token != "adventure" ){ throw LoadException("Not an adventure"); } while ( token->hasTokens() ){ try{ Token * tok; *token >> tok; if ( *tok == "name" ){ // Create an image and push it back on to vector std::string temp; *tok >> temp; this->setText(temp); } else { Global::debug( 3 ) <<"Unhandled menu attribute: "<<endl; tok->print(" "); } } catch ( const TokenException & ex ) { // delete current; string m( "Menu parse error: " ); m += ex.getReason(); throw LoadException( m ); } } if ( getText().empty() ){ throw LoadException("No name set, this option should have a name!"); } } OptionAdventure::~OptionAdventure(){ // Nothing } void OptionAdventure::logic(){ } void OptionAdventure::draw(Bitmap *work){ } void OptionAdventure::run(bool &endGame){ Keyboard key; Object * player = NULL; try{ string level = Game::selectLevelSet( Util::getDataPath() + "/levels" ); key.wait(); player = Game::selectPlayer( MenuGlobals::getInvincible() ); ((Player *)player)->setLives( MenuGlobals::getLives() ); vector< Object * > players; players.push_back( player ); Game::realGame( players, level ); } catch ( const LoadException & le ){ Global::debug( 0 ) << "Error while loading: " << le.getReason() << endl; } catch ( const ReturnException & r ){ key.wait(); } if ( player != NULL ){ delete player; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (ivan.frade@nokia.com) ** ** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at ivan.frade@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "../testhelpers.h" #include "../tracker_direct_common.h" #include <QtTest/QtTest> #include <QtSparql/QtSparql> class tst_QSparqlTrackerDirectConcurrency : public QObject { Q_OBJECT public: tst_QSparqlTrackerDirectConcurrency(); virtual ~tst_QSparqlTrackerDirectConcurrency(); private: private slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); void sameConnection_selectQueries(); void sameConnection_selectQueries_data(); //void sameConnection_updateQueries(); //void sameConnection_multipleThreads_selectQueries(); //void sameConnection_multipleThreads_updateQueries(); // multpleConnections tests will all be multi threaded //void multipleConnections_selectQueries(); //void multipleConnections_updateQueries(); private: QSharedPointer<QSignalSpy> dataReadySpy; }; namespace { class SignalObject : public QObject { Q_OBJECT public: SignalObject() : position(0) {} ~SignalObject() { // delete the signal mappers that were created foreach(QSignalMapper* map, signalMaps) { delete map; } } QSet<QSparqlResult*> pendingResults; //QSignalMapper dataReadyMapper; //QSignalMapper finishedMapper; int position; QList<QSignalMapper* > signalMaps; QList<QPair<int, int> > resultRanges; void append(QSparqlResult *r, QPair<int, int> range) { QSignalMapper *dataReadyMapper = new QSignalMapper(); QSignalMapper *finishedMapper = new QSignalMapper(); dataReadyMapper->setMapping(r, position); finishedMapper->setMapping(r, position); position++; connect(r, SIGNAL(dataReady(int)), dataReadyMapper, SLOT(map())); connect(dataReadyMapper, SIGNAL(mapped(int)), this, SLOT(onDataReady(int))); connect(r, SIGNAL(finished()), finishedMapper, SLOT(map())); connect(finishedMapper, SIGNAL(mapped(int)), this, SLOT(onFinished(int))); resultList.append(r); resultRanges.append(range); pendingResults.insert(r); // keep track of the signal mappers to delete later signalMaps.append(dataReadyMapper); signalMaps.append(finishedMapper); } QList<QSparqlResult*> resultList; bool waitForAllFinished(int silenceTimeoutMs) { QTime timeoutTimer; timeoutTimer.start(); bool timeout = false; while (!pendingResults.empty() && !timeout) { const int pendingResultsCountBefore = pendingResults.count(); QTest::qWait(silenceTimeoutMs / 10); if (pendingResults.count() < pendingResultsCountBefore) { timeoutTimer.restart(); } else if (timeoutTimer.elapsed() > silenceTimeoutMs) { timeout = true; } } return !timeout; } public Q_SLOTS: void onDataReady(int listPos) { QSparqlResult *result = resultList.at(listPos); while (result->next()) { // just do something pointless with the result result->value(1).toInt(); result->value(0).toString(); } } void onFinished(int listPos) { QPair<int, int> resultRange = resultRanges.at(listPos); QSparqlResult* result = resultList.at(listPos); int expectedResultSize = (resultRange.second - resultRange.first) + 1; QCOMPARE(expectedResultSize, result->size()); // the results should have been fully nexted in the data ready function QCOMPARE(result->pos(), (int)QSparql::AfterLastRow); // go back through the results and validate that they are in range int resultCount = 0; while (result->previous()) { //we don't know the order, so just ensure the result is within range QVERIFY(result->value(1).toInt() <= resultRange.second && result->value(1).toInt() >= resultRange.first); resultCount++; } // now make sure the results counted match the size QCOMPARE(resultCount, expectedResultSize); pendingResults.remove(result); } }; } //end namespace tst_QSparqlTrackerDirectConcurrency::tst_QSparqlTrackerDirectConcurrency() { } tst_QSparqlTrackerDirectConcurrency::~tst_QSparqlTrackerDirectConcurrency() { } void tst_QSparqlTrackerDirectConcurrency::initTestCase() { // For running the test without installing the plugins. Should work in // normal and vpath builds. QCoreApplication::addLibraryPath("../../../plugins"); // installMsgHandler(); // clean any remainings // QVERIFY(cleanData()); // QVERIFY(setupData()); } void tst_QSparqlTrackerDirectConcurrency::cleanupTestCase() { //QVERIFY(cleanData()); } void tst_QSparqlTrackerDirectConcurrency::init() { // setMsgLogLevel(QtDebugMsg); } void tst_QSparqlTrackerDirectConcurrency::cleanup() { } void tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries() { QFETCH(int, testDataAmount); QFETCH(int, numQueries); QFETCH(int, maxThreadCount); QSparqlConnectionOptions options; options.setDataReadyInterval(500); options.setMaxThreadCount(maxThreadCount); const QString testTag("<qsparql-tracker-direct-tests-concurrency-stress>"); QScopedPointer<TestData> testData(createTestData(testDataAmount, "<qsparql-tracker-direct-tests>", testTag)); QTest::qWait(2000); QVERIFY( testData->isOK() ); // seed the random number generator QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // store the result ranges we are going to use QList<QPair<int, int> > resultRanges; // first result will read everything resultRanges.append(qMakePair(1, 3000)); for (int i=1;i<numQueries;i++) { // high + 1) - low) + low int low = qrand() % ((testDataAmount) - 1) + 1; int high = qrand() % ((testDataAmount+1) - low) + low; resultRanges.append(qMakePair(low, high)); } QSparqlConnection conn("QTRACKER_DIRECT", options); SignalObject signalObject; for (int i=0;i<numQueries;i++) { QPair<int, int> resultRange = resultRanges.at(i); QSparqlQuery select(QString("select ?u ?t {?u a nmm:MusicPiece;" "nmm:trackNumber ?t;" "nie:isLogicalPartOf <qsparql-tracker-direct-tests-concurrency-stress>" "FILTER ( ?t >=%1 && ?t <=%2 ) }").arg(resultRange.first).arg(resultRange.second)); QSparqlResult *result = conn.exec(select); signalObject.append(result, resultRange); } QVERIFY(signalObject.waitForAllFinished(8000)); } void tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries_data() { QTest::addColumn<int>("testDataAmount"); QTest::addColumn<int>("numQueries"); QTest::addColumn<int>("maxThreadCount"); QTest::newRow("3000 items, 10 queries, 4 Threads") << 3000 << 10 << 4; QTest::newRow("3000 items, 100 queries, 4 Threads") << 3000 << 100 << 4; QTest::newRow("3000 items, 10 queries, 1 Thread") << 3000 << 10 << 1; QTest::newRow("3000 items, 100 queries, 1 Thread") << 3000 << 100 << 1; } QTEST_MAIN( tst_QSparqlTrackerDirectConcurrency ) #include "tst_qsparql_tracker_direct_concurrency.moc" <commit_msg>Add a threading test that uses the same connection<commit_after>/**************************************************************************** ** ** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (ivan.frade@nokia.com) ** ** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at ivan.frade@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "../testhelpers.h" #include "../tracker_direct_common.h" #include <QtTest/QtTest> #include <QtSparql/QtSparql> class tst_QSparqlTrackerDirectConcurrency : public QObject { Q_OBJECT public: tst_QSparqlTrackerDirectConcurrency(); virtual ~tst_QSparqlTrackerDirectConcurrency(); private: private slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); void sameConnection_selectQueries(); void sameConnection_selectQueries_data(); //void sameConnection_updateQueries(); void sameConnection_multipleThreads_selectQueries(); void sameConnection_multipleThreads_selectQueries_data(); //void sameConnection_multipleThreads_updateQueries(); // multpleConnections tests will all be multi threaded //void multipleConnections_selectQueries(); //void multipleConnections_updateQueries(); private: QSharedPointer<QSignalSpy> dataReadySpy; }; namespace { class SignalObject : public QObject { Q_OBJECT public: SignalObject() : position(0) {} ~SignalObject() { // delete the signal mappers that were created foreach(QSignalMapper* map, signalMaps) { delete map; } } QSet<QSparqlResult*> pendingResults; int position; QList<QSignalMapper* > signalMaps; QList<QPair<int, int> > resultRanges; void append(QSparqlResult *r, QPair<int, int> range) { QSignalMapper *dataReadyMapper = new QSignalMapper(); QSignalMapper *finishedMapper = new QSignalMapper(); dataReadyMapper->setMapping(r, position); finishedMapper->setMapping(r, position); position++; connect(r, SIGNAL(dataReady(int)), dataReadyMapper, SLOT(map())); connect(dataReadyMapper, SIGNAL(mapped(int)), this, SLOT(onDataReady(int))); connect(r, SIGNAL(finished()), finishedMapper, SLOT(map())); connect(finishedMapper, SIGNAL(mapped(int)), this, SLOT(onFinished(int))); resultList.append(r); resultRanges.append(range); pendingResults.insert(r); // keep track of the signal mappers to delete later signalMaps.append(dataReadyMapper); signalMaps.append(finishedMapper); } QList<QSparqlResult*> resultList; bool waitForAllFinished(int silenceTimeoutMs) { QTime timeoutTimer; timeoutTimer.start(); bool timeout = false; while (!pendingResults.empty() && !timeout) { const int pendingResultsCountBefore = pendingResults.count(); QTest::qWait(silenceTimeoutMs / 10); if (pendingResults.count() < pendingResultsCountBefore) { timeoutTimer.restart(); } else if (timeoutTimer.elapsed() > silenceTimeoutMs) { timeout = true; } } return !timeout; } public Q_SLOTS: void onDataReady(int listPos) { QSparqlResult *result = resultList.at(listPos); while (result->next()) { // just do something pointless with the result result->value(1).toInt(); result->value(0).toString(); } } void onFinished(int listPos) { QPair<int, int> resultRange = resultRanges.at(listPos); QSparqlResult* result = resultList.at(listPos); int expectedResultSize = (resultRange.second - resultRange.first) + 1; QCOMPARE(expectedResultSize, result->size()); // the results should have been fully nexted in the data ready function QCOMPARE(result->pos(), (int)QSparql::AfterLastRow); // go back through the results and validate that they are in range int resultCount = 0; while (result->previous()) { //we don't know the order, so just ensure the result is within range QVERIFY(result->value(1).toInt() <= resultRange.second && result->value(1).toInt() >= resultRange.first); resultCount++; } // now make sure the results counted match the size QCOMPARE(resultCount, expectedResultSize); pendingResults.remove(result); } }; class ThreadObject : public QObject { Q_OBJECT public: QSparqlConnection *connection; SignalObject *signalObject; QList<QSparqlResult*> resultList; bool deleteConnection; bool deleteSignalObject; int numQueries; int testDataSize; ThreadObject() : connection(0), signalObject(0), deleteConnection(false), deleteSignalObject(false) { } ~ThreadObject() { } void cleanup() { if (deleteConnection) { delete connection; } else { // if we were passed a connection, delete the results // here to avoid leaking them foreach(QSparqlResult* result, resultList) delete result; } if (deleteSignalObject) delete signalObject; } void setParameters(int numQueries, int testDataSize) { this->numQueries = numQueries; this->testDataSize = testDataSize; } void setConnection(QSparqlConnection* connection) { this->connection = connection; } void setSignalObject(SignalObject* signalObject) { this->signalObject = signalObject; } void waitForFinished() { signalObject->waitForAllFinished(8000); } public Q_SLOTS: void startQueries() { if (!connection) { this->connection = new QSparqlConnection("QTRACKER_DIRECT"); deleteConnection = true; } if (!signalObject) { this->signalObject = new SignalObject(); deleteSignalObject = true; } QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // store the result ranges we are going to use QList<QPair<int, int> > resultRanges; // first result will read everything resultRanges.append(qMakePair(1, testDataSize)); for (int i=1;i<numQueries;i++) { // high + 1) - low) + low int low = qrand() % ((testDataSize) - 1) + 1; int high = qrand() % ((testDataSize+1) - low) + low; resultRanges.append(qMakePair(low, high)); } for (int i=0;i<numQueries;i++) { QPair<int, int> resultRange = resultRanges.at(i); QSparqlQuery select(QString("select ?u ?t {?u a nmm:MusicPiece;" "nmm:trackNumber ?t;" "nie:isLogicalPartOf <qsparql-tracker-direct-tests-concurrency-stress>" "FILTER ( ?t >=%1 && ?t <=%2 ) }").arg(resultRange.first).arg(resultRange.second)); QSparqlResult *result = connection->exec(select); resultList.append(result); signalObject->append(result, resultRange); } waitForFinished(); cleanup(); this->thread()->quit(); } }; } //end namespace tst_QSparqlTrackerDirectConcurrency::tst_QSparqlTrackerDirectConcurrency() { } tst_QSparqlTrackerDirectConcurrency::~tst_QSparqlTrackerDirectConcurrency() { } void tst_QSparqlTrackerDirectConcurrency::initTestCase() { // For running the test without installing the plugins. Should work in // normal and vpath builds. QCoreApplication::addLibraryPath("../../../plugins"); } void tst_QSparqlTrackerDirectConcurrency::cleanupTestCase() { } void tst_QSparqlTrackerDirectConcurrency::init() { } void tst_QSparqlTrackerDirectConcurrency::cleanup() { } void tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries() { QFETCH(int, testDataAmount); QFETCH(int, numQueries); QFETCH(int, maxThreadCount); QSparqlConnectionOptions options; options.setDataReadyInterval(500); options.setMaxThreadCount(maxThreadCount); const QString testTag("<qsparql-tracker-direct-tests-concurrency-stress>"); QScopedPointer<TestData> testData(createTestData(testDataAmount, "<qsparql-tracker-direct-tests>", testTag)); QTest::qWait(2000); QVERIFY( testData->isOK() ); // seed the random number generator QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // store the result ranges we are going to use QList<QPair<int, int> > resultRanges; // first result will read everything resultRanges.append(qMakePair(1, 3000)); for (int i=1;i<numQueries;i++) { // high + 1) - low) + low int low = qrand() % ((testDataAmount) - 1) + 1; int high = qrand() % ((testDataAmount+1) - low) + low; resultRanges.append(qMakePair(low, high)); } QSparqlConnection conn("QTRACKER_DIRECT", options); SignalObject signalObject; for (int i=0;i<numQueries;i++) { QPair<int, int> resultRange = resultRanges.at(i); QSparqlQuery select(QString("select ?u ?t {?u a nmm:MusicPiece;" "nmm:trackNumber ?t;" "nie:isLogicalPartOf <qsparql-tracker-direct-tests-concurrency-stress>" "FILTER ( ?t >=%1 && ?t <=%2 ) }").arg(resultRange.first).arg(resultRange.second)); QSparqlResult *result = conn.exec(select); signalObject.append(result, resultRange); } QVERIFY(signalObject.waitForAllFinished(8000)); } void tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries_data() { QTest::addColumn<int>("testDataAmount"); QTest::addColumn<int>("numQueries"); QTest::addColumn<int>("maxThreadCount"); QTest::newRow("3000 items, 10 queries, 4 Threads") << 3000 << 10 << 4; QTest::newRow("3000 items, 100 queries, 4 Threads") << 3000 << 100 << 4; QTest::newRow("3000 items, 10 queries, 1 Thread") << 3000 << 10 << 1; QTest::newRow("3000 items, 100 queries, 1 Thread") << 3000 << 100 << 1; } void tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries() { QFETCH(int, testDataAmount); QFETCH(int, numQueries); QFETCH(int, numThreads); QSparqlConnection connection("QTRACKER_DIRECT"); const QString testTag("<qsparql-tracker-direct-tests-concurrency-stress>"); QScopedPointer<TestData> testData(createTestData(testDataAmount, "<qsparql-tracker-direct-tests>", testTag)); QTest::qWait(2000); QVERIFY( testData->isOK() ); QList<QThread*> createdThreads; QList<ThreadObject*> threadObjects; for (int i=0;i<numThreads;i++) { QThread *newThread = new QThread(); createdThreads.append(newThread); ThreadObject *threadObject = new ThreadObject(); threadObjects.append(threadObject); threadObject->setConnection(&connection); threadObject->setParameters(numQueries, testDataAmount); threadObject->moveToThread(newThread); // connec the threads started signal to the slot that does the work QObject::connect(newThread, SIGNAL(started()), threadObject, SLOT(startQueries())); } // start all the threads foreach(QThread* thread, createdThreads) { thread->start(); } // wait for all the threads then delete // TODO: add timer so we don't wait forever foreach(QThread* thread, createdThreads) { while (!thread->isFinished()) QTest::qWait(500); delete thread; } //cleanup foreach(ThreadObject *threadObject, threadObjects) delete threadObject; } void tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries_data() { QTest::addColumn<int>("testDataAmount"); QTest::addColumn<int>("numQueries"); QTest::addColumn<int>("numThreads"); QTest::newRow("3000 items, 10 queries, 2 Threads") << 3000 << 10 << 2; QTest::newRow("3000 items, 100 queries, 2 Threads") << 3000 << 100 << 2; QTest::newRow("3000 items, 10 queries, 10 Threads") << 3000 << 10 << 10; QTest::newRow("3000 items, 100 queries, 10 Threads") << 3000 << 100 << 10; } QTEST_MAIN( tst_QSparqlTrackerDirectConcurrency ) #include "tst_qsparql_tracker_direct_concurrency.moc" <|endoftext|>
<commit_before>// Time: O(n) // Space: O(n) class Solution { public: bool isValid(string code) { auto i = 0; return validTag(code, &i) && i == code.size(); } private: bool validTag(const string& s, int *i) { auto j = *i; auto tag = parseTagName(s, &j); if (tag.empty()) { return false; } parseContent(s, &j); auto k = j + tag.size() + 2; if (k >= s.size() || s.substr(j, k + 1 - j) != "</" + tag + ">") { return false; } *i = k + 1; return true; } string parseTagName(const string& s, int *i) { if (s[*i] != '<') { return ""; } auto j = s.find('>', *i); if (j == string::npos || j - 1 - *i < 1 || 9 < j - 1 - *i) { return ""; } auto tag = s.substr(*i + 1, j - 1 - *i); for (const auto& c : tag) { if (c < 'A' || 'Z' < c) { return ""; } } *i = j + 1; return tag; } void parseContent(const string& s, int *i) { while (*i < s.size()) { if (!validText(s, i) && !validCData(s, i) && !validTag(s, i)) { break; } } } bool validText(const string& s, int *i) { auto j = *i; *i = s.find("<", *i); return *i != j; } bool validCData(const string& s, int *i) { if (s.find("<![CDATA[", *i) != *i) { return false; } auto j = s.find("]]>", *i); if (j == string::npos) { return false; } *i = j + 3; return true; } }; <commit_msg>Update tag-validator.cpp<commit_after>// Time: O(n) // Space: O(n) class Solution { public: bool isValid(string code) { auto i = 0; return validTag(code, &i) && i == code.length(); } private: bool validTag(const string& s, int *i) { auto j = *i; auto tag = parseTagName(s, &j); if (tag.empty()) { return false; } parseContent(s, &j); auto k = j + tag.size() + 2; if (k >= s.size() || s.substr(j, k + 1 - j) != "</" + tag + ">") { return false; } *i = k + 1; return true; } string parseTagName(const string& s, int *i) { if (s[*i] != '<') { return ""; } auto j = s.find('>', *i); if (j == string::npos || j - 1 - *i < 1 || 9 < j - 1 - *i) { return ""; } auto tag = s.substr(*i + 1, j - 1 - *i); for (const auto& c : tag) { if (c < 'A' || 'Z' < c) { return ""; } } *i = j + 1; return tag; } void parseContent(const string& s, int *i) { while (*i < s.size()) { if (!validText(s, i) && !validCData(s, i) && !validTag(s, i)) { break; } } } bool validText(const string& s, int *i) { auto j = *i; *i = s.find("<", *i); return *i != j; } bool validCData(const string& s, int *i) { if (s.find("<![CDATA[", *i) != *i) { return false; } auto j = s.find("]]>", *i); if (j == string::npos) { return false; } *i = j + 3; return true; } }; <|endoftext|>
<commit_before>/* * * Copyright (c) 2020-2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * This file implements the ExchangeManager class. * */ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <cstring> #include <inttypes.h> #include <stddef.h> #include <core/CHIPCore.h> #include <core/CHIPEncoding.h> #include <messaging/ExchangeContext.h> #include <messaging/ExchangeMgr.h> #include <protocols/Protocols.h> #include <support/CHIPFaultInjection.h> #include <support/CodeUtils.h> #include <support/RandUtils.h> #include <support/logging/CHIPLogging.h> using namespace chip::Encoding; using namespace chip::Inet; using namespace chip::System; namespace chip { namespace Messaging { /** * Constructor for the ExchangeManager class. * It sets the state to kState_NotInitialized. * * @note * The class must be initialized via ExchangeManager::Init() * prior to use. * */ ExchangeManager::ExchangeManager() : mReliableMessageMgr(mContextPool) { mState = State::kState_NotInitialized; } CHIP_ERROR ExchangeManager::Init(NodeId localNodeId, TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrReturnError(mState == State::kState_NotInitialized, err = CHIP_ERROR_INCORRECT_STATE); mLocalNodeId = localNodeId; mTransportMgr = transportMgr; mSessionMgr = sessionMgr; mNextExchangeId = GetRandU16(); mNextKeyId = 0; mContextsInUse = 0; for (auto & handler : UMHandlerPool) { handler = {}; } mTransportMgr->SetRendezvousSession(this); sessionMgr->SetDelegate(this); mReliableMessageMgr.Init(sessionMgr->SystemLayer(), sessionMgr); err = mMessageCounterSyncMgr.Init(this); ReturnErrorOnFailure(err); mState = State::kState_Initialized; return err; } CHIP_ERROR ExchangeManager::Shutdown() { mMessageCounterSyncMgr.Shutdown(); mReliableMessageMgr.Shutdown(); if (mSessionMgr != nullptr) { mSessionMgr->SetDelegate(nullptr); mSessionMgr = nullptr; } mState = State::kState_NotInitialized; return CHIP_NO_ERROR; } ExchangeContext * ExchangeManager::NewContext(SecureSessionHandle session, ExchangeDelegate * delegate) { return AllocContext(mNextExchangeId++, session, true, delegate); } CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegate * delegate) { return RegisterUMH(protocolId, kAnyMessageType, delegate); } CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType, ExchangeDelegate * delegate) { return RegisterUMH(protocolId, static_cast<int16_t>(msgType), delegate); } CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId) { return UnregisterUMH(protocolId, kAnyMessageType); } CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType) { return UnregisterUMH(protocolId, static_cast<int16_t>(msgType)); } void ExchangeManager::OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * msgLayer) { ChipLogError(ExchangeManager, "Accept FAILED, err = %s", ErrorStr(error)); } ExchangeContext * ExchangeManager::AllocContext(uint16_t ExchangeId, SecureSessionHandle session, bool Initiator, ExchangeDelegate * delegate) { CHIP_FAULT_INJECT(FaultInjection::kFault_AllocExchangeContext, return nullptr); for (auto & ec : mContextPool) { if (ec.GetReferenceCount() == 0) { return ec.Alloc(this, ExchangeId, session, Initiator, delegate); } } ChipLogError(ExchangeManager, "Alloc ctxt FAILED"); return nullptr; } CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate) { UnsolicitedMessageHandler * umh = UMHandlerPool; UnsolicitedMessageHandler * selected = nullptr; for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++) { if (umh->Delegate == nullptr) { if (selected == nullptr) selected = umh; } else if (umh->ProtocolId == protocolId && umh->MessageType == msgType) { umh->Delegate = delegate; return CHIP_NO_ERROR; } } if (selected == nullptr) return CHIP_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS; selected->Delegate = delegate; selected->ProtocolId = protocolId; selected->MessageType = msgType; SYSTEM_STATS_INCREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers); return CHIP_NO_ERROR; } CHIP_ERROR ExchangeManager::UnregisterUMH(Protocols::Id protocolId, int16_t msgType) { UnsolicitedMessageHandler * umh = UMHandlerPool; for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++) { if (umh->Delegate != nullptr && umh->ProtocolId == protocolId && umh->MessageType == msgType) { umh->Delegate = nullptr; SYSTEM_STATS_DECREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers); return CHIP_NO_ERROR; } } return CHIP_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER; } bool ExchangeManager::IsMsgCounterSyncMessage(const PayloadHeader & payloadHeader) { if (payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncReq) || payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncRsp)) { return true; } return false; } void ExchangeManager::HandleGroupMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, const SecureSessionHandle & session, System::PacketBufferHandle msgBuf) { OnMessageReceived(packetHeader, payloadHeader, session, std::move(msgBuf), nullptr); } void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, SecureSessionHandle session, System::PacketBufferHandle msgBuf, SecureSessionMgr * msgLayer) { CHIP_ERROR err = CHIP_NO_ERROR; UnsolicitedMessageHandler * umh = nullptr; UnsolicitedMessageHandler * matchingUMH = nullptr; bool sendAckAndCloseExchange = false; if (!IsMsgCounterSyncMessage(payloadHeader) && session.IsPeerGroupMsgIdNotSynchronized()) { Transport::PeerConnectionState * state = mSessionMgr->GetPeerConnectionState(session); VerifyOrReturn(state != nullptr); // Queue the message as needed for sync with destination node. err = mMessageCounterSyncMgr.AddToReceiveTable(packetHeader, payloadHeader, session, std::move(msgBuf)); VerifyOrReturn(err == CHIP_NO_ERROR); // Initiate message counter synchronization if no message counter synchronization is in progress. if (!state->IsMsgCounterSyncInProgress()) { err = mMessageCounterSyncMgr.SendMsgCounterSyncReq(session); } if (err != CHIP_NO_ERROR) { ChipLogError(ExchangeManager, "Message counter synchronization for received message, failed to send synchronization request, err = %d", err); } // After the message that triggers message counter synchronization is stored, and a message counter // synchronization exchange is initiated, we need to return immediately and re-process the original message // when the synchronization is completed. return; } // Search for an existing exchange that the message applies to. If a match is found... for (auto & ec : mContextPool) { if (ec.GetReferenceCount() > 0 && ec.MatchExchange(session, packetHeader, payloadHeader)) { // Found a matching exchange. Set flag for correct subsequent CRMP // retransmission timeout selection. if (!ec.mReliableMessageContext.HasRcvdMsgFromPeer()) { ec.mReliableMessageContext.SetMsgRcvdFromPeer(true); } // Matched ExchangeContext; send to message handler. ec.HandleMessage(packetHeader, payloadHeader, std::move(msgBuf)); ExitNow(err = CHIP_NO_ERROR); } } // Search for an unsolicited message handler if it marked as being sent by an initiator. Since we didn't // find an existing exchange that matches the message, it must be an unsolicited message. However all // unsolicited messages must be marked as being from an initiator. if (payloadHeader.IsInitiator()) { // Search for an unsolicited message handler that can handle the message. Prefer handlers that can explicitly // handle the message type over handlers that handle all messages for a profile. umh = (UnsolicitedMessageHandler *) UMHandlerPool; matchingUMH = nullptr; for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++) { if (umh->Delegate != nullptr && payloadHeader.HasProtocol(umh->ProtocolId)) { if (umh->MessageType == payloadHeader.GetMessageType()) { matchingUMH = umh; break; } if (umh->MessageType == kAnyMessageType) matchingUMH = umh; } } } // Discard the message if it isn't marked as being sent by an initiator and the message does not need to send // an ack to the peer. else if (!payloadHeader.NeedsAck()) { ExitNow(err = CHIP_ERROR_UNSOLICITED_MSG_NO_ORIGINATOR); } // If we didn't find an existing exchange that matches the message, and no unsolicited message handler registered // to hand this message, we need to create a temporary exchange to send an ack for this message and then close this exchange. sendAckAndCloseExchange = payloadHeader.NeedsAck() && (matchingUMH == nullptr); // If we found a handler or we need to create a new exchange context (EC). if (matchingUMH != nullptr || sendAckAndCloseExchange) { ExchangeContext * ec = nullptr; if (sendAckAndCloseExchange) { // If rcvd msg is from initiator then this exchange is created as not Initiator. // If rcvd msg is not from initiator then this exchange is created as Initiator. ec = AllocContext(payloadHeader.GetExchangeID(), session, !payloadHeader.IsInitiator(), nullptr); } else { ec = AllocContext(payloadHeader.GetExchangeID(), session, false, matchingUMH->Delegate); } VerifyOrExit(ec != nullptr, err = CHIP_ERROR_NO_MEMORY); ChipLogProgress(ExchangeManager, "ec pos: %d, id: %d, Delegate: 0x%x", ec - mContextPool.begin(), ec->GetExchangeId(), ec->GetDelegate()); ec->HandleMessage(packetHeader, payloadHeader, std::move(msgBuf)); // Close exchange if it was created only to send ack for a duplicate message. if (sendAckAndCloseExchange) ec->Close(); } exit: if (err != CHIP_NO_ERROR) { ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %d", err); } } ChannelHandle ExchangeManager::EstablishChannel(const ChannelBuilder & builder, ChannelDelegate * delegate) { ChannelContext * channelContext = nullptr; // Find an existing Channel matching the builder mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { if (context->MatchesBuilder(builder)) { channelContext = context; return false; } return true; }); if (channelContext == nullptr) { // create a new channel if not found channelContext = mChannelContexts.CreateObject(this); if (channelContext == nullptr) return ChannelHandle{ nullptr }; channelContext->Start(builder); } else { channelContext->Retain(); } ChannelContextHandleAssociation * association = mChannelHandles.CreateObject(channelContext, delegate); channelContext->Release(); return ChannelHandle{ association }; } void ExchangeManager::OnNewConnection(SecureSessionHandle session, SecureSessionMgr * mgr) { mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { if (context->MatchesSession(session, mgr)) { context->OnNewConnection(session); return false; } return true; }); } void ExchangeManager::OnConnectionExpired(SecureSessionHandle session, SecureSessionMgr * mgr) { for (auto & ec : mContextPool) { if (ec.GetReferenceCount() > 0 && ec.mSecureSession == session) { ec.Close(); // Continue iterate because there can be multiple contexts associated with the connection. } } mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { if (context->MatchesSession(session, mgr)) { context->OnConnectionExpired(session); return false; } return true; }); } void ExchangeManager::OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, System::PacketBufferHandle msgBuf) { auto peer = header.GetSourceNodeId(); if (!peer.HasValue()) { char addrBuffer[Transport::PeerAddress::kMaxToStringSize]; source.ToString(addrBuffer, sizeof(addrBuffer)); ChipLogError(ExchangeManager, "Unencrypted message from %s is dropped since no source node id in packet header.", addrBuffer); return; } auto node = peer.Value(); auto notFound = mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { if (context->IsCasePairing() && context->MatchNodeId(node)) { CHIP_ERROR err = context->HandlePairingMessage(header, source, std::move(msgBuf)); if (err != CHIP_NO_ERROR) ChipLogError(ExchangeManager, "HandlePairingMessage error %s from node %llu.", chip::ErrorStr(err), node); return false; } return true; }); if (notFound) { char addrBuffer[Transport::PeerAddress::kMaxToStringSize]; source.ToString(addrBuffer, sizeof(addrBuffer)); ChipLogError(ExchangeManager, "Unencrypted message from %s is dropped since no session found for node %llu.", addrBuffer, node); return; } } void ExchangeManager::IncrementContextsInUse() { mContextsInUse++; } void ExchangeManager::DecrementContextsInUse() { if (mContextsInUse >= 1) { mContextsInUse--; } else { ChipLogError(ExchangeManager, "No context in use, decrement failed"); } } } // namespace Messaging } // namespace chip <commit_msg>Initialize UnsolicitedMessageHandler::Delegate to nullptr to avoid build bustage (#5581)<commit_after>/* * * Copyright (c) 2020-2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * This file implements the ExchangeManager class. * */ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <cstring> #include <inttypes.h> #include <stddef.h> #include <core/CHIPCore.h> #include <core/CHIPEncoding.h> #include <messaging/ExchangeContext.h> #include <messaging/ExchangeMgr.h> #include <protocols/Protocols.h> #include <support/CHIPFaultInjection.h> #include <support/CodeUtils.h> #include <support/RandUtils.h> #include <support/logging/CHIPLogging.h> using namespace chip::Encoding; using namespace chip::Inet; using namespace chip::System; namespace chip { namespace Messaging { /** * Constructor for the ExchangeManager class. * It sets the state to kState_NotInitialized. * * @note * The class must be initialized via ExchangeManager::Init() * prior to use. * */ ExchangeManager::ExchangeManager() : mReliableMessageMgr(mContextPool) { mState = State::kState_NotInitialized; } CHIP_ERROR ExchangeManager::Init(NodeId localNodeId, TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrReturnError(mState == State::kState_NotInitialized, err = CHIP_ERROR_INCORRECT_STATE); mLocalNodeId = localNodeId; mTransportMgr = transportMgr; mSessionMgr = sessionMgr; mNextExchangeId = GetRandU16(); mNextKeyId = 0; mContextsInUse = 0; for (auto & handler : UMHandlerPool) { // Mark all handlers as unallocated. This handles both initial // initialization and the case when the consumer shuts us down and // then re-initializes without removing registered handlers. handler.Delegate = nullptr; } mTransportMgr->SetRendezvousSession(this); sessionMgr->SetDelegate(this); mReliableMessageMgr.Init(sessionMgr->SystemLayer(), sessionMgr); err = mMessageCounterSyncMgr.Init(this); ReturnErrorOnFailure(err); mState = State::kState_Initialized; return err; } CHIP_ERROR ExchangeManager::Shutdown() { mMessageCounterSyncMgr.Shutdown(); mReliableMessageMgr.Shutdown(); if (mSessionMgr != nullptr) { mSessionMgr->SetDelegate(nullptr); mSessionMgr = nullptr; } mState = State::kState_NotInitialized; return CHIP_NO_ERROR; } ExchangeContext * ExchangeManager::NewContext(SecureSessionHandle session, ExchangeDelegate * delegate) { return AllocContext(mNextExchangeId++, session, true, delegate); } CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegate * delegate) { return RegisterUMH(protocolId, kAnyMessageType, delegate); } CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType, ExchangeDelegate * delegate) { return RegisterUMH(protocolId, static_cast<int16_t>(msgType), delegate); } CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId) { return UnregisterUMH(protocolId, kAnyMessageType); } CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType) { return UnregisterUMH(protocolId, static_cast<int16_t>(msgType)); } void ExchangeManager::OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * msgLayer) { ChipLogError(ExchangeManager, "Accept FAILED, err = %s", ErrorStr(error)); } ExchangeContext * ExchangeManager::AllocContext(uint16_t ExchangeId, SecureSessionHandle session, bool Initiator, ExchangeDelegate * delegate) { CHIP_FAULT_INJECT(FaultInjection::kFault_AllocExchangeContext, return nullptr); for (auto & ec : mContextPool) { if (ec.GetReferenceCount() == 0) { return ec.Alloc(this, ExchangeId, session, Initiator, delegate); } } ChipLogError(ExchangeManager, "Alloc ctxt FAILED"); return nullptr; } CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate) { UnsolicitedMessageHandler * umh = UMHandlerPool; UnsolicitedMessageHandler * selected = nullptr; for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++) { if (umh->Delegate == nullptr) { if (selected == nullptr) selected = umh; } else if (umh->ProtocolId == protocolId && umh->MessageType == msgType) { umh->Delegate = delegate; return CHIP_NO_ERROR; } } if (selected == nullptr) return CHIP_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS; selected->Delegate = delegate; selected->ProtocolId = protocolId; selected->MessageType = msgType; SYSTEM_STATS_INCREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers); return CHIP_NO_ERROR; } CHIP_ERROR ExchangeManager::UnregisterUMH(Protocols::Id protocolId, int16_t msgType) { UnsolicitedMessageHandler * umh = UMHandlerPool; for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++) { if (umh->Delegate != nullptr && umh->ProtocolId == protocolId && umh->MessageType == msgType) { umh->Delegate = nullptr; SYSTEM_STATS_DECREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers); return CHIP_NO_ERROR; } } return CHIP_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER; } bool ExchangeManager::IsMsgCounterSyncMessage(const PayloadHeader & payloadHeader) { if (payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncReq) || payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncRsp)) { return true; } return false; } void ExchangeManager::HandleGroupMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, const SecureSessionHandle & session, System::PacketBufferHandle msgBuf) { OnMessageReceived(packetHeader, payloadHeader, session, std::move(msgBuf), nullptr); } void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, SecureSessionHandle session, System::PacketBufferHandle msgBuf, SecureSessionMgr * msgLayer) { CHIP_ERROR err = CHIP_NO_ERROR; UnsolicitedMessageHandler * umh = nullptr; UnsolicitedMessageHandler * matchingUMH = nullptr; bool sendAckAndCloseExchange = false; if (!IsMsgCounterSyncMessage(payloadHeader) && session.IsPeerGroupMsgIdNotSynchronized()) { Transport::PeerConnectionState * state = mSessionMgr->GetPeerConnectionState(session); VerifyOrReturn(state != nullptr); // Queue the message as needed for sync with destination node. err = mMessageCounterSyncMgr.AddToReceiveTable(packetHeader, payloadHeader, session, std::move(msgBuf)); VerifyOrReturn(err == CHIP_NO_ERROR); // Initiate message counter synchronization if no message counter synchronization is in progress. if (!state->IsMsgCounterSyncInProgress()) { err = mMessageCounterSyncMgr.SendMsgCounterSyncReq(session); } if (err != CHIP_NO_ERROR) { ChipLogError(ExchangeManager, "Message counter synchronization for received message, failed to send synchronization request, err = %d", err); } // After the message that triggers message counter synchronization is stored, and a message counter // synchronization exchange is initiated, we need to return immediately and re-process the original message // when the synchronization is completed. return; } // Search for an existing exchange that the message applies to. If a match is found... for (auto & ec : mContextPool) { if (ec.GetReferenceCount() > 0 && ec.MatchExchange(session, packetHeader, payloadHeader)) { // Found a matching exchange. Set flag for correct subsequent CRMP // retransmission timeout selection. if (!ec.mReliableMessageContext.HasRcvdMsgFromPeer()) { ec.mReliableMessageContext.SetMsgRcvdFromPeer(true); } // Matched ExchangeContext; send to message handler. ec.HandleMessage(packetHeader, payloadHeader, std::move(msgBuf)); ExitNow(err = CHIP_NO_ERROR); } } // Search for an unsolicited message handler if it marked as being sent by an initiator. Since we didn't // find an existing exchange that matches the message, it must be an unsolicited message. However all // unsolicited messages must be marked as being from an initiator. if (payloadHeader.IsInitiator()) { // Search for an unsolicited message handler that can handle the message. Prefer handlers that can explicitly // handle the message type over handlers that handle all messages for a profile. umh = (UnsolicitedMessageHandler *) UMHandlerPool; matchingUMH = nullptr; for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++) { if (umh->Delegate != nullptr && payloadHeader.HasProtocol(umh->ProtocolId)) { if (umh->MessageType == payloadHeader.GetMessageType()) { matchingUMH = umh; break; } if (umh->MessageType == kAnyMessageType) matchingUMH = umh; } } } // Discard the message if it isn't marked as being sent by an initiator and the message does not need to send // an ack to the peer. else if (!payloadHeader.NeedsAck()) { ExitNow(err = CHIP_ERROR_UNSOLICITED_MSG_NO_ORIGINATOR); } // If we didn't find an existing exchange that matches the message, and no unsolicited message handler registered // to hand this message, we need to create a temporary exchange to send an ack for this message and then close this exchange. sendAckAndCloseExchange = payloadHeader.NeedsAck() && (matchingUMH == nullptr); // If we found a handler or we need to create a new exchange context (EC). if (matchingUMH != nullptr || sendAckAndCloseExchange) { ExchangeContext * ec = nullptr; if (sendAckAndCloseExchange) { // If rcvd msg is from initiator then this exchange is created as not Initiator. // If rcvd msg is not from initiator then this exchange is created as Initiator. ec = AllocContext(payloadHeader.GetExchangeID(), session, !payloadHeader.IsInitiator(), nullptr); } else { ec = AllocContext(payloadHeader.GetExchangeID(), session, false, matchingUMH->Delegate); } VerifyOrExit(ec != nullptr, err = CHIP_ERROR_NO_MEMORY); ChipLogProgress(ExchangeManager, "ec pos: %d, id: %d, Delegate: 0x%x", ec - mContextPool.begin(), ec->GetExchangeId(), ec->GetDelegate()); ec->HandleMessage(packetHeader, payloadHeader, std::move(msgBuf)); // Close exchange if it was created only to send ack for a duplicate message. if (sendAckAndCloseExchange) ec->Close(); } exit: if (err != CHIP_NO_ERROR) { ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %d", err); } } ChannelHandle ExchangeManager::EstablishChannel(const ChannelBuilder & builder, ChannelDelegate * delegate) { ChannelContext * channelContext = nullptr; // Find an existing Channel matching the builder mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { if (context->MatchesBuilder(builder)) { channelContext = context; return false; } return true; }); if (channelContext == nullptr) { // create a new channel if not found channelContext = mChannelContexts.CreateObject(this); if (channelContext == nullptr) return ChannelHandle{ nullptr }; channelContext->Start(builder); } else { channelContext->Retain(); } ChannelContextHandleAssociation * association = mChannelHandles.CreateObject(channelContext, delegate); channelContext->Release(); return ChannelHandle{ association }; } void ExchangeManager::OnNewConnection(SecureSessionHandle session, SecureSessionMgr * mgr) { mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { if (context->MatchesSession(session, mgr)) { context->OnNewConnection(session); return false; } return true; }); } void ExchangeManager::OnConnectionExpired(SecureSessionHandle session, SecureSessionMgr * mgr) { for (auto & ec : mContextPool) { if (ec.GetReferenceCount() > 0 && ec.mSecureSession == session) { ec.Close(); // Continue iterate because there can be multiple contexts associated with the connection. } } mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { if (context->MatchesSession(session, mgr)) { context->OnConnectionExpired(session); return false; } return true; }); } void ExchangeManager::OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source, System::PacketBufferHandle msgBuf) { auto peer = header.GetSourceNodeId(); if (!peer.HasValue()) { char addrBuffer[Transport::PeerAddress::kMaxToStringSize]; source.ToString(addrBuffer, sizeof(addrBuffer)); ChipLogError(ExchangeManager, "Unencrypted message from %s is dropped since no source node id in packet header.", addrBuffer); return; } auto node = peer.Value(); auto notFound = mChannelContexts.ForEachActiveObject([&](ChannelContext * context) { if (context->IsCasePairing() && context->MatchNodeId(node)) { CHIP_ERROR err = context->HandlePairingMessage(header, source, std::move(msgBuf)); if (err != CHIP_NO_ERROR) ChipLogError(ExchangeManager, "HandlePairingMessage error %s from node %llu.", chip::ErrorStr(err), node); return false; } return true; }); if (notFound) { char addrBuffer[Transport::PeerAddress::kMaxToStringSize]; source.ToString(addrBuffer, sizeof(addrBuffer)); ChipLogError(ExchangeManager, "Unencrypted message from %s is dropped since no session found for node %llu.", addrBuffer, node); return; } } void ExchangeManager::IncrementContextsInUse() { mContextsInUse++; } void ExchangeManager::DecrementContextsInUse() { if (mContextsInUse >= 1) { mContextsInUse--; } else { ChipLogError(ExchangeManager, "No context in use, decrement failed"); } } } // namespace Messaging } // namespace chip <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/bfloat16_support.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" namespace xla { bool BFloat16Support::SupportsBF16Operand(const HloInstruction& hlo, int64 operand_index) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kCustomCall: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; case HloOpcode::kConvert: CHECK_EQ(operand_index, 0); return hlo.operand(0)->shape().element_type() == BF16; default: break; } return false; } bool BFloat16Support::SupportsBF16Output(const HloInstruction& hlo) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kCustomCall: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; case HloOpcode::kConvert: return hlo.shape().element_type() == BF16; default: break; } return false; } bool BFloat16Support::SupportsMixedPrecisions(const HloInstruction& hlo) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; default: break; } return false; } /* static */ bool BFloat16Support::EffectiveOperandPrecisionIsOutputPrecision( const HloInstruction& hlo, int64 operand_index) { switch (hlo.opcode()) { case HloOpcode::kAbs: case HloOpcode::kBroadcast: case HloOpcode::kClamp: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPad: case HloOpcode::kReshape: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: return true; case HloOpcode::kBitcast: return hlo.shape().element_type() == hlo.operand(0)->shape().element_type(); case HloOpcode::kDynamicSlice: return operand_index == 0; case HloOpcode::kDynamicUpdateSlice: return operand_index == 0 || operand_index == 1; case HloOpcode::kSelect: case HloOpcode::kTupleSelect: return operand_index == 1 || operand_index == 2; default: break; } return false; } bool BFloat16Support::EffectiveOperandPrecisionIsBF16( const HloInstruction& hlo, int64 operand_index) const { return false; } } // namespace xla <commit_msg>[XLA] Add kAllToAll and kCollectivePermute to EffectiveOperandPrecisionIsOutputPrecision list.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/bfloat16_support.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" namespace xla { bool BFloat16Support::SupportsBF16Operand(const HloInstruction& hlo, int64 operand_index) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kCustomCall: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; case HloOpcode::kConvert: CHECK_EQ(operand_index, 0); return hlo.operand(0)->shape().element_type() == BF16; default: break; } return false; } bool BFloat16Support::SupportsBF16Output(const HloInstruction& hlo) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kCustomCall: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; case HloOpcode::kConvert: return hlo.shape().element_type() == BF16; default: break; } return false; } bool BFloat16Support::SupportsMixedPrecisions(const HloInstruction& hlo) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; default: break; } return false; } /* static */ bool BFloat16Support::EffectiveOperandPrecisionIsOutputPrecision( const HloInstruction& hlo, int64 operand_index) { switch (hlo.opcode()) { case HloOpcode::kAbs: case HloOpcode::kAllToAll: case HloOpcode::kBroadcast: case HloOpcode::kClamp: case HloOpcode::kCollectivePermute: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPad: case HloOpcode::kReshape: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: return true; case HloOpcode::kBitcast: return hlo.shape().element_type() == hlo.operand(0)->shape().element_type(); case HloOpcode::kDynamicSlice: return operand_index == 0; case HloOpcode::kDynamicUpdateSlice: return operand_index == 0 || operand_index == 1; case HloOpcode::kSelect: case HloOpcode::kTupleSelect: return operand_index == 1 || operand_index == 2; default: break; } return false; } bool BFloat16Support::EffectiveOperandPrecisionIsBF16( const HloInstruction& hlo, int64 operand_index) const { return false; } } // namespace xla <|endoftext|>
<commit_before>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "NeighborUpdater.h" #include "fboss/agent/FbossError.h" #include "fboss/agent/SwSwitch.h" #include "fboss/agent/state/SwitchState.h" #include "fboss/agent/state/VlanMap.h" #include "fboss/agent/state/Vlan.h" #include "fboss/agent/state/ArpTable.h" #include "fboss/agent/state/NdpTable.h" #include "fboss/agent/state/StateDelta.h" #include <folly/futures/Future.h> using std::chrono::seconds; using std::shared_ptr; using boost::container::flat_map; using folly::Future; using folly::collectAll; namespace facebook { namespace fboss { class NeighborUpdaterImpl : private folly::AsyncTimeout { public: NeighborUpdaterImpl(VlanID vlan, SwSwitch *sw, const SwitchState* state); SwSwitch* getSw() const { return sw_; } static void start(void* arg); static void stop(void* arg); void stateChanged(const StateDelta& delta); private: typedef std::function< std::shared_ptr<SwitchState>(const std::shared_ptr<SwitchState>&)> StateUpdateFn; NeighborUpdaterImpl(NeighborUpdaterImpl const &) = delete; NeighborUpdaterImpl& operator=(NeighborUpdaterImpl const &) = delete; shared_ptr<SwitchState> prunePendingEntries(const shared_ptr<SwitchState>& state); bool pendingEntriesExist() const; virtual void timeoutExpired() noexcept { if (pendingEntriesExist()) { sw_->updateState("Remove pending Arp entries", prunePendingEntries_); } scheduleTimeout(interval_); } VlanID const vlan_; SwSwitch* const sw_{nullptr}; StateUpdateFn prunePendingEntries_; seconds interval_; }; NeighborUpdaterImpl::NeighborUpdaterImpl(VlanID vlan, SwSwitch *sw, const SwitchState* state) : AsyncTimeout(sw->getBackgroundEVB()), vlan_(vlan), sw_(sw), interval_(state->getArpAgerInterval()) { prunePendingEntries_ = std::bind(&NeighborUpdaterImpl::prunePendingEntries, this, std::placeholders::_1); } void NeighborUpdaterImpl::start(void* arg) { auto* ntu = static_cast<NeighborUpdaterImpl*>(arg); ntu->scheduleTimeout(ntu->interval_); } void NeighborUpdaterImpl::stop(void* arg) { auto* ntu = static_cast<NeighborUpdaterImpl*>(arg); delete ntu; } void NeighborUpdaterImpl::stateChanged(const StateDelta& delta) { // Does nothing now. We may want to subscribe to changes in the configured // interval/timeouts here if we decide want to be able to change these // values on the fly } shared_ptr<SwitchState> NeighborUpdaterImpl::prunePendingEntries(const shared_ptr<SwitchState>& state) { shared_ptr<SwitchState> newState{state}; bool modified = false; auto vlanIf = state->getVlans()->getVlanIf(vlan_); if (vlanIf) { auto vlan = vlanIf.get(); auto arpTable = vlan->getArpTable().get(); if (arpTable->hasPendingEntries()) { auto newArpTable = arpTable->modify(&vlan, &newState); if (newArpTable->prunePendingEntries()) { modified = true; } } auto ndpTable = vlan->getNdpTable().get(); if (ndpTable->hasPendingEntries()) { auto newNdpTable = ndpTable->modify(&vlan, &newState); if (newNdpTable->prunePendingEntries()) { modified = true; } } } return modified ? newState : nullptr; } bool NeighborUpdaterImpl::pendingEntriesExist() const { auto state = sw_->getState(); auto vlan = state->getVlans()->getVlanIf(vlan_); auto arpTable = vlan->getArpTable(); auto ndpTable = vlan->getNdpTable(); return arpTable->hasPendingEntries() || ndpTable->hasPendingEntries(); } NeighborUpdater::NeighborUpdater(SwSwitch* sw) : AutoRegisterStateObserver(sw, "NeighborUpdater"), sw_(sw) {} NeighborUpdater::~NeighborUpdater() { std::vector<Future<void>> stopTasks; for (auto entry : updaters_) { auto vlan = entry.first; auto updater = entry.second; std::function<void()> stopUpdater = [updater]() { NeighborUpdaterImpl::stop(updater); }; // Run the stop function in the background thread to // ensure it can be safely run auto f = via(sw_->getBackgroundEVB()) .then(stopUpdater) .onError([=](const std::exception& e) { LOG(FATAL) << "failed to stop neighbor updater w/ vlan " << vlan; }); stopTasks.push_back(std::move(f)); } // Ensure that all of the updaters have been stopped before we return collectAll(stopTasks.begin(), stopTasks.end()).get(); } void NeighborUpdater::stateUpdated(const StateDelta& delta) { CHECK(sw_->getUpdateEVB()->inRunningEventBaseThread()); for (const auto& entry : delta.getVlansDelta()) { auto oldEntry = entry.getOld(); auto newEntry = entry.getNew(); if (!newEntry) { vlanDeleted(oldEntry.get()); continue; } if (!oldEntry) { vlanAdded(delta.newState().get(), newEntry.get()); } auto res = updaters_.find(newEntry->getID()); auto updater = res->second; updater->stateChanged(delta); } } void NeighborUpdater::vlanAdded(const SwitchState* state, const Vlan* vlan) { CHECK(sw_->getUpdateEVB()->inRunningEventBaseThread()); auto updater = new NeighborUpdaterImpl(vlan->getID(), sw_, state); updaters_.emplace(vlan->getID(), updater); bool ret = sw_->getBackgroundEVB()->runInEventBaseThread( NeighborUpdaterImpl::start, updater); if (!ret) { delete updater; throw FbossError("failed to start neighbor updater"); } } void NeighborUpdater::vlanDeleted(const Vlan* vlan) { CHECK(sw_->getUpdateEVB()->inRunningEventBaseThread()); auto updater = updaters_.find(vlan->getID()); if (updater != updaters_.end()) { updaters_.erase(updater); bool ret = sw_->getBackgroundEVB()->runInEventBaseThread( NeighborUpdaterImpl::stop, (*updater).second); if (!ret) { LOG(ERROR) << "failed to stop neighbor updater"; } } else { // TODO(aeckert): May want to fatal here when an updater doesn't exist for a // specific vlan. Need to make sure that updaters are correctly created for // the initial SwitchState to avoid false positives } } }} // facebook::fboss <commit_msg>use new sugar for collect*<commit_after>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "NeighborUpdater.h" #include "fboss/agent/FbossError.h" #include "fboss/agent/SwSwitch.h" #include "fboss/agent/state/SwitchState.h" #include "fboss/agent/state/VlanMap.h" #include "fboss/agent/state/Vlan.h" #include "fboss/agent/state/ArpTable.h" #include "fboss/agent/state/NdpTable.h" #include "fboss/agent/state/StateDelta.h" #include <folly/futures/Future.h> using std::chrono::seconds; using std::shared_ptr; using boost::container::flat_map; using folly::Future; using folly::collectAll; namespace facebook { namespace fboss { class NeighborUpdaterImpl : private folly::AsyncTimeout { public: NeighborUpdaterImpl(VlanID vlan, SwSwitch *sw, const SwitchState* state); SwSwitch* getSw() const { return sw_; } static void start(void* arg); static void stop(void* arg); void stateChanged(const StateDelta& delta); private: typedef std::function< std::shared_ptr<SwitchState>(const std::shared_ptr<SwitchState>&)> StateUpdateFn; NeighborUpdaterImpl(NeighborUpdaterImpl const &) = delete; NeighborUpdaterImpl& operator=(NeighborUpdaterImpl const &) = delete; shared_ptr<SwitchState> prunePendingEntries(const shared_ptr<SwitchState>& state); bool pendingEntriesExist() const; virtual void timeoutExpired() noexcept { if (pendingEntriesExist()) { sw_->updateState("Remove pending Arp entries", prunePendingEntries_); } scheduleTimeout(interval_); } VlanID const vlan_; SwSwitch* const sw_{nullptr}; StateUpdateFn prunePendingEntries_; seconds interval_; }; NeighborUpdaterImpl::NeighborUpdaterImpl(VlanID vlan, SwSwitch *sw, const SwitchState* state) : AsyncTimeout(sw->getBackgroundEVB()), vlan_(vlan), sw_(sw), interval_(state->getArpAgerInterval()) { prunePendingEntries_ = std::bind(&NeighborUpdaterImpl::prunePendingEntries, this, std::placeholders::_1); } void NeighborUpdaterImpl::start(void* arg) { auto* ntu = static_cast<NeighborUpdaterImpl*>(arg); ntu->scheduleTimeout(ntu->interval_); } void NeighborUpdaterImpl::stop(void* arg) { auto* ntu = static_cast<NeighborUpdaterImpl*>(arg); delete ntu; } void NeighborUpdaterImpl::stateChanged(const StateDelta& delta) { // Does nothing now. We may want to subscribe to changes in the configured // interval/timeouts here if we decide want to be able to change these // values on the fly } shared_ptr<SwitchState> NeighborUpdaterImpl::prunePendingEntries(const shared_ptr<SwitchState>& state) { shared_ptr<SwitchState> newState{state}; bool modified = false; auto vlanIf = state->getVlans()->getVlanIf(vlan_); if (vlanIf) { auto vlan = vlanIf.get(); auto arpTable = vlan->getArpTable().get(); if (arpTable->hasPendingEntries()) { auto newArpTable = arpTable->modify(&vlan, &newState); if (newArpTable->prunePendingEntries()) { modified = true; } } auto ndpTable = vlan->getNdpTable().get(); if (ndpTable->hasPendingEntries()) { auto newNdpTable = ndpTable->modify(&vlan, &newState); if (newNdpTable->prunePendingEntries()) { modified = true; } } } return modified ? newState : nullptr; } bool NeighborUpdaterImpl::pendingEntriesExist() const { auto state = sw_->getState(); auto vlan = state->getVlans()->getVlanIf(vlan_); auto arpTable = vlan->getArpTable(); auto ndpTable = vlan->getNdpTable(); return arpTable->hasPendingEntries() || ndpTable->hasPendingEntries(); } NeighborUpdater::NeighborUpdater(SwSwitch* sw) : AutoRegisterStateObserver(sw, "NeighborUpdater"), sw_(sw) {} NeighborUpdater::~NeighborUpdater() { std::vector<Future<void>> stopTasks; for (auto entry : updaters_) { auto vlan = entry.first; auto updater = entry.second; std::function<void()> stopUpdater = [updater]() { NeighborUpdaterImpl::stop(updater); }; // Run the stop function in the background thread to // ensure it can be safely run auto f = via(sw_->getBackgroundEVB()) .then(stopUpdater) .onError([=](const std::exception& e) { LOG(FATAL) << "failed to stop neighbor updater w/ vlan " << vlan; }); stopTasks.push_back(std::move(f)); } // Ensure that all of the updaters have been stopped before we return collectAll(stopTasks).get(); } void NeighborUpdater::stateUpdated(const StateDelta& delta) { CHECK(sw_->getUpdateEVB()->inRunningEventBaseThread()); for (const auto& entry : delta.getVlansDelta()) { auto oldEntry = entry.getOld(); auto newEntry = entry.getNew(); if (!newEntry) { vlanDeleted(oldEntry.get()); continue; } if (!oldEntry) { vlanAdded(delta.newState().get(), newEntry.get()); } auto res = updaters_.find(newEntry->getID()); auto updater = res->second; updater->stateChanged(delta); } } void NeighborUpdater::vlanAdded(const SwitchState* state, const Vlan* vlan) { CHECK(sw_->getUpdateEVB()->inRunningEventBaseThread()); auto updater = new NeighborUpdaterImpl(vlan->getID(), sw_, state); updaters_.emplace(vlan->getID(), updater); bool ret = sw_->getBackgroundEVB()->runInEventBaseThread( NeighborUpdaterImpl::start, updater); if (!ret) { delete updater; throw FbossError("failed to start neighbor updater"); } } void NeighborUpdater::vlanDeleted(const Vlan* vlan) { CHECK(sw_->getUpdateEVB()->inRunningEventBaseThread()); auto updater = updaters_.find(vlan->getID()); if (updater != updaters_.end()) { updaters_.erase(updater); bool ret = sw_->getBackgroundEVB()->runInEventBaseThread( NeighborUpdaterImpl::stop, (*updater).second); if (!ret) { LOG(ERROR) << "failed to stop neighbor updater"; } } else { // TODO(aeckert): May want to fatal here when an updater doesn't exist for a // specific vlan. Need to make sure that updaters are correctly created for // the initial SwitchState to avoid false positives } } }} // facebook::fboss <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/bfloat16_support.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" namespace xla { bool BFloat16Support::SupportsBF16Operand(const HloInstruction& hlo, int64 operand_index) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kCustomCall: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; case HloOpcode::kConvert: CHECK_EQ(operand_index, 0); return hlo.operand(0)->shape().element_type() == BF16; default: break; } return false; } bool BFloat16Support::SupportsBF16Output(const HloInstruction& hlo) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kCustomCall: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; case HloOpcode::kConvert: return hlo.shape().element_type() == BF16; default: break; } return false; } bool BFloat16Support::SupportsMixedPrecisions(const HloInstruction& hlo) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; default: break; } return false; } /* static */ bool BFloat16Support::EffectiveOperandPrecisionIsOutputPrecision( const HloInstruction& hlo, int64 operand_index) { switch (hlo.opcode()) { case HloOpcode::kAbs: case HloOpcode::kAllToAll: case HloOpcode::kBroadcast: case HloOpcode::kClamp: case HloOpcode::kCollectivePermute: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPad: case HloOpcode::kReshape: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: return true; case HloOpcode::kBitcast: return hlo.shape().element_type() == hlo.operand(0)->shape().element_type(); case HloOpcode::kDynamicSlice: return operand_index == 0; case HloOpcode::kDynamicUpdateSlice: return operand_index == 0 || operand_index == 1; case HloOpcode::kSelect: case HloOpcode::kTupleSelect: return operand_index == 1 || operand_index == 2; case HloOpcode::kReduce: case HloOpcode::kReduceWindow: { HloComputation* reduce_comp = hlo.called_computations()[0]; for (HloInstruction* inst : reduce_comp->instructions()) { if (inst->opcode() == HloOpcode::kParameter) { continue; } for (int64 i = 0; i < inst->operand_count(); ++i) { if (!EffectiveOperandPrecisionIsOutputPrecision(*inst, i)) { return false; } } } return true; } default: break; } return false; } bool BFloat16Support::EffectiveOperandPrecisionIsBF16( const HloInstruction& hlo, int64 operand_index) const { return false; } } // namespace xla <commit_msg>[XLA] Propagate BF16 through kGather.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/bfloat16_support.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" namespace xla { bool BFloat16Support::SupportsBF16Operand(const HloInstruction& hlo, int64 operand_index) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kCustomCall: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; case HloOpcode::kConvert: CHECK_EQ(operand_index, 0); return hlo.operand(0)->shape().element_type() == BF16; default: break; } return false; } bool BFloat16Support::SupportsBF16Output(const HloInstruction& hlo) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kCustomCall: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; case HloOpcode::kConvert: return hlo.shape().element_type() == BF16; default: break; } return false; } bool BFloat16Support::SupportsMixedPrecisions(const HloInstruction& hlo) const { switch (hlo.opcode()) { case HloOpcode::kCall: case HloOpcode::kConditional: case HloOpcode::kConvert: case HloOpcode::kCustomCall: case HloOpcode::kGetTupleElement: case HloOpcode::kTuple: case HloOpcode::kWhile: return true; default: break; } return false; } /* static */ bool BFloat16Support::EffectiveOperandPrecisionIsOutputPrecision( const HloInstruction& hlo, int64 operand_index) { switch (hlo.opcode()) { case HloOpcode::kAbs: case HloOpcode::kAllToAll: case HloOpcode::kBroadcast: case HloOpcode::kClamp: case HloOpcode::kCollectivePermute: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kDomain: case HloOpcode::kGetTupleElement: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kPad: case HloOpcode::kReshape: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: return true; case HloOpcode::kBitcast: return hlo.shape().element_type() == hlo.operand(0)->shape().element_type(); case HloOpcode::kDynamicSlice: return operand_index == 0; case HloOpcode::kDynamicUpdateSlice: return operand_index == 0 || operand_index == 1; case HloOpcode::kGather: return operand_index == 0; case HloOpcode::kSelect: case HloOpcode::kTupleSelect: return operand_index == 1 || operand_index == 2; case HloOpcode::kReduce: case HloOpcode::kReduceWindow: { HloComputation* reduce_comp = hlo.called_computations()[0]; for (HloInstruction* inst : reduce_comp->instructions()) { if (inst->opcode() == HloOpcode::kParameter) { continue; } for (int64 i = 0; i < inst->operand_count(); ++i) { if (!EffectiveOperandPrecisionIsOutputPrecision(*inst, i)) { return false; } } } return true; } default: break; } return false; } bool BFloat16Support::EffectiveOperandPrecisionIsBF16( const HloInstruction& hlo, int64 operand_index) const { return false; } } // namespace xla <|endoftext|>
<commit_before>#include "text/table.h" #include "text/cmdline.h" #include "cortex/cortex.h" #include "cortex/logger.h" #include "thread/thread.h" #include "cortex/measure.hpp" #include "text/to_params.hpp" #include "optim/batch/types.h" #include "optim/stoch/types.h" #include "text/concatenate.hpp" #include "cortex/tasks/task_charset.h" #include "cortex/layers/make_layers.h" using namespace nano; template < typename tvalue > static string_t stats_to_string(const stats_t<tvalue>& stats) { return to_string(static_cast<tvalue>(stats.avg())) + "+/-" + to_string(static_cast<tvalue>(stats.stdev())) + " [" + to_string(stats.min()) + ", " + to_string(stats.max()) + "]"; } template < typename ttrainer > static void test_optimizer(model_t& model, const string_t& name, const string_t& basepath, table_t& table, const vectors_t& x0s, const ttrainer& trainer) { stats_t<scalar_t> errors; stats_t<scalar_t> speeds; stats_t<scalar_t> timings; log_info() << "<<< running " << name << " ..."; for (size_t i = 0; i < x0s.size(); ++ i) { const timer_t timer; model.load_params(x0s[i]); const auto result = trainer(); const auto opt_state = result.optimum_state(); const auto opt_speed = convergence_speed(result.optimum_states()); errors(opt_state.m_test.m_error_avg); speeds(opt_speed); timings(static_cast<scalar_t>(timer.seconds().count())); const auto path = basepath + "-trial" + to_string(i) + ".state"; const auto opt_states = result.optimum_states(); save(path, opt_states); } table.append(name) << stats_to_string(errors) << stats_to_string(speeds) << stats_to_string(timings); } static void evaluate(model_t& model, const task_t& task, const size_t fold, const loss_t& loss, const criterion_t& criterion, const vectors_t& x0s, const size_t iterations, const std::vector<batch_optimizer>& batch_optimizers, const std::vector<batch_optimizer>& minibatch_optimizers, const std::vector<stoch_optimizer>& stochastic_optimizers, const string_t& basename, const string_t& basepath, table_t& table) { const auto epsilon = scalar_t(1e-6); const auto nthreads = thread::concurrency(); for (auto optimizer : batch_optimizers) { const auto optname = "batch-" + to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { const auto params = to_params("opt", optimizer, "iters", iterations, "eps", epsilon); const auto trainer = get_trainers().get("batch", params); return trainer->train(task, fold, nthreads, loss, criterion, model); }); } for (auto optimizer : minibatch_optimizers) { const auto optname = "minibatch-" + to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { const auto params = to_params("opt", optimizer, "epochs", iterations, "eps", epsilon); const auto trainer = get_trainers().get("minibatch", params); return trainer->train(task, fold, nthreads, loss, criterion, model); }); } for (auto optimizer : stochastic_optimizers) { const auto optname = "stochastic-" + to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { const auto params = to_params("opt", optimizer, "epochs", iterations); const auto trainer = get_trainers().get("stochastic", params); return trainer->train(task, fold, nthreads, loss, criterion, model); }); } } int main(int argc, const char* argv[]) { using namespace nano; // parse the command line cmdline_t cmdline("benchmark trainers"); cmdline.add("", "mlps", "use MLPs with varying number of hidden layers"); cmdline.add("", "convnets", "use convolution networks with varying number of convolution layers"); cmdline.add("", "batch", "evaluate batch optimizers"); cmdline.add("", "batch-gd", "evaluate batch optimizer GD (gradient descent)"); cmdline.add("", "batch-cgd", "evaluate batch optimizer CGD (conjugate gradient descent)"); cmdline.add("", "batch-lbfgs", "evaluate batch optimizer LBFGS"); cmdline.add("", "minibatch", "evaluate mini-batch optimizers"); cmdline.add("", "minibatch-gd", "evaluate mini-batch optimizer GD (gradient descent)"); cmdline.add("", "minibatch-cgd", "evaluate mini-batch optimizer CGD (conjugate gradient descent)"); cmdline.add("", "minibatch-lbfgs", "evaluate mini-batch optimizer LBFGS"); cmdline.add("", "stochastic", "evaluate stochastic optimizers"); cmdline.add("", "stochastic-sg", "evaluate stochastic optimizer SG (stochastic gradient)"); cmdline.add("", "stochastic-ngd", "evaluate stochastic optimizer NGS (normalized gradient descent)"); cmdline.add("", "stochastic-sgm", "evaluate stochastic optimizer SGM (stochastic gradient with momentum)"); cmdline.add("", "stochastic-ag", "evaluate stochastic optimizer AG (Nesterov's accelerated gradient)"); cmdline.add("", "stochastic-agfr", "evaluate stochastic optimizer AG (AG + function value restarts)"); cmdline.add("", "stochastic-aggr", "evaluate stochastic optimizer AG (AG + gradient restarts)"); cmdline.add("", "stochastic-adam", "evaluate stochastic optimizer ADAM"); cmdline.add("", "stochastic-adagrad", "evaluate stochastic optimizer ADAGRAD"); cmdline.add("", "stochastic-adadelta", "evaluate stochastic optimizer ADADELTA"); cmdline.add("", "l2n-reg", "also evaluate the l2-norm-based regularizer"); cmdline.add("", "var-reg", "also evaluate the variance-based regularizer"); cmdline.add("", "trials", "number of models to train & evaluate", "10"); cmdline.add("", "iterations", "number of iterations/epochs", "64"); cmdline.process(argc, argv); // check arguments and options const bool use_mlps = cmdline.has("mlps"); const bool use_convnets = cmdline.has("convnets"); const bool use_reg_l2n = cmdline.has("l2n-reg"); const bool use_reg_var = cmdline.has("var-reg"); const auto trials = cmdline.get<size_t>("trials"); const auto iterations = cmdline.get<size_t>("iterations"); if ( !use_mlps && !use_convnets) { cmdline.usage(); } std::vector<batch_optimizer> batch_optimizers; if (cmdline.has("batch") || cmdline.has("batch-gd")) batch_optimizers.push_back(batch_optimizer::GD); if (cmdline.has("batch") || cmdline.has("batch-cgd")) batch_optimizers.push_back(batch_optimizer::CGD); if (cmdline.has("batch") || cmdline.has("batch-lbfgs")) batch_optimizers.push_back(batch_optimizer::LBFGS); std::vector<batch_optimizer> minibatch_optimizers; if (cmdline.has("minibatch") || cmdline.has("minibatch-gd")) minibatch_optimizers.push_back(batch_optimizer::GD); if (cmdline.has("minibatch") || cmdline.has("minibatch-cgd")) minibatch_optimizers.push_back(batch_optimizer::CGD); if (cmdline.has("minibatch") || cmdline.has("minibatch-lbfgs")) minibatch_optimizers.push_back(batch_optimizer::LBFGS); std::vector<stoch_optimizer> stochastic_optimizers; if (cmdline.has("stochastic") || cmdline.has("stochastic-sg")) stochastic_optimizers.push_back(stoch_optimizer::SG); if (cmdline.has("stochastic") || cmdline.has("stochastic-ngd")) stochastic_optimizers.push_back(stoch_optimizer::NGD); if (cmdline.has("stochastic") || cmdline.has("stochastic-sgm")) stochastic_optimizers.push_back(stoch_optimizer::SGM); if (cmdline.has("stochastic") || cmdline.has("stochastic-ag")) stochastic_optimizers.push_back(stoch_optimizer::AG); if (cmdline.has("stochastic") || cmdline.has("stochastic-agfr")) stochastic_optimizers.push_back(stoch_optimizer::AGFR); if (cmdline.has("stochastic") || cmdline.has("stochastic-aggr")) stochastic_optimizers.push_back(stoch_optimizer::AGGR); if (cmdline.has("stochastic") || cmdline.has("stochastic-adam")) stochastic_optimizers.push_back(stoch_optimizer::ADAM); if (cmdline.has("stochastic") || cmdline.has("stochastic-adagrad")) stochastic_optimizers.push_back(stoch_optimizer::ADAGRAD); if (cmdline.has("stochastic") || cmdline.has("stochastic-adadelta")) stochastic_optimizers.push_back(stoch_optimizer::ADADELTA); if ( batch_optimizers.empty() && minibatch_optimizers.empty() && stochastic_optimizers.empty()) { cmdline.usage(); } // create task const size_t rows = 12; const size_t cols = 12; const size_t count = thread::concurrency() * 32 * 100; const color_mode color = color_mode::rgb; charset_task_t task(charset::digit, color, rows, cols, count); task.load(); const size_t fold = 0; const auto outputs = task.osize(); // construct models const auto activation = "act-snorm"; const auto pooling = "pool-full"; const auto mlp0 = string_t(); const auto mlp1 = mlp0 + make_affine_layer(16, activation); const auto mlp2 = mlp1 + make_affine_layer(16, activation); const auto mlp3 = mlp2 + make_affine_layer(16, activation); const auto convnet1 = make_conv_pool_layer(16, 5, 5, 1, activation, pooling); const auto convnet2 = make_conv_pool_layer(16, 5, 5, 1, activation, pooling) + make_conv_layer(32, 3, 3, 2); const auto convnet3 = make_conv_layer(16, 5, 5, 1, activation) + make_conv_layer(32, 5, 5, 2, activation) + make_conv_layer(64, 3, 3, 4, activation); const string_t outlayer = make_output_layer(outputs, activation); std::vector<std::pair<string_t, string_t>> networks; if (use_mlps) { networks.emplace_back(mlp0 + outlayer, "mlp0"); networks.emplace_back(mlp1 + outlayer, "mlp1"); networks.emplace_back(mlp2 + outlayer, "mlp2"); networks.emplace_back(mlp3 + outlayer, "mlp3"); } if (use_convnets) { networks.emplace_back(convnet1 + outlayer, "convnet1"); networks.emplace_back(convnet2 + outlayer, "convnet2"); networks.emplace_back(convnet3 + outlayer, "convnet3"); } const strings_t losses = { "classnll" }; //get_losses().ids(); strings_t criteria; criteria.push_back("avg"); //get_criteria().ids(); if (use_reg_l2n) { criteria.push_back("l2n-reg"); } if (use_reg_var) { criteria.push_back("var-reg"); } // vary the model for (const auto& net : networks) { const auto& network = net.first; const auto& netname = net.second; log_info() << "<<< running network [" << network << "] ..."; const auto model = get_models().get("forward-network", network); model->resize(task, false); // generate fixed random starting points vectors_t x0s(trials); for (vector_t& x0 : x0s) { model->random_params(); model->save_params(x0); } // vary the loss for (const string_t& iloss : losses) { log_info() << "<<< running loss [" << iloss << "] ..."; const auto loss = get_losses().get(iloss); table_t table(netname + "-" + iloss); table.header() << "test error" << "convergence speed" << "time [sec]"; // vary the criteria for (const string_t& icriterion : criteria) { const auto criterion = get_criteria().get(icriterion); const auto basename = "[" + icriterion + "] "; const auto basepath = netname + "-" + iloss + "-" + icriterion + "-"; evaluate(*model, task, fold, *loss, *criterion, x0s, iterations, batch_optimizers, minibatch_optimizers, stochastic_optimizers, basename, basepath, table); } // show results table.print(std::cout); } log_info(); } // OK log_info() << done; return EXIT_SUCCESS; } <commit_msg>fix compilation (linux)<commit_after>#include "text/table.h" #include "text/cmdline.h" #include "cortex/cortex.h" #include "cortex/logger.h" #include "thread/thread.h" #include "cortex/measure.hpp" #include "text/to_params.hpp" #include "optim/batch/types.h" #include "optim/stoch/types.h" #include "text/concatenate.hpp" #include "cortex/tasks/task_charset.h" #include "cortex/layers/make_layers.h" using namespace nano; template < typename tvalue > static string_t stats_to_string(const stats_t<tvalue>& stats) { return to_string(static_cast<tvalue>(stats.avg())) + "+/-" + to_string(static_cast<tvalue>(stats.stdev())) + " [" + to_string(stats.min()) + ", " + to_string(stats.max()) + "]"; } template < typename ttrainer > static void test_optimizer(model_t& model, const string_t& name, const string_t& basepath, table_t& table, const vectors_t& x0s, const ttrainer& trainer) { stats_t<scalar_t> errors; stats_t<scalar_t> speeds; stats_t<scalar_t> timings; log_info() << "<<< running " << name << " ..."; for (size_t i = 0; i < x0s.size(); ++ i) { const nano::timer_t timer; model.load_params(x0s[i]); const auto result = trainer(); const auto opt_state = result.optimum_state(); const auto opt_speed = convergence_speed(result.optimum_states()); errors(opt_state.m_test.m_error_avg); speeds(opt_speed); timings(static_cast<scalar_t>(timer.seconds().count())); const auto path = basepath + "-trial" + to_string(i) + ".state"; const auto opt_states = result.optimum_states(); save(path, opt_states); } table.append(name) << stats_to_string(errors) << stats_to_string(speeds) << stats_to_string(timings); } static void evaluate(model_t& model, const task_t& task, const size_t fold, const loss_t& loss, const criterion_t& criterion, const vectors_t& x0s, const size_t iterations, const std::vector<batch_optimizer>& batch_optimizers, const std::vector<batch_optimizer>& minibatch_optimizers, const std::vector<stoch_optimizer>& stochastic_optimizers, const string_t& basename, const string_t& basepath, table_t& table) { const auto epsilon = scalar_t(1e-6); const auto nthreads = thread::concurrency(); for (auto optimizer : batch_optimizers) { const auto optname = "batch-" + to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { const auto params = to_params("opt", optimizer, "iters", iterations, "eps", epsilon); const auto trainer = get_trainers().get("batch", params); return trainer->train(task, fold, nthreads, loss, criterion, model); }); } for (auto optimizer : minibatch_optimizers) { const auto optname = "minibatch-" + to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { const auto params = to_params("opt", optimizer, "epochs", iterations, "eps", epsilon); const auto trainer = get_trainers().get("minibatch", params); return trainer->train(task, fold, nthreads, loss, criterion, model); }); } for (auto optimizer : stochastic_optimizers) { const auto optname = "stochastic-" + to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { const auto params = to_params("opt", optimizer, "epochs", iterations); const auto trainer = get_trainers().get("stochastic", params); return trainer->train(task, fold, nthreads, loss, criterion, model); }); } } int main(int argc, const char* argv[]) { using namespace nano; // parse the command line cmdline_t cmdline("benchmark trainers"); cmdline.add("", "mlps", "use MLPs with varying number of hidden layers"); cmdline.add("", "convnets", "use convolution networks with varying number of convolution layers"); cmdline.add("", "batch", "evaluate batch optimizers"); cmdline.add("", "batch-gd", "evaluate batch optimizer GD (gradient descent)"); cmdline.add("", "batch-cgd", "evaluate batch optimizer CGD (conjugate gradient descent)"); cmdline.add("", "batch-lbfgs", "evaluate batch optimizer LBFGS"); cmdline.add("", "minibatch", "evaluate mini-batch optimizers"); cmdline.add("", "minibatch-gd", "evaluate mini-batch optimizer GD (gradient descent)"); cmdline.add("", "minibatch-cgd", "evaluate mini-batch optimizer CGD (conjugate gradient descent)"); cmdline.add("", "minibatch-lbfgs", "evaluate mini-batch optimizer LBFGS"); cmdline.add("", "stochastic", "evaluate stochastic optimizers"); cmdline.add("", "stochastic-sg", "evaluate stochastic optimizer SG (stochastic gradient)"); cmdline.add("", "stochastic-ngd", "evaluate stochastic optimizer NGS (normalized gradient descent)"); cmdline.add("", "stochastic-sgm", "evaluate stochastic optimizer SGM (stochastic gradient with momentum)"); cmdline.add("", "stochastic-ag", "evaluate stochastic optimizer AG (Nesterov's accelerated gradient)"); cmdline.add("", "stochastic-agfr", "evaluate stochastic optimizer AG (AG + function value restarts)"); cmdline.add("", "stochastic-aggr", "evaluate stochastic optimizer AG (AG + gradient restarts)"); cmdline.add("", "stochastic-adam", "evaluate stochastic optimizer ADAM"); cmdline.add("", "stochastic-adagrad", "evaluate stochastic optimizer ADAGRAD"); cmdline.add("", "stochastic-adadelta", "evaluate stochastic optimizer ADADELTA"); cmdline.add("", "l2n-reg", "also evaluate the l2-norm-based regularizer"); cmdline.add("", "var-reg", "also evaluate the variance-based regularizer"); cmdline.add("", "trials", "number of models to train & evaluate", "10"); cmdline.add("", "iterations", "number of iterations/epochs", "64"); cmdline.process(argc, argv); // check arguments and options const bool use_mlps = cmdline.has("mlps"); const bool use_convnets = cmdline.has("convnets"); const bool use_reg_l2n = cmdline.has("l2n-reg"); const bool use_reg_var = cmdline.has("var-reg"); const auto trials = cmdline.get<size_t>("trials"); const auto iterations = cmdline.get<size_t>("iterations"); if ( !use_mlps && !use_convnets) { cmdline.usage(); } std::vector<batch_optimizer> batch_optimizers; if (cmdline.has("batch") || cmdline.has("batch-gd")) batch_optimizers.push_back(batch_optimizer::GD); if (cmdline.has("batch") || cmdline.has("batch-cgd")) batch_optimizers.push_back(batch_optimizer::CGD); if (cmdline.has("batch") || cmdline.has("batch-lbfgs")) batch_optimizers.push_back(batch_optimizer::LBFGS); std::vector<batch_optimizer> minibatch_optimizers; if (cmdline.has("minibatch") || cmdline.has("minibatch-gd")) minibatch_optimizers.push_back(batch_optimizer::GD); if (cmdline.has("minibatch") || cmdline.has("minibatch-cgd")) minibatch_optimizers.push_back(batch_optimizer::CGD); if (cmdline.has("minibatch") || cmdline.has("minibatch-lbfgs")) minibatch_optimizers.push_back(batch_optimizer::LBFGS); std::vector<stoch_optimizer> stochastic_optimizers; if (cmdline.has("stochastic") || cmdline.has("stochastic-sg")) stochastic_optimizers.push_back(stoch_optimizer::SG); if (cmdline.has("stochastic") || cmdline.has("stochastic-ngd")) stochastic_optimizers.push_back(stoch_optimizer::NGD); if (cmdline.has("stochastic") || cmdline.has("stochastic-sgm")) stochastic_optimizers.push_back(stoch_optimizer::SGM); if (cmdline.has("stochastic") || cmdline.has("stochastic-ag")) stochastic_optimizers.push_back(stoch_optimizer::AG); if (cmdline.has("stochastic") || cmdline.has("stochastic-agfr")) stochastic_optimizers.push_back(stoch_optimizer::AGFR); if (cmdline.has("stochastic") || cmdline.has("stochastic-aggr")) stochastic_optimizers.push_back(stoch_optimizer::AGGR); if (cmdline.has("stochastic") || cmdline.has("stochastic-adam")) stochastic_optimizers.push_back(stoch_optimizer::ADAM); if (cmdline.has("stochastic") || cmdline.has("stochastic-adagrad")) stochastic_optimizers.push_back(stoch_optimizer::ADAGRAD); if (cmdline.has("stochastic") || cmdline.has("stochastic-adadelta")) stochastic_optimizers.push_back(stoch_optimizer::ADADELTA); if ( batch_optimizers.empty() && minibatch_optimizers.empty() && stochastic_optimizers.empty()) { cmdline.usage(); } // create task const size_t rows = 12; const size_t cols = 12; const size_t count = thread::concurrency() * 32 * 100; const color_mode color = color_mode::rgb; charset_task_t task(charset::digit, color, rows, cols, count); task.load(); const size_t fold = 0; const auto outputs = task.osize(); // construct models const auto activation = "act-snorm"; const auto pooling = "pool-full"; const auto mlp0 = string_t(); const auto mlp1 = mlp0 + make_affine_layer(16, activation); const auto mlp2 = mlp1 + make_affine_layer(16, activation); const auto mlp3 = mlp2 + make_affine_layer(16, activation); const auto convnet1 = make_conv_pool_layer(16, 5, 5, 1, activation, pooling); const auto convnet2 = make_conv_pool_layer(16, 5, 5, 1, activation, pooling) + make_conv_layer(32, 3, 3, 2); const auto convnet3 = make_conv_layer(16, 5, 5, 1, activation) + make_conv_layer(32, 5, 5, 2, activation) + make_conv_layer(64, 3, 3, 4, activation); const string_t outlayer = make_output_layer(outputs, activation); std::vector<std::pair<string_t, string_t>> networks; if (use_mlps) { networks.emplace_back(mlp0 + outlayer, "mlp0"); networks.emplace_back(mlp1 + outlayer, "mlp1"); networks.emplace_back(mlp2 + outlayer, "mlp2"); networks.emplace_back(mlp3 + outlayer, "mlp3"); } if (use_convnets) { networks.emplace_back(convnet1 + outlayer, "convnet1"); networks.emplace_back(convnet2 + outlayer, "convnet2"); networks.emplace_back(convnet3 + outlayer, "convnet3"); } const strings_t losses = { "classnll" }; //get_losses().ids(); strings_t criteria; criteria.push_back("avg"); //get_criteria().ids(); if (use_reg_l2n) { criteria.push_back("l2n-reg"); } if (use_reg_var) { criteria.push_back("var-reg"); } // vary the model for (const auto& net : networks) { const auto& network = net.first; const auto& netname = net.second; log_info() << "<<< running network [" << network << "] ..."; const auto model = get_models().get("forward-network", network); model->resize(task, false); // generate fixed random starting points vectors_t x0s(trials); for (vector_t& x0 : x0s) { model->random_params(); model->save_params(x0); } // vary the loss for (const string_t& iloss : losses) { log_info() << "<<< running loss [" << iloss << "] ..."; const auto loss = get_losses().get(iloss); table_t table(netname + "-" + iloss); table.header() << "test error" << "convergence speed" << "time [sec]"; // vary the criteria for (const string_t& icriterion : criteria) { const auto criterion = get_criteria().get(icriterion); const auto basename = "[" + icriterion + "] "; const auto basepath = netname + "-" + iloss + "-" + icriterion + "-"; evaluate(*model, task, fold, *loss, *criterion, x0s, iterations, batch_optimizers, minibatch_optimizers, stochastic_optimizers, basename, basepath, table); } // show results table.print(std::cout); } log_info(); } // OK log_info() << done; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/optimize_dataset_op.h" // On mobile we do not provide optimize dataset op because not all of its // dependencies are available there. The op is replaced with a no-op. #if !defined(IS_MOBILE_PLATFORM) #include <map> #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/kernels/data/dataset_utils.h" #include "tensorflow/core/kernels/data/rewrite_utils.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/platform/host_info.h" #include "tensorflow/core/protobuf/rewriter_config.pb.h" namespace tensorflow { namespace data { /* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType; /* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsEnabled; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsDisabled; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsDefault; /* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes; /* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationConfigs; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2; constexpr char kOptimizerName[] = "tf_data_meta_optimizer"; constexpr char kOptimizers[] = "optimizers"; constexpr char kOptimizerConfigs[] = "optimizer_configs"; OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) { auto& op_name = ctx->def().op(); if (op_name == kOptimizeDatasetV1) { op_version_ = 1; } else if (op_name == kOptimizeDatasetV2) { op_version_ = 2; } OP_REQUIRES_OK(ctx, ctx->GetAttr(kOptimizationConfigs, &optimization_configs_)); } void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { std::vector<tstring> optimizations; if (op_version_ == 1) { OP_REQUIRES_OK( ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations)); } else if (op_version_ == 2) { std::vector<tstring> optimizations_enabled, optimizations_disabled, optimizations_default; OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled, &optimizations_enabled)); OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled, &optimizations_disabled)); OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault, &optimizations_default)); string job_name = port::JobName(); // The map that stores the live experiment names and for how much percentage // of the Borg jobs, the experiments will be randomly turned on. // clang-format off absl::flat_hash_map<string, uint64> live_experiments = { {"enable_gradient_descent", 20} }; // clang-format on auto hash_func = [](const string& str) { return Hash64(str); }; optimizations = SelectOptimizations( job_name, live_experiments, optimizations_enabled, optimizations_disabled, optimizations_default, hash_func); // Log and record the live experiments that will be applied. if (!job_name.empty() && !live_experiments.empty()) { VLOG(1) << "The input pipeline is subject to tf.data experiment. " "Please see `go/tf-data-experiments` for more details."; for (auto& pair : live_experiments) { string experiment = pair.first; if (std::find(optimizations.begin(), optimizations.end(), experiment) != optimizations.end()) { VLOG(1) << "The live experiment \"" << experiment << "\" is applied."; metrics::RecordTFDataExperiment(experiment); } } } } // The vector stores the graduated experiment names which will be turned on // for all input pipelines. // clang-format off std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"}; // clang-format on // Add the graduated experiments to the optimization list and log them. for (auto& experiment : graduated_experiments) { if (std::find(optimizations.begin(), optimizations.end(), experiment) == optimizations.end()) { optimizations.push_back(experiment); } VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied."; } // If there are no optimizations to be applied, directly return the input. if (optimizations.empty()) { *output = input; input->Ref(); return; } auto config_factory = [this, &optimizations]() { return CreateConfig(optimizations, optimization_configs_); }; Status s = RewriteDataset(ctx, input, std::move(config_factory), /*record_fingerprint=*/true, output); if (errors::IsDeadlineExceeded(s)) { // Ignore DeadlineExceeded as it implies that the attempted rewrite took too // long which should not prevent further computation. LOG(WARNING) << s.ToString(); *output = input; input->Ref(); return; } OP_REQUIRES_OK(ctx, s); } RewriterConfig OptimizeDatasetOp::CreateConfig( std::vector<tstring> optimizations, std::vector<string> optimizations_configs) { RewriterConfig rewriter_config; rewriter_config.add_optimizers(kOptimizerName); rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE); rewriter_config.set_fail_on_optimizer_errors(true); auto custom_optimizer = rewriter_config.add_custom_optimizers(); custom_optimizer->set_name(kOptimizerName); auto* custom_optimizations_list = (*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list(); for (const auto& opt : optimizations) { custom_optimizations_list->add_s(opt.data(), opt.size()); } auto* config_list = (*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs] .mutable_list(); for (const auto& config : optimizations_configs) { config_list->add_s(config.data(), config.size()); } return rewriter_config; } namespace { REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU), OptimizeDatasetOp); REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU), OptimizeDatasetOp); } // namespace } // namespace data } // namespace tensorflow #else // !IS_MOBILE_PLATFORM namespace tensorflow { namespace data { OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) {} void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { input->Ref(); *output = input; } namespace { REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU), OptimizeDatasetOp); REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU), OptimizeDatasetOp); } // namespace } // namespace data } // namespace tensorflow #endif // !IS_MOBILE_PLATFORM <commit_msg>[tf.data] Increase the roll out percentage of optimization `enable_gradient_descent` to 50%.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/optimize_dataset_op.h" // On mobile we do not provide optimize dataset op because not all of its // dependencies are available there. The op is replaced with a no-op. #if !defined(IS_MOBILE_PLATFORM) #include <map> #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/kernels/data/dataset_utils.h" #include "tensorflow/core/kernels/data/rewrite_utils.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/platform/host_info.h" #include "tensorflow/core/protobuf/rewriter_config.pb.h" namespace tensorflow { namespace data { /* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType; /* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsEnabled; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsDisabled; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsDefault; /* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes; /* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationConfigs; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2; constexpr char kOptimizerName[] = "tf_data_meta_optimizer"; constexpr char kOptimizers[] = "optimizers"; constexpr char kOptimizerConfigs[] = "optimizer_configs"; OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) { auto& op_name = ctx->def().op(); if (op_name == kOptimizeDatasetV1) { op_version_ = 1; } else if (op_name == kOptimizeDatasetV2) { op_version_ = 2; } OP_REQUIRES_OK(ctx, ctx->GetAttr(kOptimizationConfigs, &optimization_configs_)); } void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { std::vector<tstring> optimizations; if (op_version_ == 1) { OP_REQUIRES_OK( ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations)); } else if (op_version_ == 2) { std::vector<tstring> optimizations_enabled, optimizations_disabled, optimizations_default; OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled, &optimizations_enabled)); OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled, &optimizations_disabled)); OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault, &optimizations_default)); string job_name = port::JobName(); // The map that stores the live experiment names and for how much percentage // of the Borg jobs, the experiments will be randomly turned on. // clang-format off absl::flat_hash_map<string, uint64> live_experiments = { {"enable_gradient_descent", 50} }; // clang-format on auto hash_func = [](const string& str) { return Hash64(str); }; optimizations = SelectOptimizations( job_name, live_experiments, optimizations_enabled, optimizations_disabled, optimizations_default, hash_func); // Log and record the live experiments that will be applied. if (!job_name.empty() && !live_experiments.empty()) { VLOG(1) << "The input pipeline is subject to tf.data experiment. " "Please see `go/tf-data-experiments` for more details."; for (auto& pair : live_experiments) { string experiment = pair.first; if (std::find(optimizations.begin(), optimizations.end(), experiment) != optimizations.end()) { VLOG(1) << "The live experiment \"" << experiment << "\" is applied."; metrics::RecordTFDataExperiment(experiment); } } } } // The vector stores the graduated experiment names which will be turned on // for all input pipelines. // clang-format off std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"}; // clang-format on // Add the graduated experiments to the optimization list and log them. for (auto& experiment : graduated_experiments) { if (std::find(optimizations.begin(), optimizations.end(), experiment) == optimizations.end()) { optimizations.push_back(experiment); } VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied."; } // If there are no optimizations to be applied, directly return the input. if (optimizations.empty()) { *output = input; input->Ref(); return; } auto config_factory = [this, &optimizations]() { return CreateConfig(optimizations, optimization_configs_); }; Status s = RewriteDataset(ctx, input, std::move(config_factory), /*record_fingerprint=*/true, output); if (errors::IsDeadlineExceeded(s)) { // Ignore DeadlineExceeded as it implies that the attempted rewrite took too // long which should not prevent further computation. LOG(WARNING) << s.ToString(); *output = input; input->Ref(); return; } OP_REQUIRES_OK(ctx, s); } RewriterConfig OptimizeDatasetOp::CreateConfig( std::vector<tstring> optimizations, std::vector<string> optimizations_configs) { RewriterConfig rewriter_config; rewriter_config.add_optimizers(kOptimizerName); rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE); rewriter_config.set_fail_on_optimizer_errors(true); auto custom_optimizer = rewriter_config.add_custom_optimizers(); custom_optimizer->set_name(kOptimizerName); auto* custom_optimizations_list = (*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list(); for (const auto& opt : optimizations) { custom_optimizations_list->add_s(opt.data(), opt.size()); } auto* config_list = (*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs] .mutable_list(); for (const auto& config : optimizations_configs) { config_list->add_s(config.data(), config.size()); } return rewriter_config; } namespace { REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU), OptimizeDatasetOp); REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU), OptimizeDatasetOp); } // namespace } // namespace data } // namespace tensorflow #else // !IS_MOBILE_PLATFORM namespace tensorflow { namespace data { OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) {} void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { input->Ref(); *output = input; } namespace { REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU), OptimizeDatasetOp); REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU), OptimizeDatasetOp); } // namespace } // namespace data } // namespace tensorflow #endif // !IS_MOBILE_PLATFORM <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/lib/core/status.h" namespace tensorflow { using shape_inference::InferenceContext; using shape_inference::ShapeHandle; ShapeHandle _UpdatePartitionDim(InferenceContext* c, const ShapeHandle handle, const int partition_dim) { ShapeHandle newoutput0; shape_inference::DimensionHandle new_dim; TF_CHECK_OK( c->Multiply(c->Dim(handle, partition_dim), c->num_inputs(), &new_dim)); TF_CHECK_OK(c->ReplaceDim(handle, partition_dim, new_dim, &newoutput0)); return newoutput0; } REGISTER_OP("TPUPartitionedInput") .Input("inputs: N * T") .Output("output: T") .Attr("N: int >= 1") .Attr("T: type") .Attr("partition_dim: int = 0") .SetShapeFn([](InferenceContext* c) { DataType dtype; TF_RETURN_IF_ERROR(c->GetAttr("T", &dtype)); int partition_dim; TF_RETURN_IF_ERROR(c->GetAttr("partition_dim", &partition_dim)); ShapeHandle cur = c->input(c->num_inputs() - 1); for (int i = c->num_inputs() - 2; i >= 0; --i) { TF_RETURN_WITH_CONTEXT_IF_ERROR(c->Merge(c->input(i), cur, &cur), "From merging shape ", i, " with other shapes."); } if (partition_dim == -1 || dtype == DT_RESOURCE) { c->set_output(0, cur); } else { ShapeHandle newoutput0 = _UpdatePartitionDim(c, cur, partition_dim); c->set_output(0, newoutput0); } // If this is a resource, unify the resource shapes. if (dtype == DT_RESOURCE) { ShapeHandle previous_shape_handle; for (int i = c->num_inputs() - 1; i >= 0; --i) { ShapeHandle shape_handle = c->input_handle_shapes_and_types(i)->at(0).shape; if (!c->FullyDefined(shape_handle)) { return errors::InvalidArgument("Inputs must have static shape,", "input[", i, "] has unknown dimension."); } if (i != c->num_inputs() - 1) { ShapeHandle tmp; if (!c->Merge(shape_handle, previous_shape_handle, &tmp).ok()) { return errors::InvalidArgument( "Inputs must have the same shape."); } } else { previous_shape_handle = shape_handle; } } if (partition_dim == -1) { c->set_output_handle_shapes_and_types( 0, *c->input_handle_shapes_and_types(0)); } else { ShapeHandle newoutput0 = _UpdatePartitionDim(c, previous_shape_handle, partition_dim); std::vector<shape_inference::ShapeAndType> output_shapes_and_types; output_shapes_and_types.push_back(shape_inference::ShapeAndType( newoutput0, c->input_handle_shapes_and_types(0)->at(0).dtype)); c->set_output_handle_shapes_and_types(0, output_shapes_and_types); } } return Status::OK(); }); } // namespace tensorflow <commit_msg>Make sure TPUPartitionedInput shape inference doesn't crash if input handle shapes and types are not available.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/lib/core/status.h" namespace tensorflow { using shape_inference::InferenceContext; using shape_inference::ShapeHandle; ShapeHandle _UpdatePartitionDim(InferenceContext* c, const ShapeHandle handle, const int partition_dim) { ShapeHandle newoutput0; shape_inference::DimensionHandle new_dim; TF_CHECK_OK( c->Multiply(c->Dim(handle, partition_dim), c->num_inputs(), &new_dim)); TF_CHECK_OK(c->ReplaceDim(handle, partition_dim, new_dim, &newoutput0)); return newoutput0; } REGISTER_OP("TPUPartitionedInput") .Input("inputs: N * T") .Output("output: T") .Attr("N: int >= 1") .Attr("T: type") .Attr("partition_dim: int = 0") .SetShapeFn([](InferenceContext* c) { DataType dtype; TF_RETURN_IF_ERROR(c->GetAttr("T", &dtype)); int partition_dim; TF_RETURN_IF_ERROR(c->GetAttr("partition_dim", &partition_dim)); ShapeHandle cur = c->input(c->num_inputs() - 1); for (int i = c->num_inputs() - 2; i >= 0; --i) { TF_RETURN_WITH_CONTEXT_IF_ERROR(c->Merge(c->input(i), cur, &cur), "From merging shape ", i, " with other shapes."); } if (partition_dim == -1 || dtype == DT_RESOURCE) { c->set_output(0, cur); } else { ShapeHandle newoutput0 = _UpdatePartitionDim(c, cur, partition_dim); c->set_output(0, newoutput0); } // If this is a resource, unify the resource shapes. if (dtype == DT_RESOURCE) { ShapeHandle previous_shape_handle; const std::vector<shape_inference::ShapeAndType>* shapes_and_types = nullptr; for (int i = c->num_inputs() - 1; i >= 0; --i) { shapes_and_types = c->input_handle_shapes_and_types(i); if (shapes_and_types) { ShapeHandle shape_handle = shapes_and_types->at(0).shape; if (!c->FullyDefined(shape_handle)) { return errors::InvalidArgument("Inputs must have static shape,", "input[", i, "] has unknown dimension."); } if (i != c->num_inputs() - 1) { ShapeHandle tmp; if (!c->Merge(shape_handle, previous_shape_handle, &tmp).ok()) { return errors::InvalidArgument( "Inputs must have the same shape."); } } else { previous_shape_handle = shape_handle; } } } if (shapes_and_types) { if (partition_dim == -1) { c->set_output_handle_shapes_and_types(0, *shapes_and_types); } else { ShapeHandle newoutput0 = _UpdatePartitionDim(c, previous_shape_handle, partition_dim); std::vector<shape_inference::ShapeAndType> output_shapes_and_types; output_shapes_and_types.push_back(shape_inference::ShapeAndType( newoutput0, shapes_and_types->at(0).dtype)); c->set_output_handle_shapes_and_types(0, output_shapes_and_types); } } } return Status::OK(); }); } // namespace tensorflow <|endoftext|>
<commit_before>// // // #include "MicroTasksTask.h" #include "MicroTasksEvent.h" #include "MicroTasks.h" using namespace MicroTasks; uint32_t MicroTasksClass::WaitForEvent = (1 << 31); uint32_t MicroTasksClass::WaitForMessage = (1 << 30); uint32_t MicroTasksClass::WaitForMask = MicroTasksClass::WaitForEvent | WaitForMessage; uint32_t MicroTasksClass::Infinate = ~MicroTasksClass::WaitForMask; MicroTasksClass::MicroTasksClass() { } void MicroTasksClass::init() { } uint32_t MicroTasksClass::update() { Event *oNextEvent; EventListener *oNextEventListener; Task *oNextTask; // Any events triggered? for (Event *oEvent = (Event *)Event::oEvents.GetFirst(); oEvent; oEvent = oNextEvent) { oNextEvent = (Event *)oEvent->GetNext(); if (oEvent->triggered) { for (EventListener *oEventListener = (EventListener *)(oEvent->oClients.GetFirst()); oEventListener; oEventListener = oNextEventListener) { // Keep a pointer to the next task in case this on is stopped oNextEventListener = (EventListener *)(oEventListener->GetNext()); oEventListener->triggered = 1; wakeTask(oEventListener->GetTask(), WakeReason_Event); oEventListener->triggered = 0; } oEvent->triggered = 0; } } // Any tasks waiting to be woken for (Task *oTask = (Task *)oTasks.GetFirst(); oTask; oTask = oNextTask) { // Keep a pointer to the next task in case this on is stopped oNextTask = (Task *)oTask->GetNext(); if (oTask->ulNextLoop <= millis()) { wakeTask(oTask, WakeReason_Scheduled); } } // Find the time of the next event uint32_t uiNextEvent = 0xFFFFFFFF; for (Task *oTask = (Task *)oTasks.GetFirst(); oTask; oTask = (Task *)oTask->GetNext()) { if(oTask->ulNextLoop < uiNextEvent) { uiNextEvent = oTask->ulNextLoop; } } return uiNextEvent; } void MicroTasksClass::wakeTask(Task *oTask, WakeReason eReason) { // Serial.print(millis()); // Serial.print(": W "); // Serial.print((unsigned int)oTask); // Serial.print(" ["); // Serial.print((int)eReason); // Serial.print("] -> "); uint32_t ulDelay = oTask->loop(eReason); uint32_t ulNext = ulDelay & ~MicroTask.WaitForMask; oTask->uiFlags = ulDelay & MicroTask.WaitForMask; if (MicroTask.Infinate == ulNext) { oTask->ulNextLoop = 0xFFFFFFFF; // Serial.println("Forever"); } else { oTask->ulNextLoop = millis() + ulNext; // Serial.print(ulNext); // Serial.print(":"); // Serial.println(oTask->ulNextLoop); } } void MicroTasksClass::startTask(Task *oTask) { oTasks.Add(oTask); oTask->setup(); } void MicroTasksClass::stopTask(Task *oTask) { oTasks.Remove(oTask); } MicroTasksClass MicroTask; <commit_msg>Added some debug<commit_after>// // // #include "MicroTasksTask.h" #include "MicroTasksEvent.h" #include "MicroTasks.h" #include "debug.h" using namespace MicroTasks; uint32_t MicroTasksClass::WaitForEvent = (1 << 31); uint32_t MicroTasksClass::WaitForMessage = (1 << 30); uint32_t MicroTasksClass::WaitForMask = MicroTasksClass::WaitForEvent | WaitForMessage; uint32_t MicroTasksClass::Infinate = ~MicroTasksClass::WaitForMask; MicroTasksClass::MicroTasksClass() { } void MicroTasksClass::init() { } uint32_t MicroTasksClass::update() { Event *oNextEvent; EventListener *oNextEventListener; Task *oNextTask; // Any events triggered? for (Event *oEvent = (Event *)Event::oEvents.GetFirst(); oEvent; oEvent = oNextEvent) { oNextEvent = (Event *)oEvent->GetNext(); if (oEvent->triggered) { for (EventListener *oEventListener = (EventListener *)(oEvent->oClients.GetFirst()); oEventListener; oEventListener = oNextEventListener) { // Keep a pointer to the next task in case this on is stopped oNextEventListener = (EventListener *)(oEventListener->GetNext()); oEventListener->triggered = 1; wakeTask(oEventListener->GetTask(), WakeReason_Event); oEventListener->triggered = 0; } oEvent->triggered = 0; } } // Any tasks waiting to be woken uint32_t uiNextEvent = 0xFFFFFFFF; for (Task *oTask = (Task *)oTasks.GetFirst(); oTask; oTask = oNextTask) { // Keep a pointer to the next task in case this one is stopped oNextTask = (Task *)oTask->GetNext(); if (oTask->ulNextLoop <= millis()) { wakeTask(oTask, WakeReason_Scheduled); } if(oTask->ulNextLoop < uiNextEvent) { uiNextEvent = oTask->ulNextLoop; } } DEBUG_PORT.flush(); return uiNextEvent; } void MicroTasksClass::wakeTask(Task *oTask, WakeReason eReason) { DBUG(millis()); DBUG(": W "); DBUG((unsigned int)oTask); DBUG(" ["); DBUG((int)eReason); DBUG("] -> "); #ifdef ENABLE_DEBUG uint32_t ulStart = micros(); #endif uint32_t ulDelay = oTask->loop(eReason); DBUG(micros() - ulStart); DBUG(":"); uint32_t ulNext = ulDelay & ~MicroTask.WaitForMask; oTask->uiFlags = ulDelay & MicroTask.WaitForMask; if (MicroTask.Infinate == ulNext) { oTask->ulNextLoop = 0xFFFFFFFF; DBUGLN("Forever"); } else { oTask->ulNextLoop = millis() + ulNext; DBUG(ulNext); DBUG(":"); DBUGLN(oTask->ulNextLoop); } } void MicroTasksClass::startTask(Task *oTask) { oTasks.Add(oTask); oTask->setup(); } void MicroTasksClass::stopTask(Task *oTask) { oTasks.Remove(oTask); oTask->ulNextLoop = 0xFFFFFFFF; } MicroTasksClass MicroTask; <|endoftext|>
<commit_before>#include "mjolnir/graphoptimizer.h" #include "config.h" #include <ostream> #include <set> using namespace valhalla::midgard; using namespace valhalla::baldr; namespace valhalla { namespace mjolnir { GraphOptimizer::GraphOptimizer(const boost::property_tree::ptree& pt) : tile_hierarchy_(pt), graphreader_(tile_hierarchy_) { // Make sure there are at least 2 levels! if (tile_hierarchy_.levels().size() < 2) throw std::runtime_error("Bad tile hierarchy - need 2 levels"); } void GraphOptimizer::Optimize() { // Iterate through all levels and all tiles. // TODO - concurrency for (auto tile_level : tile_hierarchy_.levels()) { uint32_t level = (uint32_t)tile_level.second.level; uint32_t ntiles = tile_level.second.tiles.TileCount(); for (uint32_t tileid = 0; tileid < ntiles; tileid++) { // Get the graph tile. Skip if no tile exists (common case) GraphTileBuilder tilebuilder(tile_hierarchy_, GraphId(tileid, level, 0)); if (tilebuilder.size() == 0) { continue; } // Update nodes and directed edges as needed const GraphTileHeader* existinghdr = tilebuilder.header(); GraphTileHeaderBuilder hdrbuilder; hdrbuilder.set_nodecount(existinghdr->nodecount()); hdrbuilder.set_directededgecount(existinghdr->directededgecount()); hdrbuilder.set_edgeinfo_offset(existinghdr->edgeinfo_offset()); hdrbuilder.set_textlist_offset(existinghdr->textlist_offset()); std::vector<NodeInfoBuilder> nodes; std::vector<DirectedEdgeBuilder> directededges; // Iterate through the nodes and the directed edges uint32_t nodecount = tilebuilder.header()->nodecount(); GraphId node(tileid, level, 0); for (uint32_t i = 0; i < nodecount; i++, node++) { NodeInfoBuilder nodeinfo = tilebuilder.node(i); // Go through directed edges and update data for (uint32_t j = 0, n = nodeinfo.edge_count(); j < n; j++) { DirectedEdgeBuilder& directededge = tilebuilder.directededge( nodeinfo.edge_index() + j); // Set the opposing edge index // NOTE: shortcut edges do not always have opposing shortcuts // may need to fix this! if (directededge.shortcut()) { directededge.set_opp_index(31); } else { directededge.set_opp_index(GetOpposingEdgeIndex(node, directededge)); } directededges.emplace_back(std::move(directededge)); } // Add the node to the list nodes.emplace_back(std::move(nodeinfo)); } // Write the new file tilebuilder.Update(tile_hierarchy_, hdrbuilder, nodes, directededges); } } } // Get the GraphId of the opposing edge. uint32_t GraphOptimizer::GetOpposingEdgeIndex(const GraphId& node, DirectedEdge& edge) { // Get the tile at the end node GraphId endnode = edge.endnode(); GraphTile* tile = graphreader_.GetGraphTile(endnode); // Get the node info const NodeInfo* nodeinfo = tile->node(endnode.id()); uint32_t n = nodeinfo->edge_count(); // Get the directed edges and return when the end node matches // the specified node and length matches const DirectedEdge* directededge = tile->directededge( nodeinfo->edge_index()); for (uint32_t i = 0; i < n; i++, directededge++) { if (directededge->endnode() == node && fabs(directededge->length() - edge.length()) < 0.0001f) { return i; } } std::cout << "Opposing edge not found at LL= " << nodeinfo->latlng().lat() << "," << nodeinfo->latlng().lng() << " edges at end node= " << n << std::endl; std::cout << " Length = " << edge.length() << " Basenode " << node << " EndNode " << edge.endnode() << " sc,td,tu " << edge.shortcut() << "," << edge.trans_down() << "," << edge.trans_up() << std::endl; directededge = tile->directededge(nodeinfo->edge_index()); for (uint32_t i = 0; i < n; i++, directededge++) { std::cout << " Length = " << directededge->length() << " Endnode: " << directededge->endnode() << std::endl; } return 0; } } } <commit_msg>update logging to use logging framework<commit_after>#include "mjolnir/graphoptimizer.h" #include <valhalla/midgard/logging.h> #include <ostream> #include <set> #include <boost/format.hpp> using namespace valhalla::midgard; using namespace valhalla::baldr; namespace valhalla { namespace mjolnir { GraphOptimizer::GraphOptimizer(const boost::property_tree::ptree& pt) : tile_hierarchy_(pt), graphreader_(tile_hierarchy_) { // Make sure there are at least 2 levels! if (tile_hierarchy_.levels().size() < 2) throw std::runtime_error("Bad tile hierarchy - need 2 levels"); } void GraphOptimizer::Optimize() { // Iterate through all levels and all tiles. // TODO - concurrency for (auto tile_level : tile_hierarchy_.levels()) { uint32_t level = (uint32_t)tile_level.second.level; uint32_t ntiles = tile_level.second.tiles.TileCount(); for (uint32_t tileid = 0; tileid < ntiles; tileid++) { // Get the graph tile. Skip if no tile exists (common case) GraphTileBuilder tilebuilder(tile_hierarchy_, GraphId(tileid, level, 0)); if (tilebuilder.size() == 0) { continue; } // Update nodes and directed edges as needed const GraphTileHeader* existinghdr = tilebuilder.header(); GraphTileHeaderBuilder hdrbuilder; hdrbuilder.set_nodecount(existinghdr->nodecount()); hdrbuilder.set_directededgecount(existinghdr->directededgecount()); hdrbuilder.set_edgeinfo_offset(existinghdr->edgeinfo_offset()); hdrbuilder.set_textlist_offset(existinghdr->textlist_offset()); std::vector<NodeInfoBuilder> nodes; std::vector<DirectedEdgeBuilder> directededges; // Iterate through the nodes and the directed edges uint32_t nodecount = tilebuilder.header()->nodecount(); GraphId node(tileid, level, 0); for (uint32_t i = 0; i < nodecount; i++, node++) { NodeInfoBuilder nodeinfo = tilebuilder.node(i); // Go through directed edges and update data for (uint32_t j = 0, n = nodeinfo.edge_count(); j < n; j++) { DirectedEdgeBuilder& directededge = tilebuilder.directededge( nodeinfo.edge_index() + j); // Set the opposing edge index // NOTE: shortcut edges do not always have opposing shortcuts // may need to fix this! if (directededge.shortcut()) { directededge.set_opp_index(31); } else { directededge.set_opp_index(GetOpposingEdgeIndex(node, directededge)); } directededges.emplace_back(std::move(directededge)); } // Add the node to the list nodes.emplace_back(std::move(nodeinfo)); } // Write the new file tilebuilder.Update(tile_hierarchy_, hdrbuilder, nodes, directededges); } } } // Get the GraphId of the opposing edge. uint32_t GraphOptimizer::GetOpposingEdgeIndex(const GraphId& node, DirectedEdge& edge) { // Get the tile at the end node GraphId endnode = edge.endnode(); GraphTile* tile = graphreader_.GetGraphTile(endnode); // Get the node info const NodeInfo* nodeinfo = tile->node(endnode.id()); uint32_t n = nodeinfo->edge_count(); // Get the directed edges and return when the end node matches // the specified node and length matches const DirectedEdge* directededge = tile->directededge( nodeinfo->edge_index()); for (uint32_t i = 0; i < n; i++, directededge++) { if (directededge->endnode() == node && fabs(directededge->length() - edge.length()) < 0.0001f) { return i; } } LOG_WARN((boost::format("Opposing edge not found at LL=%1%,%2% edges at end node= %3%") % nodeinfo->latlng().lat() % nodeinfo->latlng().lng() % n).str()); LOG_WARN((boost::format("Length = %1% Basenode %2% EndNode %3% sc,td,tu %4%,%5%,%6%") % edge.length() % node % edge.endnode() % edge.shortcut() % edge.trans_down() % edge.trans_up()).str()); directededge = tile->directededge(nodeinfo->edge_index()); for (uint32_t i = 0; i < n; i++, directededge++) { LOG_WARN("Length = " + std::to_string(directededge->length()) + " Endnode: " + std::string(directededge->endnode())); } return 0; } } } <|endoftext|>
<commit_before>// Composes two transform sets. // Output transform is the result of applying the first input transform, followed by the second. #include <assert.h> #include "itkTransformFileReader.h" #include "itkTransformFileWriter.h" #include "itkTransformFactory.h" #include "itkAffineTransform.h" #include "IOHelpers.hpp" #include "Dirs.hpp" void checkUsage(int argc, char const *argv[]) { if( argc < 3 ) { cerr << "\nUsage: " << endl; cerr << argv[0] << " originalDir adjustmentDir outputDir\n\n"; exit(EXIT_FAILURE); } } int main(int argc, char const *argv[]) { // Verify the number of parameters in the command line checkUsage(argc, argv); // Generate file lists vector< string > basenames = directoryContents(argv[1]); vector< string > originalPaths = constructPaths(argv[1], basenames); vector< string > adjustmentPaths = constructPaths(argv[2], basenames); vector< string > outputPaths = constructPaths(argv[3], basenames); // clear results directory remove_all(argv[3]); create_directories(argv[3]); // Some transforms might not be registered // with the factory so we add them manually itk::TransformFactoryBase::RegisterDefaultTransforms(); // itk::TransformFactory< itk::TranslationTransform< double, 2 > >::RegisterTransform(); // Generate new transforms // TranslationTransform also has a Compose() interface, but only with other TranslationTransforms typedef itk::MatrixOffsetTransformBase< double, 2, 2 > ComposableTransformType; typedef itk::AffineTransform< double, 2 > AffineTransformType; // the first and last slices should not have adjustments // apply adjustments for every other slice for(unsigned int i=1; i < originalPaths.size() - 1; ++i) { // check that transforms are of the right dynamic type itk::TransformBase::Pointer bpOriginalTransform = readTransform(originalPaths[i]); itk::TransformBase::Pointer bpAdjustmentTransform = readTransform(adjustmentPaths[i]); ComposableTransformType *pOriginalTransform = dynamic_cast<ComposableTransformType*>( bpOriginalTransform.GetPointer() ); ComposableTransformType *pAdjustmentTransform = dynamic_cast<ComposableTransformType*>( bpAdjustmentTransform.GetPointer() ); assert( pOriginalTransform != 0 && pAdjustmentTransform != 0 ); // compose transforms // If the argument pre is true (default false), then other is precomposed with self; that is, the resulting transformation consists of first // applying other to the source, followed by self. If pre is false or omitted, then other is post-composed with self; that is the resulting // transformation consists of first applying self to the source, followed by other. This updates the Translation based on current center. AffineTransformType::Pointer outputTransform = AffineTransformType::New(); outputTransform->SetIdentity(); outputTransform->Compose(pOriginalTransform); outputTransform->Compose(pAdjustmentTransform); // save output transform writeTransform(outputTransform, outputPaths[i]); } // write out the unaltered first and last transforms copy_file( *(originalPaths.begin()), *(outputPaths.begin()) ); copy_file( *(--originalPaths.end()), *(--outputPaths.end()) ); return EXIT_SUCCESS; } <commit_msg>Use adjustmentPaths directory contents as might be a subset of originalPaths<commit_after>// Composes two transform sets. // Output transform is the result of applying the first input transform, followed by the second. #include <assert.h> #include "itkTransformFileReader.h" #include "itkTransformFileWriter.h" #include "itkTransformFactory.h" #include "itkAffineTransform.h" #include "IOHelpers.hpp" #include "Dirs.hpp" void checkUsage(int argc, char const *argv[]) { if( argc < 3 ) { cerr << "\nUsage: " << endl; cerr << argv[0] << " originalDir adjustmentDir outputDir\n\n"; exit(EXIT_FAILURE); } } int main(int argc, char const *argv[]) { // Verify the number of parameters in the command line checkUsage(argc, argv); // Generate file lists // use argv[2] instead of argv[1] because we might be examining a subset // of the original paths e.g. for testing and debugging vector< string > basenames = directoryContents(argv[2]); vector< string > originalPaths = constructPaths(argv[1], basenames); vector< string > adjustmentPaths = constructPaths(argv[2], basenames); vector< string > outputPaths = constructPaths(argv[3], basenames); // clear results directory remove_all(argv[3]); create_directories(argv[3]); // Some transforms might not be registered // with the factory so we add them manually itk::TransformFactoryBase::RegisterDefaultTransforms(); // itk::TransformFactory< itk::TranslationTransform< double, 2 > >::RegisterTransform(); // Generate new transforms // TranslationTransform also has a Compose() interface, but only with other TranslationTransforms typedef itk::MatrixOffsetTransformBase< double, 2, 2 > ComposableTransformType; typedef itk::AffineTransform< double, 2 > AffineTransformType; // the first and last slices should not have adjustments // apply adjustments for every other slice for(unsigned int i=1; i < originalPaths.size() - 1; ++i) { // check that transforms are of the right dynamic type itk::TransformBase::Pointer bpOriginalTransform = readTransform(originalPaths[i]); itk::TransformBase::Pointer bpAdjustmentTransform = readTransform(adjustmentPaths[i]); ComposableTransformType *pOriginalTransform = dynamic_cast<ComposableTransformType*>( bpOriginalTransform.GetPointer() ); ComposableTransformType *pAdjustmentTransform = dynamic_cast<ComposableTransformType*>( bpAdjustmentTransform.GetPointer() ); assert( pOriginalTransform != 0 && pAdjustmentTransform != 0 ); // compose transforms // If the argument pre is true (default false), then other is precomposed with self; that is, the resulting transformation consists of first // applying other to the source, followed by self. If pre is false or omitted, then other is post-composed with self; that is the resulting // transformation consists of first applying self to the source, followed by other. This updates the Translation based on current center. AffineTransformType::Pointer outputTransform = AffineTransformType::New(); outputTransform->SetIdentity(); outputTransform->Compose(pOriginalTransform); outputTransform->Compose(pAdjustmentTransform); // save output transform writeTransform(outputTransform, outputPaths[i]); } // write out the unaltered first and last transforms copy_file( *(originalPaths.begin()), *(outputPaths.begin()) ); copy_file( *(--originalPaths.end()), *(--outputPaths.end()) ); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- This source file is part of Hopsan NG Copyright (c) 2011 Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson, Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack This file is provided "as is", with no guarantee or warranty for the functionality or reliability of the contents. All contents in this file is the original work of the copyright holders at the Division of Fluid and Mechatronic Systems (Flumes) at Linköping University. Modifying, using or redistributing any part of this file is prohibited without explicit permission from the copyright holders. -----------------------------------------------------------------------------*/ //! //! @file SignalLookUpTable2D.hpp //! @author Björn Eriksson <bjorn.eriksson@liu.se> //! @date 2010-11-03 //! //! @brief Contains a Look Up Table 2D //! //$Id$ #ifndef SIGNALLOOKUPTABLE2D_HPP_INCLUDED #define SIGNALLOOKUPTABLE2D_HPP_INCLUDED #include "ComponentEssentials.h" #include "ComponentUtilities.h" #include <algorithm> #include <sstream> namespace hopsan { //! //! @brief The data csv file should be on , separated form or ; separated form //! //! @ingroup SignalComponents //! class SignalLookUpTable2D : public ComponentSignal { private: Port *mpIn, *mpOut; double *mpND_in, *mpND_out; int mOutDataId; std::string mDataCurveFileName; CSVParser *myDataCurve; public: static Component *Creator() { return new SignalLookUpTable2D(); } void configure() { mpIn = addReadPort("in", "NodeSignal", Port::NOTREQUIRED); mpOut = addWritePort("out", "NodeSignal", Port::NOTREQUIRED); mOutDataId=1; mDataCurveFileName = "AbsFilePath"; registerParameter("filename", "Abs. path to data file", "", mDataCurveFileName); registerParameter("outid", "csv file value column index", "", mOutDataId); myDataCurve = 0; } void initialize() { bool success=false; if (myDataCurve!=0) { delete myDataCurve; myDataCurve=0; } myDataCurve = new CSVParser(success, findFilePath(mDataCurveFileName)); if(!success) { std::stringstream ss; ss << "Unable to initialize CSV file: " << mDataCurveFileName << ", " << myDataCurve->getErrorString(); addErrorMessage(ss.str()); stopSimulation(); } else { // Make sure that selected data vector is in range if (mOutDataId >= int(myDataCurve->getNumDataCols())) { std::stringstream ss; ss << "outid:" << mOutDataId << " is out of range, limiting to: "; mOutDataId = int(myDataCurve->getNumDataCols())-1; ss << mOutDataId; addWarningMessage(ss.str()); } if (myDataCurve->getIncreasingOrDecresing(0) != 1) { myDataCurve->sortIncreasing(0); myDataCurve->calcIncreasingOrDecreasing(); } success = (myDataCurve->getIncreasingOrDecresing(0) == 1); if(!success) { std::stringstream ss; ss << "Unable to initialize CSV file: " << mDataCurveFileName << ", " << "Even after sorting, index column is still not strictly increasing"; addErrorMessage(ss.str()); stopSimulation(); } } if(success) { // std::stringstream ss; // ss << mGain << " " << myDataCurve->interpolate(mGain); // addInfoMessage(ss.str()); mpND_in = getSafeNodeDataPtr(mpIn, NodeSignal::VALUE, 0); mpND_out = getSafeNodeDataPtr(mpOut, NodeSignal::VALUE); } } void simulateOneTimestep() { // (*mpND_out) = myDataCurve->interpolate_old(*mpND_in, 1); // (*mpND_out) = myDataCurve->interpolate(*mpND_in, 1); // (*mpND_out) = myDataCurve->interpolateInc(*mpND_in, 1); (*mpND_out) = myDataCurve->interpolate(*mpND_in, mOutDataId); } void finalize() { //! @todo actually this is only needed in destructor to cleanup //Cleanup data curve if (myDataCurve!=0) { delete myDataCurve; myDataCurve=0; } } }; } #endif // SIGNALLOOKUPTABLE2D_HPP_INCLUDED <commit_msg>Incorporated the file finding capability. <commit_after>/*----------------------------------------------------------------------------- This source file is part of Hopsan NG Copyright (c) 2011 Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson, Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack This file is provided "as is", with no guarantee or warranty for the functionality or reliability of the contents. All contents in this file is the original work of the copyright holders at the Division of Fluid and Mechatronic Systems (Flumes) at Linköping University. Modifying, using or redistributing any part of this file is prohibited without explicit permission from the copyright holders. -----------------------------------------------------------------------------*/ //! //! @file SignalLookUpTable2D.hpp //! @author Björn Eriksson <bjorn.eriksson@liu.se> //! @date 2010-11-03 //! //! @brief Contains a Look Up Table 2D //! //$Id$ #ifndef SIGNALLOOKUPTABLE2D_HPP_INCLUDED #define SIGNALLOOKUPTABLE2D_HPP_INCLUDED #include "ComponentEssentials.h" #include "ComponentUtilities.h" #include <algorithm> #include <sstream> namespace hopsan { //! //! @brief The data csv file should be on , separated form or ; separated form //! //! @ingroup SignalComponents //! class SignalLookUpTable2D : public ComponentSignal { private: Port *mpIn, *mpOut; double *mpND_in, *mpND_out; int mOutDataId; std::string mDataCurveFileName; CSVParser *myDataCurve; public: static Component *Creator() { return new SignalLookUpTable2D(); } void configure() { mpIn = addReadPort("in", "NodeSignal", Port::NOTREQUIRED); mpOut = addWritePort("out", "NodeSignal", Port::NOTREQUIRED); mOutDataId=1; mDataCurveFileName = "FilePath"; registerParameter("filename", "Abs. path to data file", "", mDataCurveFileName); registerParameter("outid", "csv file value column index", "", mOutDataId); myDataCurve = 0; } void initialize() { bool success=false; if (myDataCurve!=0) { delete myDataCurve; myDataCurve=0; } myDataCurve = new CSVParser(success, findFilePath(mDataCurveFileName)); if(!success) { std::stringstream ss; ss << "Unable to initialize CSV file: " << mDataCurveFileName << ", " << myDataCurve->getErrorString(); addErrorMessage(ss.str()); stopSimulation(); } else { // Make sure that selected data vector is in range if (mOutDataId >= int(myDataCurve->getNumDataCols())) { std::stringstream ss; ss << "outid:" << mOutDataId << " is out of range, limiting to: "; mOutDataId = int(myDataCurve->getNumDataCols())-1; ss << mOutDataId; addWarningMessage(ss.str()); } if (myDataCurve->getIncreasingOrDecresing(0) != 1) { myDataCurve->sortIncreasing(0); myDataCurve->calcIncreasingOrDecreasing(); } success = (myDataCurve->getIncreasingOrDecresing(0) == 1); if(!success) { std::stringstream ss; ss << "Unable to initialize CSV file: " << mDataCurveFileName << ", " << "Even after sorting, index column is still not strictly increasing"; addErrorMessage(ss.str()); stopSimulation(); } } if(success) { // std::stringstream ss; // ss << mGain << " " << myDataCurve->interpolate(mGain); // addInfoMessage(ss.str()); mpND_in = getSafeNodeDataPtr(mpIn, NodeSignal::VALUE, 0); mpND_out = getSafeNodeDataPtr(mpOut, NodeSignal::VALUE); } } void simulateOneTimestep() { // (*mpND_out) = myDataCurve->interpolate_old(*mpND_in, 1); // (*mpND_out) = myDataCurve->interpolate(*mpND_in, 1); // (*mpND_out) = myDataCurve->interpolateInc(*mpND_in, 1); (*mpND_out) = myDataCurve->interpolate(*mpND_in, mOutDataId); } void finalize() { //! @todo actually this is only needed in destructor to cleanup //Cleanup data curve if (myDataCurve!=0) { delete myDataCurve; myDataCurve=0; } } }; } #endif // SIGNALLOOKUPTABLE2D_HPP_INCLUDED <|endoftext|>
<commit_before> #include "FibonacciHeap.h" using namespace std; FibonacciHeap::FibonacciHeap() { minPointer = NULL; nodes = 0; } FibonacciHeap::~FibonacciHeap() { } void FibonacciHeap::addToRoot(FibonacciNode* x) { if(!minPointer) { minPointer = x; x->leftSibling = x; x->rightSibling = x; } else { x->rightSibling = minPointer->rightSibling; x->leftSibling = minPointer; minPointer->rightSibling = x; x->rightSibling->leftSibling = x; } } void FibonacciHeap::consolidate() { } void FibonacciHeap::heapLink(FibonacciNode* x, FibonacciNode* y) { y->leftSibling->rightSibling = y->rightSibling; y->leftSibling = x->child; y->rightSibling = x->child->rightSibling; x->child->rightSibling = y; x->degree++; y->mark = false; } void FibonacciHeap::cut(FibonacciNode* x, FibonacciNode* y) { x->rightSibling->leftSibling = x->leftSibling; x->leftSibling->rightSibling = x->rightSibling; y->degree--; // If x is the first child, update parent's(y) child pointer if(y->child == x) y->child = x->rightSibling; // Add x to the root list addToRoot(x); x->parent = NULL; x->mark = false; } void FibonacciHeap::cascadingCut(FibonacciNode* y) { FibonacciNode* z = y->parent; if(z) { if(y->mark == false) y->mark = true; else { cut(y, z); cascadingCut(z); } } } void FibonacciHeap :: makeHeap() { } Location FibonacciHeap :: insertKey(Priority key) { FibonacciNode* newNode = new FibonacciNode; newNode->degree = 0; newNode->parent = NULL; newNode->child = NULL; newNode->mark = false; newNode->key = key; setLocation(newNode, key); addToRoot(newNode); if(newNode->key < minPointer->key) minPointer = newNode; nodes++; return newNode; } int FibonacciHeap :: deleteKey(Location nodeAddress) { decreaseKey(nodeAddress, -1); extractMin(); return 0; } Priority FibonacciHeap :: extractMin() { FibonacciNode* extractedNode = minPointer; if(!extractedNode) { FibonacciNode *childPointer = extractedNode->child, *nextChild; while(childPointer) { nextChild = childPointer->rightSibling; childPointer->rightSibling = minPointer->rightSibling; childPointer->leftSibling = minPointer; minPointer->rightSibling = childPointer; childPointer->parent = NULL; childPointer = nextChild; } extractedNode->leftSibling->rightSibling = extractedNode->rightSibling; if(extractedNode == extractedNode->rightSibling) minPointer = NULL; else consolidate(); nodes--; return extractedNode->key; } minPointer->leftSibling->rightSibling = minPointer->rightSibling; delete minPointer; return 0; } Priority FibonacciHeap :: findMin() { return minPointer->key; } bool FibonacciHeap :: increaseKey(Location nodeAddress, Priority newKey) { return true; } bool FibonacciHeap :: decreaseKey(Location nodeAddress, Priority newKey) { FibonacciNode* x = (FibonacciNode*)nodeAddress; FibonacciNode* y; if(newKey > x->key) return -1; x->key = newKey; y = x->parent; if((y != NULL) && (x->key < y->key)) { cut(x, y); cascadingCut(y); } if(x->key < minPointer->key) minPointer = x; return true; } bool FibonacciHeap :: displayHeap(char* fileName) { FibonacciNode* temp = minPointer; do { cout << temp->key << " "; temp = temp->leftSibling; } while(temp != minPointer); return true; } <commit_msg>consolidate added<commit_after> #include "FibonacciHeap.h" using namespace std; FibonacciHeap::FibonacciHeap() { minPointer = NULL; nodes = 0; } FibonacciHeap::~FibonacciHeap() { } void FibonacciHeap::addToRoot(FibonacciNode* x) { if(!minPointer) { minPointer = x; x->leftSibling = x; x->rightSibling = x; } else { x->rightSibling = minPointer->rightSibling; x->leftSibling = minPointer; minPointer->rightSibling = x; x->rightSibling->leftSibling = x; } } void FibonacciHeap::consolidate() { std::map<int, Location> rankToAddress; FibonacciNode * temp = minPointer, * x,*y; Priority rank; bool updateRootList = true; while(updateRootList) { y = temp; temp = temp->rightSibling; if(rankToAddress.count(y->degree) == 0) { rankToAddress[y->degree] = y; } else if(rankToAddress.count(y->degree) > 0 && rankToAddress(y->degree) != y) { while(rankToAddress.count(y->degree) > 0) { x = rankToAddress(y->degree); if(y->key < x->key ) { rankToAddress.erase(x->degree); heapLink(y,x); if (rankToAddress[y->degree] != NULL) continue; else rankToAddress[y->degree] = y; if (minPointer->key > y->key) { minPointer = y; } } else { rankToAddress.erase(x->degree); heapLink(x,y); if (rankToAddress[x->degree]!= NULL) { y = x; continue; } else rankToAddress[x->degree] = x; if (minPointer->key > x->key) { minPointer = x; } } } } else { updateRootList = false; } } } void FibonacciHeap::heapLink(FibonacciNode* x, FibonacciNode* y) { y->leftSibling->rightSibling = y->rightSibling; y->leftSibling = x->child; y->rightSibling = x->child->rightSibling; x->child->rightSibling = y; y->parent = x; x->degree++; y->mark = false; } void FibonacciHeap::cut(FibonacciNode* x, FibonacciNode* y) { x->rightSibling->leftSibling = x->leftSibling; x->leftSibling->rightSibling = x->rightSibling; y->degree--; // If x is the first child, update parent's(y) child pointer if(y->child == x) y->child = x->rightSibling; // Add x to the root list addToRoot(x); x->parent = NULL; x->mark = false; } void FibonacciHeap::cascadingCut(FibonacciNode* y) { FibonacciNode* z = y->parent; if(z) { if(y->mark == false) y->mark = true; else { cut(y, z); cascadingCut(z); } } } void FibonacciHeap :: makeHeap() { } Location FibonacciHeap :: insertKey(Priority key) { FibonacciNode* newNode = new FibonacciNode; newNode->degree = 0; newNode->parent = NULL; newNode->child = NULL; newNode->mark = false; newNode->key = key; setLocation(newNode, key); addToRoot(newNode); if(newNode->key < minPointer->key) minPointer = newNode; nodes++; return newNode; } int FibonacciHeap :: deleteKey(Location nodeAddress) { decreaseKey(nodeAddress, -1); extractMin(); return 0; } Priority FibonacciHeap :: extractMin() { FibonacciNode* extractedNode = minPointer; if(!extractedNode) { FibonacciNode *childPointer = extractedNode->child, *nextChild; while(childPointer) { nextChild = childPointer->rightSibling; childPointer->rightSibling = minPointer->rightSibling; childPointer->leftSibling = minPointer; minPointer->rightSibling = childPointer; childPointer->parent = NULL; childPointer = nextChild; } extractedNode->leftSibling->rightSibling = extractedNode->rightSibling; if(extractedNode == extractedNode->rightSibling) minPointer = NULL; else consolidate(); nodes--; return extractedNode->key; } minPointer->leftSibling->rightSibling = minPointer->rightSibling; delete minPointer; return 0; } Priority FibonacciHeap :: findMin() { return minPointer->key; } bool FibonacciHeap :: increaseKey(Location nodeAddress, Priority newKey) { return true; } bool FibonacciHeap :: decreaseKey(Location nodeAddress, Priority newKey) { FibonacciNode* x = (FibonacciNode*)nodeAddress; FibonacciNode* y; if(newKey > x->key) return -1; x->key = newKey; y = x->parent; if((y != NULL) && (x->key < y->key)) { cut(x, y); cascadingCut(y); } if(x->key < minPointer->key) minPointer = x; return true; } bool FibonacciHeap :: displayHeap(char* fileName) { FibonacciNode* temp = minPointer; do { cout << temp->key << " "; temp = temp->leftSibling; } while(temp != minPointer); return true; } <|endoftext|>
<commit_before>#include "stdafx.h" #ifdef _WIN32 #include "OculusInterfaceHelper.hpp" #include "AnnLogger.hpp" #include "AnnException.hpp" using namespace std; using namespace OVR; using namespace Annwvyn; void OculusInterfaceHelper::abortOnFailure() { session = {}; luid = {}; hmdDesc = {}; //Notify user AnnDebug() << "Error: Cannot create Oculus Session"; //Debug HMD is now handled by the configuration utility and the runtime. AnnDebug() << "Please make sure Oculus Home is installed on your system and " "please check if you have correctly plugged HDMI and USB on the Rift and Tracker"; displayWin32ErrorMessage(L"Error: Cannot create Oculus Session!", L"Please make sure Oculus Home is installed on your system\n" L"and check HDMI and USB connection to your Rift and Tracker"); //Cleanup ovr_Shutdown(); //Return an error AnnDebug() << "Unable to Initialize client library or get a session valid from the Oculus Runtime. Closing program and returning 0xDEAD60D error"; //Stop program throw AnnInitializationError(ANN_ERR_CRITIC, "Unable to create an Oculus session"); } OculusInterfaceHelper::OculusInterfaceHelper() { AnnDebug() << "Init Oculus Interface object"; //Init Oculus Virtual Reality library if (OVR_FAILURE(ovr_Initialize(nullptr))) abortOnFailure(); //Declare this client to the Oculus service stringstream clientIentifier; clientIentifier << "EngineName: Annwvyn\n"; clientIentifier << "EngineVersion: " << AnnEngine::getAnnwvynVersion(); ovr_IdentifyClient(clientIentifier.str().c_str()); AnnDebug() << "Identifier string sent to the Oculus Service : \n" << clientIentifier.str(); AnnDebug() << "LibOVR version : " << ovr_GetVersionString(); //Attempt to create OVR session if (OVR_FAILURE(ovr_Create(&session, &luid))) abortOnFailure(); //Fill the hmdDesc structure hmdDesc = ovr_GetHmdDesc(session); //Print to log all known information about the headset logHardwareReport(); } OculusInterfaceHelper::~OculusInterfaceHelper() { //Set the performance HUD to Off ovr_SetInt(getSession(), "PerfHudMode", ovrPerfHud_Off); AnnDebug() << "Shutdown OculusInterfaceHelper object"; ovr_Destroy(getSession()); ovr_Shutdown(); AnnDebug() << "LibOVR Shutdown... No longer can communicate with OculusService"; } inline Ogre::Vector3 oculusToOgreVect3(const ovrVector3f & v) { return{ v.x, v.y, v.z }; } inline Ogre::Quaternion oculusToOgreQuat(const ovrQuatf & q) { return{ q.w, q.x, q.y, q.z }; } void OculusInterfaceHelper::logHardwareReport() const { //Print to the logger a bunch of information AnnDebug() << " - Detected Oculus hardware :"; AnnDebug() << "OVR version " << ovr_GetVersionString(); AnnDebug() << "Detected the following Oculus Rift VR Headset :"; AnnDebug() << "Product name : " << hmdDesc.ProductName; AnnDebug() << "Serial number : " << hmdDesc.SerialNumber; AnnDebug() << "Manufacturer : " << hmdDesc.Manufacturer; AnnDebug() << "Display Resolution : " << hmdDesc.Resolution.w << "x" << hmdDesc.Resolution.h; AnnDebug() << "Display refresh rate : " << hmdDesc.DisplayRefreshRate << "Hz"; AnnDebug() << "Type of HMD identifier : " << hmdDesc.Type; AnnDebug() << "Firmware version : " << hmdDesc.FirmwareMajor << "." << hmdDesc.FirmwareMinor; const auto trackerCount{ ovr_GetTrackerCount(session) }; AnnDebug() << "Detected " << trackerCount << " Oculus Sensors"; for (auto i{ 0u }; i < trackerCount; ++i) { const auto tracker = 1 + i; const auto trackerPose = ovr_GetTrackerPose(session, i).Pose; const auto desc = ovr_GetTrackerDesc(session, i); AnnDebug() << "Tracker_" << tracker << " Pose : " << oculusToOgreVect3(trackerPose.Position) << "; " << oculusToOgreQuat(trackerPose.Orientation); AnnDebug() << "Tracker_" << tracker << " Camera Frustum : Near " << desc.FrustumNearZInMeters << "m Far " << desc.FrustumFarZInMeters << "m H fov " << desc.FrustumHFovInRadians << "rad V fov " << desc.FrustumVFovInRadians << "rad"; } } ovrHmdDesc OculusInterfaceHelper::getHmdDesc() const { return hmdDesc; } ovrSession OculusInterfaceHelper::getSession() const { return session; } float OculusInterfaceHelper::getUserEyeHeight() const { return ovr_GetFloat(session, "EyeHeight", -1.f); } void OculusInterfaceHelper::recenterTrackingOrigin() const { ovr_RecenterTrackingOrigin(session); } void OculusInterfaceHelper::setPerfHudMode(ovrPerfHudMode mode) const { ovr_SetInt(session, "PerfHudMode", int(mode)); } ovrSizei OculusInterfaceHelper::getHmdResolution() const { return hmdDesc.Resolution; } float OculusInterfaceHelper::getHmdDisplayRefreshRate() const { return hmdDesc.DisplayRefreshRate; } void OculusInterfaceHelper::setTrackingOriginToFloorLevel() const { ovr_SetTrackingOriginType(session, ovrTrackingOrigin_FloorLevel); } #endif<commit_msg>Set the "ovrInit_focusAware" flag at initalization<commit_after>#include "stdafx.h" #ifdef _WIN32 #include "OculusInterfaceHelper.hpp" #include "AnnLogger.hpp" #include "AnnException.hpp" using namespace std; using namespace OVR; using namespace Annwvyn; void OculusInterfaceHelper::abortOnFailure() { session = {}; luid = {}; hmdDesc = {}; //Notify user AnnDebug() << "Error: Cannot create Oculus Session"; //Debug HMD is now handled by the configuration utility and the runtime. AnnDebug() << "Please make sure Oculus Home is installed on your system and " "please check if you have correctly plugged HDMI and USB on the Rift and Tracker"; displayWin32ErrorMessage(L"Error: Cannot create Oculus Session!", L"Please make sure Oculus Home is installed on your system\n" L"and check HDMI and USB connection to your Rift and Tracker"); //Cleanup ovr_Shutdown(); //Return an error AnnDebug() << "Unable to Initialize client library or get a session valid from the Oculus Runtime. Closing program and returning 0xDEAD60D error"; //Stop program throw AnnInitializationError(ANN_ERR_CRITIC, "Unable to create an Oculus session"); } OculusInterfaceHelper::OculusInterfaceHelper() { AnnDebug() << "Init Oculus Interface object"; ovrInitParams params = { ovrInit_FocusAware }; //Init Oculus Virtual Reality library if (OVR_FAILURE(ovr_Initialize(&params))) abortOnFailure(); //Declare this client to the Oculus service stringstream clientIentifier; clientIentifier << "EngineName: Annwvyn\n"; clientIentifier << "EngineVersion: " << AnnEngine::getAnnwvynVersion(); ovr_IdentifyClient(clientIentifier.str().c_str()); AnnDebug() << "Identifier string sent to the Oculus Service : \n" << clientIentifier.str(); AnnDebug() << "LibOVR version : " << ovr_GetVersionString(); //Attempt to create OVR session if (OVR_FAILURE(ovr_Create(&session, &luid))) abortOnFailure(); //Fill the hmdDesc structure hmdDesc = ovr_GetHmdDesc(session); //Print to log all known information about the headset logHardwareReport(); } OculusInterfaceHelper::~OculusInterfaceHelper() { //Set the performance HUD to Off ovr_SetInt(getSession(), "PerfHudMode", ovrPerfHud_Off); AnnDebug() << "Shutdown OculusInterfaceHelper object"; ovr_Destroy(getSession()); ovr_Shutdown(); AnnDebug() << "LibOVR Shutdown... No longer can communicate with OculusService"; } inline Ogre::Vector3 oculusToOgreVect3(const ovrVector3f & v) { return{ v.x, v.y, v.z }; } inline Ogre::Quaternion oculusToOgreQuat(const ovrQuatf & q) { return{ q.w, q.x, q.y, q.z }; } void OculusInterfaceHelper::logHardwareReport() const { //Print to the logger a bunch of information AnnDebug() << " - Detected Oculus hardware :"; AnnDebug() << "OVR version " << ovr_GetVersionString(); AnnDebug() << "Detected the following Oculus Rift VR Headset :"; AnnDebug() << "Product name : " << hmdDesc.ProductName; AnnDebug() << "Serial number : " << hmdDesc.SerialNumber; AnnDebug() << "Manufacturer : " << hmdDesc.Manufacturer; AnnDebug() << "Display Resolution : " << hmdDesc.Resolution.w << "x" << hmdDesc.Resolution.h; AnnDebug() << "Display refresh rate : " << hmdDesc.DisplayRefreshRate << "Hz"; AnnDebug() << "Type of HMD identifier : " << hmdDesc.Type; AnnDebug() << "Firmware version : " << hmdDesc.FirmwareMajor << "." << hmdDesc.FirmwareMinor; const auto trackerCount{ ovr_GetTrackerCount(session) }; AnnDebug() << "Detected " << trackerCount << " Oculus Sensors"; for (auto i{ 0u }; i < trackerCount; ++i) { const auto tracker = 1 + i; const auto trackerPose = ovr_GetTrackerPose(session, i).Pose; const auto desc = ovr_GetTrackerDesc(session, i); AnnDebug() << "Tracker_" << tracker << " Pose : " << oculusToOgreVect3(trackerPose.Position) << "; " << oculusToOgreQuat(trackerPose.Orientation); AnnDebug() << "Tracker_" << tracker << " Camera Frustum : Near " << desc.FrustumNearZInMeters << "m Far " << desc.FrustumFarZInMeters << "m H fov " << desc.FrustumHFovInRadians << "rad V fov " << desc.FrustumVFovInRadians << "rad"; } } ovrHmdDesc OculusInterfaceHelper::getHmdDesc() const { return hmdDesc; } ovrSession OculusInterfaceHelper::getSession() const { return session; } float OculusInterfaceHelper::getUserEyeHeight() const { return ovr_GetFloat(session, "EyeHeight", -1.f); } void OculusInterfaceHelper::recenterTrackingOrigin() const { ovr_RecenterTrackingOrigin(session); } void OculusInterfaceHelper::setPerfHudMode(ovrPerfHudMode mode) const { ovr_SetInt(session, "PerfHudMode", int(mode)); } ovrSizei OculusInterfaceHelper::getHmdResolution() const { return hmdDesc.Resolution; } float OculusInterfaceHelper::getHmdDisplayRefreshRate() const { return hmdDesc.DisplayRefreshRate; } void OculusInterfaceHelper::setTrackingOriginToFloorLevel() const { ovr_SetTrackingOriginType(session, ovrTrackingOrigin_FloorLevel); } #endif<|endoftext|>
<commit_before> /*========================================================================= Program: Visualization Toolkit Module: vtkDICOMImageReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "DICOMParser.h" #include "DICOMAppHelper.h" #include "vtkDICOMImageReader.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkDirectory.h" #include <vtkstd/vector> #include <vtkstd/string> vtkCxxRevisionMacro(vtkDICOMImageReader, "1.23"); vtkStandardNewMacro(vtkDICOMImageReader); class vtkDICOMImageReaderVector : public vtkstd::vector<vtkstd::string> { }; vtkDICOMImageReader::vtkDICOMImageReader() { this->Parser = new DICOMParser(); this->AppHelper = new DICOMAppHelper(); this->DirectoryName = NULL; this->PatientName = NULL; this->StudyUID = NULL; this->StudyID = NULL; this->TransferSyntaxUID = NULL; this->DICOMFileNames = new vtkDICOMImageReaderVector(); } vtkDICOMImageReader::~vtkDICOMImageReader() { delete this->Parser; delete this->AppHelper; delete this->DICOMFileNames; if (this->DirectoryName) { delete [] this->DirectoryName; } if (this->PatientName) { delete [] this->PatientName; } if (this->StudyUID) { delete [] this->StudyUID; } if (this->StudyID) { delete [] this->StudyID; } if (this->TransferSyntaxUID) { delete [] this->TransferSyntaxUID; } } void vtkDICOMImageReader::PrintSelf(ostream& os, vtkIndent indent) { this->vtkImageReader2::PrintSelf(os, indent); if (this->DirectoryName) { os << "DirectoryName : " << this->DirectoryName << "\n"; } else { os << "DirectoryName : (NULL)" << "\n"; } if (this->FileName) { os << "FileName : " << this->FileName << "\n"; } else { os << "FileName : (NULL)" << "\n"; } } int vtkDICOMImageReader::CanReadFile(const char* fname) { bool canOpen = this->Parser->OpenFile((char*) fname); if (canOpen == false) { vtkErrorMacro("DICOMParser couldn't open : " << fname); return 0; } bool canRead = this->Parser->IsDICOMFile(); if (canRead == true) { return 1; } else { return 0; } } void vtkDICOMImageReader::ExecuteInformation() { if (this->FileName == NULL && this->DirectoryName == NULL) { return; } if (this->FileName) { this->DICOMFileNames->clear(); this->AppHelper->Clear(); this->Parser->ClearAllDICOMTagCallbacks(); this->Parser->OpenFile(this->FileName); this->AppHelper->RegisterCallbacks(this->Parser); this->Parser->ReadHeader(); this->SetupOutputInformation(1); } else if (this->DirectoryName) { vtkDirectory* dir = vtkDirectory::New(); int opened = dir->Open(this->DirectoryName); if (!opened) { vtkErrorMacro("Couldn't open " << this->DirectoryName); dir->Delete(); return; } int numFiles = dir->GetNumberOfFiles(); vtkDebugMacro( << "There are " << numFiles << " files in the directory."); this->DICOMFileNames->clear(); this->AppHelper->Clear(); for (int i = 0; i < numFiles; i++) { if (strcmp(dir->GetFile(i), ".") == 0 || strcmp(dir->GetFile(i), "..") == 0) { continue; } vtkstd::string fileString = this->DirectoryName; fileString += "/"; fileString += dir->GetFile(i); int val = this->CanReadFile(fileString.c_str()); if (val == 1) { vtkDebugMacro( << "Adding " << fileString.c_str() << " to DICOMFileNames."); this->DICOMFileNames->push_back(fileString); } else { vtkDebugMacro( << fileString.c_str() << " - DICOMParser CanReadFile returned : " << val); } } vtkstd::vector<vtkstd::string>::iterator iter; for (iter = this->DICOMFileNames->begin(); iter != this->DICOMFileNames->end(); iter++) { char* fn = (char*) (*iter).c_str(); vtkDebugMacro( << "Trying : " << fn); bool couldOpen = this->Parser->OpenFile(fn); if (!couldOpen) { dir->Delete(); return; } // this->Parser->ClearAllDICOMTagCallbacks(); this->AppHelper->RegisterCallbacks(this->Parser); this->Parser->ReadHeader(); vtkDebugMacro( << "File name : " << fn ); vtkDebugMacro( << "Slice number : " << this->AppHelper->GetSliceNumber()); } vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles; this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles, false); this->SetupOutputInformation(static_cast<int>(sortedFiles.size())); //this->AppHelper->OutputSeries(); if (sortedFiles.size() > 0) { this->DICOMFileNames->clear(); vtkstd::vector<vtkstd::pair<float, vtkstd::string> >::iterator siter; for (siter = sortedFiles.begin(); siter != sortedFiles.end(); siter++) { vtkDebugMacro(<< "Sorted filename : " << (*siter).second.c_str()); vtkDebugMacro(<< "Adding file " << (*siter).second.c_str() << " at slice : " << (*siter).first); this->DICOMFileNames->push_back((*siter).second); } } else { vtkErrorMacro( << "Couldn't get sorted files. Slices may be in wrong order!"); } dir->Delete(); } } void vtkDICOMImageReader::ExecuteData(vtkDataObject *output) { vtkImageData *data = this->AllocateOutputData(output); if (!this->FileName && this->DICOMFileNames->size() == 0) { vtkErrorMacro( << "Either a filename was not specified or the specified directory does not contain any DICOM images."); return; } data->GetPointData()->GetScalars()->SetName("DICOMImage"); this->ComputeDataIncrements(); // Get the pointer to the output pixel data void *outPtr; outPtr = data->GetScalarPointer(); if (this->FileName) { vtkDebugMacro( << "Single file : " << this->FileName); this->Parser->ClearAllDICOMTagCallbacks(); this->Parser->OpenFile(this->FileName); this->AppHelper->Clear(); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->RegisterPixelDataCallback(this->Parser); this->Parser->ReadHeader(); void* imgData = NULL; DICOMParser::VRTypes dataType; unsigned long imageDataLength; this->AppHelper->GetImageData(imgData, dataType, imageDataLength); void* buffer = data->GetScalarPointer(); if (buffer == NULL) { vtkErrorMacro(<< "No memory allocated for image data!"); return; } // DICOM stores the upper left pixel as the first pixel in an // image. VTK stores the lower left pixel as the first pixel in // an image. Need to flip the data. unsigned long rowLength; rowLength = this->DataIncrements[1]; unsigned char *b = (unsigned char *)buffer; unsigned char *iData = (unsigned char *)imgData; iData += (imageDataLength - rowLength); // beginning of last row for (int i=0; i < this->AppHelper->GetHeight(); ++i) { memcpy(b, iData, rowLength); b += rowLength; iData -= rowLength; } } else if (this->DICOMFileNames->size() > 0) { vtkDebugMacro( << "Multiple files (" << static_cast<int>(this->DICOMFileNames->size()) << ")"); this->Parser->ClearAllDICOMTagCallbacks(); this->AppHelper->Clear(); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->RegisterPixelDataCallback(this->Parser); void* buffer = data->GetScalarPointer(); if (buffer == NULL) { vtkErrorMacro(<< "No memory allocated for image data!"); return; } vtkstd::vector<vtkstd::string>::iterator fiter; int count = 0; int numFiles = static_cast<int>(this->DICOMFileNames->size()); for (fiter = this->DICOMFileNames->begin(); fiter != this->DICOMFileNames->end(); fiter++) { count++; vtkDebugMacro( << "File : " << (*fiter).c_str()); this->Parser->OpenFile((char*)(*fiter).c_str()); this->Parser->ReadHeader(); void* imgData = NULL; DICOMParser::VRTypes dataType; unsigned long imageDataLengthInBytes; this->AppHelper->GetImageData(imgData, dataType, imageDataLengthInBytes); // DICOM stores the upper left pixel as the first pixel in an // image. VTK stores the lower left pixel as the first pixel in // an image. Need to flip the data. unsigned long rowLength; rowLength = this->DataIncrements[1]; unsigned char *b = (unsigned char *)buffer; unsigned char *iData = (unsigned char *)imgData; iData += (imageDataLengthInBytes - rowLength); // beginning of last row for (int i=0; i < this->AppHelper->GetHeight(); ++i) { memcpy(b, iData, rowLength); b += rowLength; iData -= rowLength; } buffer = ((char*) buffer) + imageDataLengthInBytes; this->UpdateProgress(float(count)/float(numFiles)); int len = static_cast<int> (strlen((char*) (*fiter).c_str())); char* filename = new char[len+1]; strcpy(filename, (char*) (*fiter).c_str()); this->SetProgressText(filename); } } } void vtkDICOMImageReader::SetupOutputInformation(int num_slices) { int width = this->AppHelper->GetWidth(); int height = this->AppHelper->GetHeight(); int bit_depth = this->AppHelper->GetBitsAllocated(); int num_comp = this->AppHelper->GetNumberOfComponents(); this->DataExtent[0] = 0; this->DataExtent[1] = width - 1; this->DataExtent[2] = 0; this->DataExtent[3] = height - 1; this->DataExtent[4] = 0; this->DataExtent[5] = num_slices - 1; bool isFloat = this->AppHelper->RescaledImageDataIsFloat(); bool sign = this->AppHelper->RescaledImageDataIsSigned(); if (isFloat) { this->SetDataScalarTypeToFloat(); } else if (bit_depth <= 8) { this->SetDataScalarTypeToUnsignedChar(); } else { if (sign) { this->SetDataScalarTypeToShort(); } else { this->SetDataScalarTypeToUnsignedShort(); } } this->SetNumberOfScalarComponents(num_comp); this->GetPixelSpacing(); this->vtkImageReader2::ExecuteInformation(); } void vtkDICOMImageReader::SetDirectoryName(const char* dn) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting DirectoryName to " << (dn ? dn : "(null)") ); if ( this->DirectoryName == NULL && dn == NULL) { return; } if (this->FileName) { delete [] this->FileName; this->FileName = NULL; } if ( this->DirectoryName && dn && (!strcmp(this->DirectoryName,dn))) { return; } if (this->DirectoryName) { delete [] this->DirectoryName; } if (dn) { this->DirectoryName = new char[strlen(dn)+1]; strcpy(this->DirectoryName,dn); } else { this->DirectoryName = NULL; } this->Modified(); } double* vtkDICOMImageReader::GetPixelSpacing() { vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles; this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles, false); float* spacing = this->AppHelper->GetPixelSpacing(); this->DataSpacing[0] = spacing[0]; this->DataSpacing[1] = spacing[1]; if (sortedFiles.size() > 1) { vtkstd::pair<float, vtkstd::string> p1 = sortedFiles[0]; vtkstd::pair<float, vtkstd::string> p2 = sortedFiles[1]; this->DataSpacing[2] = fabs(p1.first - p2.first); } else { this->DataSpacing[2] = spacing[2]; } return this->DataSpacing; } int vtkDICOMImageReader::GetWidth() { return this->AppHelper->GetWidth(); } int vtkDICOMImageReader::GetHeight() { return this->AppHelper->GetHeight(); } float* vtkDICOMImageReader::GetImagePositionPatient() { return this->AppHelper->GetImagePositionPatient(); } int vtkDICOMImageReader::GetBitsAllocated() { return this->AppHelper->GetBitsAllocated(); } int vtkDICOMImageReader::GetPixelRepresentation() { return this->AppHelper->GetPixelRepresentation(); } int vtkDICOMImageReader::GetNumberOfComponents() { return this->AppHelper->GetNumberOfComponents(); } const char* vtkDICOMImageReader::GetTransferSyntaxUID() { vtkstd::string tmp = this->AppHelper->GetTransferSyntaxUID(); if (this->TransferSyntaxUID) { delete [] this->TransferSyntaxUID; } this->TransferSyntaxUID = new char[tmp.length()+1]; strcpy(this->TransferSyntaxUID, tmp.c_str()); this->TransferSyntaxUID[tmp.length()] = '\0'; return this->TransferSyntaxUID; } float vtkDICOMImageReader::GetRescaleSlope() { return this->AppHelper->GetRescaleSlope(); } float vtkDICOMImageReader::GetRescaleOffset() { return this->AppHelper->GetRescaleOffset(); } const char* vtkDICOMImageReader::GetPatientName() { vtkstd::string tmp = this->AppHelper->GetPatientName(); if (this->PatientName) { delete [] this->PatientName; } this->PatientName = new char[tmp.length()+1]; strcpy(this->PatientName, tmp.c_str()); this->PatientName[tmp.length()] = '\0'; return this->PatientName; } const char* vtkDICOMImageReader::GetStudyUID() { vtkstd::string tmp = this->AppHelper->GetStudyUID(); if (this->StudyUID) { delete [] this->StudyUID; } this->StudyUID = new char[tmp.length()+1]; strcpy(this->StudyUID, tmp.c_str()); this->StudyUID[tmp.length()] = '\0'; return this->StudyUID; } const char* vtkDICOMImageReader::GetStudyID() { vtkstd::string tmp = this->AppHelper->GetStudyID(); if (this->StudyID) { delete [] this->StudyID; } this->StudyID = new char[tmp.length()+1]; strcpy(this->StudyID, tmp.c_str()); this->StudyID[tmp.length()] = '\0'; return this->StudyID; } float vtkDICOMImageReader::GetGantryAngle() { return this->AppHelper->GetGantryAngle(); } <commit_msg>Remove warning about never used 'outPtr'<commit_after> /*========================================================================= Program: Visualization Toolkit Module: vtkDICOMImageReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "DICOMParser.h" #include "DICOMAppHelper.h" #include "vtkDICOMImageReader.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkDirectory.h" #include <vtkstd/vector> #include <vtkstd/string> vtkCxxRevisionMacro(vtkDICOMImageReader, "1.24"); vtkStandardNewMacro(vtkDICOMImageReader); class vtkDICOMImageReaderVector : public vtkstd::vector<vtkstd::string> { }; vtkDICOMImageReader::vtkDICOMImageReader() { this->Parser = new DICOMParser(); this->AppHelper = new DICOMAppHelper(); this->DirectoryName = NULL; this->PatientName = NULL; this->StudyUID = NULL; this->StudyID = NULL; this->TransferSyntaxUID = NULL; this->DICOMFileNames = new vtkDICOMImageReaderVector(); } vtkDICOMImageReader::~vtkDICOMImageReader() { delete this->Parser; delete this->AppHelper; delete this->DICOMFileNames; if (this->DirectoryName) { delete [] this->DirectoryName; } if (this->PatientName) { delete [] this->PatientName; } if (this->StudyUID) { delete [] this->StudyUID; } if (this->StudyID) { delete [] this->StudyID; } if (this->TransferSyntaxUID) { delete [] this->TransferSyntaxUID; } } void vtkDICOMImageReader::PrintSelf(ostream& os, vtkIndent indent) { this->vtkImageReader2::PrintSelf(os, indent); if (this->DirectoryName) { os << "DirectoryName : " << this->DirectoryName << "\n"; } else { os << "DirectoryName : (NULL)" << "\n"; } if (this->FileName) { os << "FileName : " << this->FileName << "\n"; } else { os << "FileName : (NULL)" << "\n"; } } int vtkDICOMImageReader::CanReadFile(const char* fname) { bool canOpen = this->Parser->OpenFile((char*) fname); if (canOpen == false) { vtkErrorMacro("DICOMParser couldn't open : " << fname); return 0; } bool canRead = this->Parser->IsDICOMFile(); if (canRead == true) { return 1; } else { return 0; } } void vtkDICOMImageReader::ExecuteInformation() { if (this->FileName == NULL && this->DirectoryName == NULL) { return; } if (this->FileName) { this->DICOMFileNames->clear(); this->AppHelper->Clear(); this->Parser->ClearAllDICOMTagCallbacks(); this->Parser->OpenFile(this->FileName); this->AppHelper->RegisterCallbacks(this->Parser); this->Parser->ReadHeader(); this->SetupOutputInformation(1); } else if (this->DirectoryName) { vtkDirectory* dir = vtkDirectory::New(); int opened = dir->Open(this->DirectoryName); if (!opened) { vtkErrorMacro("Couldn't open " << this->DirectoryName); dir->Delete(); return; } int numFiles = dir->GetNumberOfFiles(); vtkDebugMacro( << "There are " << numFiles << " files in the directory."); this->DICOMFileNames->clear(); this->AppHelper->Clear(); for (int i = 0; i < numFiles; i++) { if (strcmp(dir->GetFile(i), ".") == 0 || strcmp(dir->GetFile(i), "..") == 0) { continue; } vtkstd::string fileString = this->DirectoryName; fileString += "/"; fileString += dir->GetFile(i); int val = this->CanReadFile(fileString.c_str()); if (val == 1) { vtkDebugMacro( << "Adding " << fileString.c_str() << " to DICOMFileNames."); this->DICOMFileNames->push_back(fileString); } else { vtkDebugMacro( << fileString.c_str() << " - DICOMParser CanReadFile returned : " << val); } } vtkstd::vector<vtkstd::string>::iterator iter; for (iter = this->DICOMFileNames->begin(); iter != this->DICOMFileNames->end(); iter++) { char* fn = (char*) (*iter).c_str(); vtkDebugMacro( << "Trying : " << fn); bool couldOpen = this->Parser->OpenFile(fn); if (!couldOpen) { dir->Delete(); return; } // this->Parser->ClearAllDICOMTagCallbacks(); this->AppHelper->RegisterCallbacks(this->Parser); this->Parser->ReadHeader(); vtkDebugMacro( << "File name : " << fn ); vtkDebugMacro( << "Slice number : " << this->AppHelper->GetSliceNumber()); } vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles; this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles, false); this->SetupOutputInformation(static_cast<int>(sortedFiles.size())); //this->AppHelper->OutputSeries(); if (sortedFiles.size() > 0) { this->DICOMFileNames->clear(); vtkstd::vector<vtkstd::pair<float, vtkstd::string> >::iterator siter; for (siter = sortedFiles.begin(); siter != sortedFiles.end(); siter++) { vtkDebugMacro(<< "Sorted filename : " << (*siter).second.c_str()); vtkDebugMacro(<< "Adding file " << (*siter).second.c_str() << " at slice : " << (*siter).first); this->DICOMFileNames->push_back((*siter).second); } } else { vtkErrorMacro( << "Couldn't get sorted files. Slices may be in wrong order!"); } dir->Delete(); } } void vtkDICOMImageReader::ExecuteData(vtkDataObject *output) { vtkImageData *data = this->AllocateOutputData(output); if (!this->FileName && this->DICOMFileNames->size() == 0) { vtkErrorMacro( << "Either a filename was not specified or the specified directory does not contain any DICOM images."); return; } data->GetPointData()->GetScalars()->SetName("DICOMImage"); this->ComputeDataIncrements(); if (this->FileName) { vtkDebugMacro( << "Single file : " << this->FileName); this->Parser->ClearAllDICOMTagCallbacks(); this->Parser->OpenFile(this->FileName); this->AppHelper->Clear(); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->RegisterPixelDataCallback(this->Parser); this->Parser->ReadHeader(); void* imgData = NULL; DICOMParser::VRTypes dataType; unsigned long imageDataLength; this->AppHelper->GetImageData(imgData, dataType, imageDataLength); void* buffer = data->GetScalarPointer(); if (buffer == NULL) { vtkErrorMacro(<< "No memory allocated for image data!"); return; } // DICOM stores the upper left pixel as the first pixel in an // image. VTK stores the lower left pixel as the first pixel in // an image. Need to flip the data. unsigned long rowLength; rowLength = this->DataIncrements[1]; unsigned char *b = (unsigned char *)buffer; unsigned char *iData = (unsigned char *)imgData; iData += (imageDataLength - rowLength); // beginning of last row for (int i=0; i < this->AppHelper->GetHeight(); ++i) { memcpy(b, iData, rowLength); b += rowLength; iData -= rowLength; } } else if (this->DICOMFileNames->size() > 0) { vtkDebugMacro( << "Multiple files (" << static_cast<int>(this->DICOMFileNames->size()) << ")"); this->Parser->ClearAllDICOMTagCallbacks(); this->AppHelper->Clear(); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->RegisterPixelDataCallback(this->Parser); void* buffer = data->GetScalarPointer(); if (buffer == NULL) { vtkErrorMacro(<< "No memory allocated for image data!"); return; } vtkstd::vector<vtkstd::string>::iterator fiter; int count = 0; int numFiles = static_cast<int>(this->DICOMFileNames->size()); for (fiter = this->DICOMFileNames->begin(); fiter != this->DICOMFileNames->end(); fiter++) { count++; vtkDebugMacro( << "File : " << (*fiter).c_str()); this->Parser->OpenFile((char*)(*fiter).c_str()); this->Parser->ReadHeader(); void* imgData = NULL; DICOMParser::VRTypes dataType; unsigned long imageDataLengthInBytes; this->AppHelper->GetImageData(imgData, dataType, imageDataLengthInBytes); // DICOM stores the upper left pixel as the first pixel in an // image. VTK stores the lower left pixel as the first pixel in // an image. Need to flip the data. unsigned long rowLength; rowLength = this->DataIncrements[1]; unsigned char *b = (unsigned char *)buffer; unsigned char *iData = (unsigned char *)imgData; iData += (imageDataLengthInBytes - rowLength); // beginning of last row for (int i=0; i < this->AppHelper->GetHeight(); ++i) { memcpy(b, iData, rowLength); b += rowLength; iData -= rowLength; } buffer = ((char*) buffer) + imageDataLengthInBytes; this->UpdateProgress(float(count)/float(numFiles)); int len = static_cast<int> (strlen((char*) (*fiter).c_str())); char* filename = new char[len+1]; strcpy(filename, (char*) (*fiter).c_str()); this->SetProgressText(filename); } } } void vtkDICOMImageReader::SetupOutputInformation(int num_slices) { int width = this->AppHelper->GetWidth(); int height = this->AppHelper->GetHeight(); int bit_depth = this->AppHelper->GetBitsAllocated(); int num_comp = this->AppHelper->GetNumberOfComponents(); this->DataExtent[0] = 0; this->DataExtent[1] = width - 1; this->DataExtent[2] = 0; this->DataExtent[3] = height - 1; this->DataExtent[4] = 0; this->DataExtent[5] = num_slices - 1; bool isFloat = this->AppHelper->RescaledImageDataIsFloat(); bool sign = this->AppHelper->RescaledImageDataIsSigned(); if (isFloat) { this->SetDataScalarTypeToFloat(); } else if (bit_depth <= 8) { this->SetDataScalarTypeToUnsignedChar(); } else { if (sign) { this->SetDataScalarTypeToShort(); } else { this->SetDataScalarTypeToUnsignedShort(); } } this->SetNumberOfScalarComponents(num_comp); this->GetPixelSpacing(); this->vtkImageReader2::ExecuteInformation(); } void vtkDICOMImageReader::SetDirectoryName(const char* dn) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting DirectoryName to " << (dn ? dn : "(null)") ); if ( this->DirectoryName == NULL && dn == NULL) { return; } if (this->FileName) { delete [] this->FileName; this->FileName = NULL; } if ( this->DirectoryName && dn && (!strcmp(this->DirectoryName,dn))) { return; } if (this->DirectoryName) { delete [] this->DirectoryName; } if (dn) { this->DirectoryName = new char[strlen(dn)+1]; strcpy(this->DirectoryName,dn); } else { this->DirectoryName = NULL; } this->Modified(); } double* vtkDICOMImageReader::GetPixelSpacing() { vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles; this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles, false); float* spacing = this->AppHelper->GetPixelSpacing(); this->DataSpacing[0] = spacing[0]; this->DataSpacing[1] = spacing[1]; if (sortedFiles.size() > 1) { vtkstd::pair<float, vtkstd::string> p1 = sortedFiles[0]; vtkstd::pair<float, vtkstd::string> p2 = sortedFiles[1]; this->DataSpacing[2] = fabs(p1.first - p2.first); } else { this->DataSpacing[2] = spacing[2]; } return this->DataSpacing; } int vtkDICOMImageReader::GetWidth() { return this->AppHelper->GetWidth(); } int vtkDICOMImageReader::GetHeight() { return this->AppHelper->GetHeight(); } float* vtkDICOMImageReader::GetImagePositionPatient() { return this->AppHelper->GetImagePositionPatient(); } int vtkDICOMImageReader::GetBitsAllocated() { return this->AppHelper->GetBitsAllocated(); } int vtkDICOMImageReader::GetPixelRepresentation() { return this->AppHelper->GetPixelRepresentation(); } int vtkDICOMImageReader::GetNumberOfComponents() { return this->AppHelper->GetNumberOfComponents(); } const char* vtkDICOMImageReader::GetTransferSyntaxUID() { vtkstd::string tmp = this->AppHelper->GetTransferSyntaxUID(); if (this->TransferSyntaxUID) { delete [] this->TransferSyntaxUID; } this->TransferSyntaxUID = new char[tmp.length()+1]; strcpy(this->TransferSyntaxUID, tmp.c_str()); this->TransferSyntaxUID[tmp.length()] = '\0'; return this->TransferSyntaxUID; } float vtkDICOMImageReader::GetRescaleSlope() { return this->AppHelper->GetRescaleSlope(); } float vtkDICOMImageReader::GetRescaleOffset() { return this->AppHelper->GetRescaleOffset(); } const char* vtkDICOMImageReader::GetPatientName() { vtkstd::string tmp = this->AppHelper->GetPatientName(); if (this->PatientName) { delete [] this->PatientName; } this->PatientName = new char[tmp.length()+1]; strcpy(this->PatientName, tmp.c_str()); this->PatientName[tmp.length()] = '\0'; return this->PatientName; } const char* vtkDICOMImageReader::GetStudyUID() { vtkstd::string tmp = this->AppHelper->GetStudyUID(); if (this->StudyUID) { delete [] this->StudyUID; } this->StudyUID = new char[tmp.length()+1]; strcpy(this->StudyUID, tmp.c_str()); this->StudyUID[tmp.length()] = '\0'; return this->StudyUID; } const char* vtkDICOMImageReader::GetStudyID() { vtkstd::string tmp = this->AppHelper->GetStudyID(); if (this->StudyID) { delete [] this->StudyID; } this->StudyID = new char[tmp.length()+1]; strcpy(this->StudyID, tmp.c_str()); this->StudyID[tmp.length()] = '\0'; return this->StudyID; } float vtkDICOMImageReader::GetGantryAngle() { return this->AppHelper->GetGantryAngle(); } <|endoftext|>
<commit_before> #include <string> #include <vector> #include <list> #include <iostream> #include <fstream> #include <sstream> #include <thread> #include <chrono> /* Input File Displaying int viewLength = 20 int padding = std::min(5, (viewSize - note.size()) / 2); int startLine = std::max(0, currentLine - padding); int endline = startLine + ((noteLength > viewLength) ? noteLength : viewLength ); endline = std::min( lines.size(), currentLine + noteLength + padding ); std::cout << (endline - startLine) << "\n"; Headers headerPosition, headerLength getNextNoteLine h - Goto next Header or skip Header Auto Sorting - Term Frequency - Inverse Document Frequency Filter out common words, count instances of term and sort them sort them find term occurance by dividing by total length For documents, find average for all other documents and divide the average by the document's total - / total weight = tf / length normalized = (weight - minWeight) / (maxWeight - minWeight) tf / averageTF */ typedef std::string String; #define ESK "\033[" #define CON_MOVETO(r,c) ESK #r ";" #c "H" /* namespace Console { moveTo(x,y) move(n, direction) erase color style scroll } namespace Cli { } */ #include <unistd.h> void getConsolePosition(int& row, int& col) { return; // Goto last Column, query Cursor position std::cout << ESK "999C"; // TODO Read from stdin without needing the user to press enter // Maybe write out a newline? can stdout be tied to stdin?] //return; String input; char dummy; std::cout << ESK "6n\n"; char nl[] = "\n\n"; write(STDIN_FILENO, &nl, sizeof(nl)); std::this_thread::sleep_for( std::chrono::milliseconds(100) ); getline(std::cin, input); std::stringstream ss( input.substr(2,32) ); ss >> row >> dummy >> col; //Erase row std::cout << " " << ESK "2K"; } void mainLoop(); void getNextNoteLine(); void getNoteLength(); void display(); void removeCurrentNote(); void parseLine(String line); bool parseSetCommand(String line); bool loadInputFile(); bool loadState(); bool saveState(); void consoleTest(); String inputFilename; int currentLine = 0; int noteLength = 1; std::vector<String> lines; String configFilename; std::fstream configfile; const int indexes = 9; String outputFilenames[indexes]; std::ofstream outputFiles[indexes]; bool doQuit = false; std::list<String> log; int logLength = 3; int intputViewLength = 20; int endCol = 0; int getIndentLevel(String line) { int indent = 0; for (char c: line) { if (std::isspace(c)) { ++indent; } else { break; } } return indent; } bool isBlankLine(int line) { if ( lines[line].empty() ) { return true; } for(char ch : lines[line]) { if ( !std::isspace(ch) ) { return false; } } return true; } bool isSymbolLine(int line) { if ( lines[line].empty() ) { return false; } for(char ch : lines[line]) { switch(ch) { case'<':case'>':case'(':case')':case'[':case']':case'{':case'}': case';':case':':case'\'':case'"':case'-':case'_':case'=':case'+': case'!':case'@':case'#':case'$':case'%':case'^':case'&':case'*': case'`':case'~':case'/':case'?':case',':case'.':case'\\':case'|': break; default: return false; } } return true; } void getNextNoteLine() { currentLine += noteLength; while (currentLine < (int)lines.size()) { if (isBlankLine(currentLine)) { ++currentLine; } else { break; } } } bool enterSubNote() { if ( noteLength <= 1 ) { return false; } ++currentLine; //getNextNoteLine(); getNoteLength(); return true; /*int indent = getIndentLevel(lines[currentLine]); int line = currentLine + 1; while (line < currentLine + noteLength) { if ( indent < getIndentLevel(lines[line]) ) { ++line; } else if ( isSymbolLine(line) ) { ++line; } else { break; } } */ } void getPrevNoteLine() { //int indent = getIndentLevel( lines[currentLine] ); while (currentLine >= 0) { --currentLine; } } void getNoteLength() { if (currentLine >= (int)lines.size()) { noteLength = 0; return; } //if (isHeaderLine(currentLine)) { //Read until 2 blank lines } int indent = getIndentLevel(lines[currentLine]); int line = currentLine + 1; while (line < (int)lines.size()) { if ( indent < getIndentLevel(lines[line]) ) { ++line; } else if ( isSymbolLine(line) && (indent == getIndentLevel(lines[line]))) { ++line; } else { break; } } noteLength = line - currentLine; } void display() { std::cout << "Commands:\n"; std::cout << " set 1-" << indexes << " destination_file\n"; std::cout << " 1-" << indexes << " - Send Note to Destination File\n"; //std::cout << " a - Auto Sort Note\n"; //std::cout << " u - Undo previous operation\n"; std::cout << " s - Skip Note\n"; std::cout << " p - Previous Note\n"; //std::cout << " e - Edit Note\n"; //std::cout << " TAB - Enter into inner sub-note" //std::cout << " n - Insert Newline into previous Destination output file\n"; std::cout << " d - Delete Note\n"; std::cout << " save - Save output files and configuration\n"; std::cout << " q - Quit the Program\n"; // Display Output file destinations std::cout << "\n"; for ( int i = 0; i < indexes; ++i ) { std::cout << (i+1) << " " << outputFilenames[i] << " "; } std::cout << "\n"; // Display Log /*if ( !log.empty() ) { std::cout << "----------\n"; for (auto elem : log) { std::cout << elem << "\n"; } if ((int)log.size() >= logLength) { log.pop_front(); } //std::cout << "----------\n"; } */ // Display Input file section std::cout << ESK "36;1m" "##############################\n" ESK "0m"; int startLine = std::max(0, currentLine - 5); int endline = startLine + ((noteLength > intputViewLength) ? noteLength : intputViewLength ); endline = std::min( endline, (int)lines.size()-1 ); //std::cout << (endline - startLine) << "\n"; for ( int i = startLine; i < endline; ++i ) { if (i >= (int)lines.size()) { break; } if ((i >= currentLine) && (i < noteLength + currentLine)) { int row, col = 0; getConsolePosition(row,col); std::cout << ESK "7m " << lines[i]; //for ( int i = col; i < endCol; ++i ) { std::cout << " "; } std::cout << ESK "0m" "\n"; } else { std::cout << " " << lines[i] << "\n"; } } for ( int i = 0; i < 20-(endline-startLine); ++i ) { std::cout << "\n"; } std::cout << ESK "36;1m" "##############################\n" ESK "0m"; } void removeCurrentNote() { lines.erase( lines.begin() + currentLine, lines.begin() + currentLine + noteLength ); } void parseLine(String str) { if (str.empty()) { return; } if ( parseSetCommand( str ) ) { return; } std::stringstream ss; ss.str(str); ss >> str; if ( (str[0] >= '1') && (str[0] <= '9') ) { int dest = std::stoi(str); if ( (dest <= 0) || (dest > 9) ) { return; } for ( int i = currentLine; i < currentLine + noteLength; ++i ) { outputFiles[dest-1] << lines[i] << "\n"; } removeCurrentNote(); return; } if ( str == "save" ) { saveState(); } else if ( str == "s" ) { if (currentLine != (int)lines.size()) { log.push_back( String("Skipped ") + std::to_string(currentLine) ); } int before = currentLine; getNextNoteLine(); if ((before != currentLine) && (currentLine == (int)lines.size())) { log.push_back("Reached End of Input"); } return; } //if ( str == "e" ) { // log.push_back( String("Modified ") + std::to_string(currentLine) ); // editCurrentNote(); //} if ( str == "d" ) { log.push_back( String("Deleted ") + std::to_string(currentLine) ); removeCurrentNote(); } if ( str == "p" ) { log.push_back("Previous"); --currentLine; //getPrevNoteLine(); } if ( str == "q" ) { doQuit = true; return; } if ( str == "\t" ) { enterSubNote(); } ss.str(""); ss.clear(); } bool parseSetCommand(String str) { std::stringstream ss; ss.str(str); ss >> str; if (str.empty()) { return false; } if ( str == "set") { int n = 0; ss >> n; if ( (n < 1) || (n > indexes) ) { std::cout << n << "\n"; std::cout << "Number must be within range [1-" << indexes << "]\n"; return false; } n -= 1; String filename; str = ss.str(); filename = str.substr( (int)ss.tellg() + 1, str.size() - ss.tellg() - 1 ); if ( outputFiles[n].is_open() ) { std::cout << "Closing " << outputFilenames[n] << "\n"; outputFiles[n].close(); } if ( !filename.empty() ) { std::cout << "Opening " << filename << "\n"; outputFiles[n].open( filename, std::ofstream::out | std::ofstream::app ); outputFilenames[n] = filename; } log.push_back( String("set ") + std::to_string(n) + String(" to ") + filename ); return true; } return false; } void mainLoop() { while (!doQuit) { std::cout << "\033[2J"; std::cout << CON_MOVETO(1,1); getNoteLength(); display(); std::cout << "> "; String line; getline(std::cin, line); parseLine( line ); } std::cout << "Would you like to save? [y/N]: "; String input; getline(std::cin, input); if ( input == "y" ) { saveState(); } std::cout << "Quitting...\n"; } bool saveState() { if (configfile.is_open()) { configfile.close(); } configfile.open( configFilename, std::fstream::out | std::fstream::trunc ); std::cout << "Saving configuration to '" << configFilename << "'\n"; for ( int i = 0; i < indexes; ++i ) { if ( !outputFilenames[i].empty() ) { std::cout << " set " << (i+1) << " " << outputFilenames[i] << "\n"; configfile << "set " << (i+1) << " " << outputFilenames[i] << "\n"; } } // Save Input File configfile.close(); std::fstream inputFile(inputFilename, std::fstream::out | std::fstream::trunc); std::cout << "Saving '" << inputFilename << "' modifications\n"; for (String& line : lines) { inputFile << line << "\n"; } // Save Output Files for ( int i = 0; i < indexes; ++i ) { outputFiles[i].close(); outputFiles[i].open( outputFilenames[i], std::ofstream::out | std::ofstream::app ); } return true; } bool loadState() { if (configfile.is_open()) { configfile.close(); } configfile.open(configFilename, std::ifstream::in); String line; while ( !configfile.eof() ) { getline( configfile, line ); parseSetCommand( line ); } return true; } bool loadInputFile() { std::ifstream ifile(inputFilename); if (!ifile.is_open()) { return false; } String line; while (ifile.good()) { getline(ifile, line); lines.push_back(line); } ifile.close(); return true; } /* loadState() loadInputFile() */ int main(int argc, char* argv[] ) { //getConsolePosition(row, endCol); if (argc <= 1) { std::cout << "USAGE: " << String(argv[0]) << " input_file [config_file].\n"; return 1; } std::cout << "\033[?47h"; if (argc > 2) { configFilename = argv[2]; loadState(); } inputFilename = argv[1]; loadInputFile(); log.clear(); mainLoop(); for ( int i = 0; i < indexes; ++i ) { outputFiles[i].close(); } std::this_thread::sleep_for( std::chrono::milliseconds(1000) ); std::cout << "\033[?47l"; return 0; } <commit_msg>Removed experimental getConsolePosition()<commit_after> #include <string> #include <vector> #include <list> #include <iostream> #include <fstream> #include <sstream> #include <thread> #include <chrono> /* Input File Displaying int viewLength = 20 int padding = std::min(5, (viewSize - note.size()) / 2); int startLine = std::max(0, currentLine - padding); int endline = startLine + ((noteLength > viewLength) ? noteLength : viewLength ); endline = std::min( lines.size(), currentLine + noteLength + padding ); std::cout << (endline - startLine) << "\n"; Headers headerPosition, headerLength getNextNoteLine h - Goto next Header or skip Header Auto Sorting - Term Frequency - Inverse Document Frequency Filter out common words, count instances of term and sort them sort them find term occurance by dividing by total length For documents, find average for all other documents and divide the average by the document's total - / total weight = tf / length normalized = (weight - minWeight) / (maxWeight - minWeight) tf / averageTF */ typedef std::string String; #define ESK "\033[" #define CON_MOVETO(r,c) ESK #r ";" #c "H" void mainLoop(); void getNextNoteLine(); void getNoteLength(); void display(); void removeCurrentNote(); void parseLine(String line); bool parseSetCommand(String line); bool loadInputFile(); bool loadState(); bool saveState(); void consoleTest(); String inputFilename; int currentLine = 0; int noteLength = 1; std::vector<String> lines; String configFilename; std::fstream configfile; const int indexes = 9; String outputFilenames[indexes]; std::ofstream outputFiles[indexes]; bool doQuit = false; std::list<String> log; int logLength = 3; int intputViewLength = 20; int endCol = 0; int getIndentLevel(String line) { int indent = 0; for (char c: line) { if (std::isspace(c)) { ++indent; } else { break; } } return indent; } bool isBlankLine(int line) { if ( lines[line].empty() ) { return true; } for(char ch : lines[line]) { if ( !std::isspace(ch) ) { return false; } } return true; } bool isSymbolLine(int line) { if ( lines[line].empty() ) { return false; } for(char ch : lines[line]) { switch(ch) { case'<':case'>':case'(':case')':case'[':case']':case'{':case'}': case';':case':':case'\'':case'"':case'-':case'_':case'=':case'+': case'!':case'@':case'#':case'$':case'%':case'^':case'&':case'*': case'`':case'~':case'/':case'?':case',':case'.':case'\\':case'|': break; default: return false; } } return true; } void getNextNoteLine() { currentLine += noteLength; while (currentLine < (int)lines.size()) { if (isBlankLine(currentLine)) { ++currentLine; } else { break; } } } bool enterSubNote() { if ( noteLength <= 1 ) { return false; } ++currentLine; //getNextNoteLine(); getNoteLength(); return true; /*int indent = getIndentLevel(lines[currentLine]); int line = currentLine + 1; while (line < currentLine + noteLength) { if ( indent < getIndentLevel(lines[line]) ) { ++line; } else if ( isSymbolLine(line) ) { ++line; } else { break; } } */ } void getPrevNoteLine() { //int indent = getIndentLevel( lines[currentLine] ); while (currentLine >= 0) { --currentLine; } } void getNoteLength() { if (currentLine >= (int)lines.size()) { noteLength = 0; return; } //if (isHeaderLine(currentLine)) { //Read until 2 blank lines } int indent = getIndentLevel(lines[currentLine]); int line = currentLine + 1; while (line < (int)lines.size()) { if ( indent < getIndentLevel(lines[line]) ) { ++line; } else if ( isSymbolLine(line) && (indent == getIndentLevel(lines[line]))) { ++line; } else { break; } } noteLength = line - currentLine; } void display() { std::cout << "Commands:\n"; std::cout << " set 1-" << indexes << " destination_file\n"; std::cout << " 1-" << indexes << " - Send Note to Destination File\n"; //std::cout << " a - Auto Sort Note\n"; //std::cout << " u - Undo previous operation\n"; std::cout << " s - Skip Note\n"; std::cout << " p - Previous Note\n"; //std::cout << " e - Edit Note\n"; //std::cout << " TAB - Enter into inner sub-note" //std::cout << " n - Insert Newline into previous Destination output file\n"; std::cout << " d - Delete Note\n"; std::cout << " save - Save output files and configuration\n"; std::cout << " q - Quit the Program\n"; // Display Output file destinations std::cout << "\n"; for ( int i = 0; i < indexes; ++i ) { std::cout << (i+1) << " " << outputFilenames[i] << " "; } std::cout << "\n"; // Display Log /*if ( !log.empty() ) { std::cout << "----------\n"; for (auto elem : log) { std::cout << elem << "\n"; } if ((int)log.size() >= logLength) { log.pop_front(); } //std::cout << "----------\n"; } */ // Display Input file section std::cout << ESK "36;1m" "##############################\n" ESK "0m"; int startLine = std::max(0, currentLine - 5); int endline = startLine + ((noteLength > intputViewLength) ? noteLength : intputViewLength ); endline = std::min( endline, (int)lines.size()-1 ); //std::cout << (endline - startLine) << "\n"; for ( int i = startLine; i < endline; ++i ) { if (i >= (int)lines.size()) { break; } if ((i >= currentLine) && (i < noteLength + currentLine)) { std::cout << ESK "7m " << lines[i]; std::cout << ESK "0m" "\n"; } else { std::cout << " " << lines[i] << "\n"; } } for ( int i = 0; i < 20-(endline-startLine); ++i ) { std::cout << "\n"; } std::cout << ESK "36;1m" "##############################\n" ESK "0m"; } void removeCurrentNote() { lines.erase( lines.begin() + currentLine, lines.begin() + currentLine + noteLength ); } void parseLine(String str) { if (str.empty()) { return; } if ( parseSetCommand( str ) ) { return; } std::stringstream ss; ss.str(str); ss >> str; if ( (str[0] >= '1') && (str[0] <= '9') ) { int dest = std::stoi(str); if ( (dest <= 0) || (dest > 9) ) { return; } for ( int i = currentLine; i < currentLine + noteLength; ++i ) { outputFiles[dest-1] << lines[i] << "\n"; } removeCurrentNote(); return; } if ( str == "save" ) { saveState(); } else if ( str == "s" ) { if (currentLine != (int)lines.size()) { log.push_back( String("Skipped ") + std::to_string(currentLine) ); } int before = currentLine; getNextNoteLine(); if ((before != currentLine) && (currentLine == (int)lines.size())) { log.push_back("Reached End of Input"); } return; } //if ( str == "e" ) { // log.push_back( String("Modified ") + std::to_string(currentLine) ); // editCurrentNote(); //} if ( str == "d" ) { log.push_back( String("Deleted ") + std::to_string(currentLine) ); removeCurrentNote(); } if ( str == "p" ) { log.push_back("Previous"); --currentLine; //getPrevNoteLine(); } if ( str == "q" ) { doQuit = true; return; } if ( str == "\t" ) { enterSubNote(); } ss.str(""); ss.clear(); } bool parseSetCommand(String str) { std::stringstream ss; ss.str(str); ss >> str; if (str.empty()) { return false; } if ( str == "set") { int n = 0; ss >> n; if ( (n < 1) || (n > indexes) ) { std::cout << n << "\n"; std::cout << "Number must be within range [1-" << indexes << "]\n"; return false; } n -= 1; String filename; str = ss.str(); filename = str.substr( (int)ss.tellg() + 1, str.size() - ss.tellg() - 1 ); if ( outputFiles[n].is_open() ) { std::cout << "Closing " << outputFilenames[n] << "\n"; outputFiles[n].close(); } if ( !filename.empty() ) { std::cout << "Opening " << filename << "\n"; outputFiles[n].open( filename, std::ofstream::out | std::ofstream::app ); outputFilenames[n] = filename; } log.push_back( String("set ") + std::to_string(n) + String(" to ") + filename ); return true; } return false; } void mainLoop() { while (!doQuit) { std::cout << "\033[2J"; std::cout << CON_MOVETO(1,1); getNoteLength(); display(); std::cout << "> "; String line; getline(std::cin, line); parseLine( line ); } std::cout << "Would you like to save? [y/N]: "; String input; getline(std::cin, input); if ( input == "y" ) { saveState(); } std::cout << "Quitting...\n"; } bool saveState() { if (configfile.is_open()) { configfile.close(); } configfile.open( configFilename, std::fstream::out | std::fstream::trunc ); std::cout << "Saving configuration to '" << configFilename << "'\n"; for ( int i = 0; i < indexes; ++i ) { if ( !outputFilenames[i].empty() ) { std::cout << " set " << (i+1) << " " << outputFilenames[i] << "\n"; configfile << "set " << (i+1) << " " << outputFilenames[i] << "\n"; } } // Save Input File configfile.close(); std::fstream inputFile(inputFilename, std::fstream::out | std::fstream::trunc); std::cout << "Saving '" << inputFilename << "' modifications\n"; for (String& line : lines) { inputFile << line << "\n"; } // Save Output Files for ( int i = 0; i < indexes; ++i ) { outputFiles[i].close(); outputFiles[i].open( outputFilenames[i], std::ofstream::out | std::ofstream::app ); } return true; } bool loadState() { if (configfile.is_open()) { configfile.close(); } configfile.open(configFilename, std::ifstream::in); String line; while ( !configfile.eof() ) { getline( configfile, line ); parseSetCommand( line ); } return true; } bool loadInputFile() { std::ifstream ifile(inputFilename); if (!ifile.is_open()) { return false; } String line; while (ifile.good()) { getline(ifile, line); lines.push_back(line); } ifile.close(); return true; } /* loadState() loadInputFile() */ int main(int argc, char* argv[] ) { if (argc <= 1) { std::cout << "USAGE: " << String(argv[0]) << " input_file [config_file].\n"; return 1; } std::cout << "\033[?47h"; if (argc > 2) { configFilename = argv[2]; loadState(); } inputFilename = argv[1]; loadInputFile(); log.clear(); mainLoop(); for ( int i = 0; i < indexes; ++i ) { outputFiles[i].close(); } std::this_thread::sleep_for( std::chrono::milliseconds(1000) ); std::cout << "\033[?47l"; return 0; } <|endoftext|>
<commit_before>/* HardwareSerial.cpp - esp8266 UART support Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 31 March 2015 by Markus Sattler (rewrite the code for UART0 + UART1 support in ESP8266) Modified 25 April 2015 by Thomas Flayols (add configuration different from 8N1 in ESP8266) Modified 3 May 2015 by Hristo Gochkov (change register access methods) */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Arduino.h" #include "HardwareSerial.h" #include "Esp.h" HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _rx_size(256) {} void HardwareSerial::begin(unsigned long baud, SerialConfig config, SerialMode mode, uint8_t tx_pin) { end(); _uart = uart_init(_uart_nr, baud, (int) config, (int) mode, tx_pin, _rx_size); #if defined(DEBUG_ESP_PORT) && !defined(NDEBUG) if (this == &DEBUG_ESP_PORT) { setDebugOutput(true); println(); println(ESP.getFullVersion()); } #endif } void HardwareSerial::end() { if(uart_get_debug() == _uart_nr) { uart_set_debug(UART_NO); } uart_uninit(_uart); _uart = NULL; } size_t HardwareSerial::setRxBufferSize(size_t size){ if(_uart) { _rx_size = uart_resize_rx_buffer(_uart, size); } else { _rx_size = size; } return _rx_size; } void HardwareSerial::setDebugOutput(bool en) { if(!_uart) { return; } if(en) { if(uart_tx_enabled(_uart)) { uart_set_debug(_uart_nr); } else { uart_set_debug(UART_NO); } } else { // disable debug for this interface if(uart_get_debug() == _uart_nr) { uart_set_debug(UART_NO); } } } int HardwareSerial::available(void) { int result = static_cast<int>(uart_rx_available(_uart)); if (!result) { optimistic_yield(10000); } return result; } void HardwareSerial::flush() { if(!_uart || !uart_tx_enabled(_uart)) { return; } uart_wait_tx_empty(_uart); //Workaround for a bug in serial not actually being finished yet //Wait for 8 data bits, 1 parity and 2 stop bits, just in case delayMicroseconds(11000000 / uart_get_baudrate(_uart) + 1); } #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL) HardwareSerial Serial(UART0); #endif #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL1) HardwareSerial Serial1(UART1); #endif <commit_msg>Allow other ESP debug port class types (#4611)<commit_after>/* HardwareSerial.cpp - esp8266 UART support Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 31 March 2015 by Markus Sattler (rewrite the code for UART0 + UART1 support in ESP8266) Modified 25 April 2015 by Thomas Flayols (add configuration different from 8N1 in ESP8266) Modified 3 May 2015 by Hristo Gochkov (change register access methods) */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Arduino.h" #include "HardwareSerial.h" #include "Esp.h" HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _rx_size(256) {} void HardwareSerial::begin(unsigned long baud, SerialConfig config, SerialMode mode, uint8_t tx_pin) { end(); _uart = uart_init(_uart_nr, baud, (int) config, (int) mode, tx_pin, _rx_size); #if defined(DEBUG_ESP_PORT) && !defined(NDEBUG) if (static_cast<void*>(this) == static_cast<void*>(&DEBUG_ESP_PORT)) { setDebugOutput(true); println(); println(ESP.getFullVersion()); } #endif } void HardwareSerial::end() { if(uart_get_debug() == _uart_nr) { uart_set_debug(UART_NO); } uart_uninit(_uart); _uart = NULL; } size_t HardwareSerial::setRxBufferSize(size_t size){ if(_uart) { _rx_size = uart_resize_rx_buffer(_uart, size); } else { _rx_size = size; } return _rx_size; } void HardwareSerial::setDebugOutput(bool en) { if(!_uart) { return; } if(en) { if(uart_tx_enabled(_uart)) { uart_set_debug(_uart_nr); } else { uart_set_debug(UART_NO); } } else { // disable debug for this interface if(uart_get_debug() == _uart_nr) { uart_set_debug(UART_NO); } } } int HardwareSerial::available(void) { int result = static_cast<int>(uart_rx_available(_uart)); if (!result) { optimistic_yield(10000); } return result; } void HardwareSerial::flush() { if(!_uart || !uart_tx_enabled(_uart)) { return; } uart_wait_tx_empty(_uart); //Workaround for a bug in serial not actually being finished yet //Wait for 8 data bits, 1 parity and 2 stop bits, just in case delayMicroseconds(11000000 / uart_get_baudrate(_uart) + 1); } #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL) HardwareSerial Serial(UART0); #endif #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL1) HardwareSerial Serial1(UART1); #endif <|endoftext|>
<commit_before>/** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief Auxiliary stdlib specializations. */ #pragma once #include <Onsang/config.hpp> #include <memory> #include <string> #include <vector> #include <deque> #include <map> #include <unordered_map> #include <unordered_set> namespace Onsang { namespace aux { /** @addtogroup etc @{ */ /** @addtogroup aux @{ */ /** @c std::shared_ptr<T>. */ template< typename T > using shared_ptr = std::shared_ptr<T>; /** @c std::weak_ptr<T>. */ template< typename T > using weak_ptr = std::weak_ptr<T>; /** @c std::unique_ptr<T>. */ template< typename T, typename Deleter = std::default_delete<T> > using unique_ptr = std::unique_ptr<T>; /** Alias for @c std::make_shared(). */ using std::make_shared; /** Alias for @c std::owner_less<T>. */ using std::owner_less; /** Alias for @c std::enable_shared_from_this<T>. */ using std::enable_shared_from_this; /** @c std::basic_string<CharT, Traits>. */ template< typename CharT, class Traits = std::char_traits<CharT> > using basic_string = std::basic_string< CharT, Traits, ONSANG_AUX_ALLOCATOR<CharT> >; /** @c std::vector<T>. */ template< typename T > using vector = std::vector< T, ONSANG_AUX_ALLOCATOR<T> >; /** @c std::deque<T>. */ template< typename T > using deque = std::deque< T, ONSANG_AUX_ALLOCATOR<T> >; /** @c std::unordered_map<Key, T, Hash, KeyEqual>. */ template< typename Key, typename T, class Compare = std::less<Key> > using map = std::map< Key, T, Compare, ONSANG_AUX_ALLOCATOR<std::pair<Key const, T> > >; /** @c std::unordered_map<Key, T, Hash, KeyEqual>. */ template< typename Key, typename T, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key> > using unordered_map = std::unordered_map< Key, T, Hash, KeyEqual, ONSANG_AUX_ALLOCATOR<std::pair<Key const, T> > >; /** @c std::unordered_set<Key, Hash, KeyEqual>. */ template< typename Key, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key> > using unordered_set = std::unordered_set< Key, Hash, KeyEqual, ONSANG_AUX_ALLOCATOR<Key> >; /** @} */ // end of doc-group aux /** @} */ // end of doc-group etc } // namespace aux } // namespace Onsang <commit_msg>aux: changed spec for template type parameters from typename to class.<commit_after>/** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief Auxiliary stdlib specializations. */ #pragma once #include <Onsang/config.hpp> #include <memory> #include <string> #include <vector> #include <deque> #include <map> #include <unordered_map> #include <unordered_set> namespace Onsang { namespace aux { /** @addtogroup etc @{ */ /** @addtogroup aux @{ */ /** @c std::shared_ptr<T>. */ template< class T > using shared_ptr = std::shared_ptr<T>; /** @c std::weak_ptr<T>. */ template< class T > using weak_ptr = std::weak_ptr<T>; /** @c std::unique_ptr<T>. */ template< class T, class Deleter = std::default_delete<T> > using unique_ptr = std::unique_ptr<T>; /** Alias for @c std::make_shared(). */ using std::make_shared; /** Alias for @c std::owner_less<T>. */ using std::owner_less; /** Alias for @c std::enable_shared_from_this<T>. */ using std::enable_shared_from_this; /** @c std::basic_string<CharT, Traits>. */ template< class CharT, class Traits = std::char_traits<CharT> > using basic_string = std::basic_string< CharT, Traits, ONSANG_AUX_ALLOCATOR<CharT> >; /** @c std::vector<T>. */ template< class T > using vector = std::vector< T, ONSANG_AUX_ALLOCATOR<T> >; /** @c std::deque<T>. */ template< class T > using deque = std::deque< T, ONSANG_AUX_ALLOCATOR<T> >; /** @c std::unordered_map<Key, T, Hash, KeyEqual>. */ template< class Key, class T, class Compare = std::less<Key> > using map = std::map< Key, T, Compare, ONSANG_AUX_ALLOCATOR<std::pair<Key const, T> > >; /** @c std::unordered_map<Key, T, Hash, KeyEqual>. */ template< class Key, class T, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key> > using unordered_map = std::unordered_map< Key, T, Hash, KeyEqual, ONSANG_AUX_ALLOCATOR<std::pair<Key const, T> > >; /** @c std::unordered_set<Key, Hash, KeyEqual>. */ template< class Key, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key> > using unordered_set = std::unordered_set< Key, Hash, KeyEqual, ONSANG_AUX_ALLOCATOR<Key> >; /** @} */ // end of doc-group aux /** @} */ // end of doc-group etc } // namespace aux } // namespace Onsang <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "Material.h" class MaterialTest : public ::testing::Test { protected: CompMap test_comp; string test_mat_unit; string test_rec_name; double test_size; Basis test_type; Material* test_mat; virtual void SetUp(){ Iso u235 = 92235; Atoms one = 1.0; test_comp[u235]=one; test_mat_unit = "test_mat_unit"; test_rec_name = "test_rec_name"; test_size = 10.0; test_type = atomBased; test_mat = new Material(test_comp, test_mat_unit, test_rec_name, test_size, test_type); //Material* test_mat = new Material(); }; }; TEST_F(MaterialTest, ManualConstructor) { EXPECT_EQ(test_mat->getUnits(), "test_mat_unit"); //EXPECT_EQ(MaterialTest::test_mat->getTotAtoms(),0); } <commit_msg>improves MaterialTest::ManualConstructor test to do slightly more interesting things. <commit_after>#include <gtest/gtest.h> #include "Material.h" class MaterialTest : public ::testing::Test { protected: Iso u235; Atoms one; CompMap test_comp; string test_mat_unit; string test_rec_name; double test_size; Basis test_type; Material* test_mat; virtual void SetUp(){ u235 = 92235; Atoms one = 1.0; test_comp[u235]=one; test_mat_unit = "test_mat_unit"; test_rec_name = "test_rec_name"; test_size = 10.0; test_type = atomBased; test_mat = new Material(test_comp, test_mat_unit, test_rec_name, test_size, test_type); }; }; TEST_F(MaterialTest, ManualConstructor) { EXPECT_EQ( test_mat->getUnits(), "test_mat_unit" ); EXPECT_EQ( test_mat->getTotAtoms(), 10 ); ASSERT_NEAR( test_mat->getTotMass(), 2.35, 0.001); // 10mol U235 ~= 2.35kg ASSERT_NEAR( test_mat->getMassComp(u235), 1, 0.001); // normalized ASSERT_NEAR( test_mat->getComp(u235), 1, 0.001); // normalized } <|endoftext|>
<commit_before><commit_msg><commit_after><|endoftext|>