text
stringlengths
54
60.6k
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "component_score_json_writer_process.h" #include <vistk/pipeline/datum.h> #include <vistk/pipeline/process_exception.h> #include <vistk/scoring/scoring_result.h> #include <vistk/scoring/scoring_statistics.h> #include <vistk/scoring/statistics.h> #include <vistk/utilities/path.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/foreach.hpp> #include <boost/make_shared.hpp> #include <fstream> #include <string> /** * \file component_score_json_writer_process.cxx * * \brief Implementation of a process which writes out component scores to a file in JSON. */ namespace vistk { class component_score_json_writer_process::priv { public: typedef port_t tag_t; typedef std::vector<tag_t> tags_t; typedef std::map<tag_t, bool> tag_stat_map_t; priv(); priv(path_t const& output_path, tags_t const& tags_); ~priv(); path_t const path; std::ofstream fout; tags_t tags; tag_stat_map_t tag_stats; static config::key_t const config_path; static port_t const port_score_prefix; static port_t const port_stats_prefix; }; config::key_t const component_score_json_writer_process::priv::config_path = "path"; process::port_t const component_score_json_writer_process::priv::port_score_prefix = process::port_t("score/"); process::port_t const component_score_json_writer_process::priv::port_stats_prefix = process::port_t("stats/"); component_score_json_writer_process ::component_score_json_writer_process(config_t const& config) : process(config) , d(new priv) { declare_configuration_key(priv::config_path, boost::make_shared<conf_info>( config::value_t(), config::description_t("The path to output scores to."))); } component_score_json_writer_process ::~component_score_json_writer_process() { } void component_score_json_writer_process ::_configure() { // Configure the process. { path_t const path = config_value<path_t>(priv::config_path); d.reset(new priv(path, d->tags)); } path_t::string_type const path = d->path.native(); if (path.empty()) { static std::string const reason = "The path given was empty"; config::value_t const value = config::value_t(path.begin(), path.end()); throw invalid_configuration_value_exception(name(), priv::config_path, value, reason); } d->fout.open(path.c_str()); if (!d->fout.good()) { std::string const file_path(path.begin(), path.end()); std::string const reason = "Failed to open the path: " + file_path; throw invalid_configuration_exception(name(), reason); } process::_configure(); } void component_score_json_writer_process ::_init() { if (!d->tags.size()) { static std::string const reason = "There must be at least one component score to write"; throw invalid_configuration_exception(name(), reason); } BOOST_FOREACH (priv::tag_t const& tag, d->tags) { port_t const port_stat = priv::port_stats_prefix + tag; d->tag_stats[tag] = false; if (input_port_edge(port_stat)) { d->tag_stats[tag] = true; } } process::_init(); } void component_score_json_writer_process ::_step() { #define JSON_KEY(key) \ ("\"" key "\": ") #define JSON_ATTR(key, value) \ JSON_KEY(key) << value #define JSON_SEP \ "," << std::endl #define JSON_OBJECT_BEGIN \ "{" << std::endl #define JSON_OBJECT_END \ "}" d->fout << JSON_OBJECT_BEGIN; /// \todo Name runs. d->fout << JSON_ATTR("name", "\"(unnamed)\""); d->fout << JSON_SEP; /// \todo Insert date. d->fout << JSON_ATTR("date", "\"\""); d->fout << JSON_SEP; /// \todo Get git hash. d->fout << JSON_ATTR("hash", "\"\""); d->fout << JSON_SEP; d->fout << JSON_ATTR("config", "{}"); d->fout << JSON_SEP; d->fout << JSON_KEY("results") << JSON_OBJECT_BEGIN; bool first = true; BOOST_FOREACH (priv::tag_t const& tag, d->tags) { if (!first) { d->fout << JSON_SEP; } first = false; d->fout << JSON_KEY(+ tag +); d->fout << JSON_OBJECT_BEGIN; scoring_result_t const result = grab_from_port_as<scoring_result_t>(priv::port_score_prefix + tag); d->fout << JSON_ATTR("true-positive", result->true_positives); d->fout << JSON_SEP; d->fout << JSON_ATTR("false-positive", result->false_positives); d->fout << JSON_SEP; d->fout << JSON_ATTR("total-true", result->total_trues); d->fout << JSON_SEP; d->fout << JSON_ATTR("total-possible", result->total_possible); d->fout << JSON_SEP; d->fout << JSON_ATTR("percent-detection", result->percent_detection()); d->fout << JSON_SEP; d->fout << JSON_ATTR("precision", result->precision()); d->fout << JSON_SEP; d->fout << JSON_ATTR("specificity", result->specificity()); if (d->tag_stats[tag]) { port_t const port_stats = priv::port_stats_prefix + tag; d->fout << JSON_SEP; #define OUTPUT_STATISTICS(key, stats) \ do \ { \ d->fout << JSON_KEY(key); \ d->fout << JSON_OBJECT_BEGIN; \ d->fout << JSON_ATTR("count", stats->count()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("min", stats->minimum()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("max", stats->maximum()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("mean", stats->mean()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("median", stats->median()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("standard-deviation", stats->standard_deviation()); \ d->fout << JSON_OBJECT_END; \ } while (false) scoring_statistics_t const sc_stats = grab_from_port_as<scoring_statistics_t>(port_stats); statistics_t const pd_stats = sc_stats->percent_detection_stats(); statistics_t const precision_stats = sc_stats->precision_stats(); statistics_t const specificity_stats = sc_stats->specificity_stats(); d->fout << JSON_KEY("statistics"); d->fout << JSON_OBJECT_BEGIN; OUTPUT_STATISTICS("percent-detection", pd_stats); d->fout << JSON_SEP; OUTPUT_STATISTICS("precision", precision_stats); d->fout << JSON_SEP; OUTPUT_STATISTICS("specificity", specificity_stats); d->fout << JSON_OBJECT_END; #undef OUTPUT_STATISTICS } d->fout << JSON_OBJECT_END; } d->fout << std::endl; d->fout << JSON_OBJECT_END; d->fout << std::endl; d->fout << JSON_OBJECT_END; d->fout << std::endl; #undef JSON_OBJECT_END #undef JSON_OBJECT_BEGIN #undef JSON_SEP #undef JSON_ATTR #undef JSON_KEY process::_step(); } process::port_info_t component_score_json_writer_process ::_input_port_info(port_t const& port) { if (boost::starts_with(port, priv::port_score_prefix)) { priv::tag_t const tag = port.substr(priv::port_score_prefix.size()); priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag); if (i == d->tags.end()) { port_t const port_score = priv::port_score_prefix + tag; port_t const port_stats = priv::port_stats_prefix + tag; d->tags.push_back(tag); port_flags_t required; required.insert(flag_required); declare_input_port(port_score, boost::make_shared<port_info>( "score", required, port_description_t("The \'" + tag + "\' score component."))); declare_input_port(port_stats, boost::make_shared<port_info>( "statistics/score", port_flags_t(), port_description_t("The \'" + tag + "\' score statistics component."))); } } return process::_input_port_info(port); } component_score_json_writer_process::priv ::priv() { } component_score_json_writer_process::priv ::priv(path_t const& output_path, tags_t const& tags_) : path(output_path) , tags(tags_) { } component_score_json_writer_process::priv ::~priv() { } } <commit_msg>Factor out port name combining<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "component_score_json_writer_process.h" #include <vistk/pipeline/datum.h> #include <vistk/pipeline/process_exception.h> #include <vistk/scoring/scoring_result.h> #include <vistk/scoring/scoring_statistics.h> #include <vistk/scoring/statistics.h> #include <vistk/utilities/path.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/foreach.hpp> #include <boost/make_shared.hpp> #include <fstream> #include <string> /** * \file component_score_json_writer_process.cxx * * \brief Implementation of a process which writes out component scores to a file in JSON. */ namespace vistk { class component_score_json_writer_process::priv { public: typedef port_t tag_t; typedef std::vector<tag_t> tags_t; typedef std::map<tag_t, bool> tag_stat_map_t; priv(); priv(path_t const& output_path, tags_t const& tags_); ~priv(); path_t const path; std::ofstream fout; tags_t tags; tag_stat_map_t tag_stats; static config::key_t const config_path; static port_t const port_score_prefix; static port_t const port_stats_prefix; }; config::key_t const component_score_json_writer_process::priv::config_path = "path"; process::port_t const component_score_json_writer_process::priv::port_score_prefix = process::port_t("score/"); process::port_t const component_score_json_writer_process::priv::port_stats_prefix = process::port_t("stats/"); component_score_json_writer_process ::component_score_json_writer_process(config_t const& config) : process(config) , d(new priv) { declare_configuration_key(priv::config_path, boost::make_shared<conf_info>( config::value_t(), config::description_t("The path to output scores to."))); } component_score_json_writer_process ::~component_score_json_writer_process() { } void component_score_json_writer_process ::_configure() { // Configure the process. { path_t const path = config_value<path_t>(priv::config_path); d.reset(new priv(path, d->tags)); } path_t::string_type const path = d->path.native(); if (path.empty()) { static std::string const reason = "The path given was empty"; config::value_t const value = config::value_t(path.begin(), path.end()); throw invalid_configuration_value_exception(name(), priv::config_path, value, reason); } d->fout.open(path.c_str()); if (!d->fout.good()) { std::string const file_path(path.begin(), path.end()); std::string const reason = "Failed to open the path: " + file_path; throw invalid_configuration_exception(name(), reason); } process::_configure(); } void component_score_json_writer_process ::_init() { if (!d->tags.size()) { static std::string const reason = "There must be at least one component score to write"; throw invalid_configuration_exception(name(), reason); } BOOST_FOREACH (priv::tag_t const& tag, d->tags) { port_t const port_stat = priv::port_stats_prefix + tag; d->tag_stats[tag] = false; if (input_port_edge(port_stat)) { d->tag_stats[tag] = true; } } process::_init(); } void component_score_json_writer_process ::_step() { #define JSON_KEY(key) \ ("\"" key "\": ") #define JSON_ATTR(key, value) \ JSON_KEY(key) << value #define JSON_SEP \ "," << std::endl #define JSON_OBJECT_BEGIN \ "{" << std::endl #define JSON_OBJECT_END \ "}" d->fout << JSON_OBJECT_BEGIN; /// \todo Name runs. d->fout << JSON_ATTR("name", "\"(unnamed)\""); d->fout << JSON_SEP; /// \todo Insert date. d->fout << JSON_ATTR("date", "\"\""); d->fout << JSON_SEP; /// \todo Get git hash. d->fout << JSON_ATTR("hash", "\"\""); d->fout << JSON_SEP; d->fout << JSON_ATTR("config", "{}"); d->fout << JSON_SEP; d->fout << JSON_KEY("results") << JSON_OBJECT_BEGIN; bool first = true; BOOST_FOREACH (priv::tag_t const& tag, d->tags) { port_t const port_score = priv::port_score_prefix + tag; if (!first) { d->fout << JSON_SEP; } first = false; d->fout << JSON_KEY(+ tag +); d->fout << JSON_OBJECT_BEGIN; scoring_result_t const result = grab_from_port_as<scoring_result_t>(port_score); d->fout << JSON_ATTR("true-positive", result->true_positives); d->fout << JSON_SEP; d->fout << JSON_ATTR("false-positive", result->false_positives); d->fout << JSON_SEP; d->fout << JSON_ATTR("total-true", result->total_trues); d->fout << JSON_SEP; d->fout << JSON_ATTR("total-possible", result->total_possible); d->fout << JSON_SEP; d->fout << JSON_ATTR("percent-detection", result->percent_detection()); d->fout << JSON_SEP; d->fout << JSON_ATTR("precision", result->precision()); d->fout << JSON_SEP; d->fout << JSON_ATTR("specificity", result->specificity()); if (d->tag_stats[tag]) { port_t const port_stats = priv::port_stats_prefix + tag; d->fout << JSON_SEP; #define OUTPUT_STATISTICS(key, stats) \ do \ { \ d->fout << JSON_KEY(key); \ d->fout << JSON_OBJECT_BEGIN; \ d->fout << JSON_ATTR("count", stats->count()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("min", stats->minimum()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("max", stats->maximum()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("mean", stats->mean()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("median", stats->median()); \ d->fout << JSON_SEP; \ d->fout << JSON_ATTR("standard-deviation", stats->standard_deviation()); \ d->fout << JSON_OBJECT_END; \ } while (false) scoring_statistics_t const sc_stats = grab_from_port_as<scoring_statistics_t>(port_stats); statistics_t const pd_stats = sc_stats->percent_detection_stats(); statistics_t const precision_stats = sc_stats->precision_stats(); statistics_t const specificity_stats = sc_stats->specificity_stats(); d->fout << JSON_KEY("statistics"); d->fout << JSON_OBJECT_BEGIN; OUTPUT_STATISTICS("percent-detection", pd_stats); d->fout << JSON_SEP; OUTPUT_STATISTICS("precision", precision_stats); d->fout << JSON_SEP; OUTPUT_STATISTICS("specificity", specificity_stats); d->fout << JSON_OBJECT_END; #undef OUTPUT_STATISTICS } d->fout << JSON_OBJECT_END; } d->fout << std::endl; d->fout << JSON_OBJECT_END; d->fout << std::endl; d->fout << JSON_OBJECT_END; d->fout << std::endl; #undef JSON_OBJECT_END #undef JSON_OBJECT_BEGIN #undef JSON_SEP #undef JSON_ATTR #undef JSON_KEY process::_step(); } process::port_info_t component_score_json_writer_process ::_input_port_info(port_t const& port) { if (boost::starts_with(port, priv::port_score_prefix)) { priv::tag_t const tag = port.substr(priv::port_score_prefix.size()); priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag); if (i == d->tags.end()) { port_t const port_score = priv::port_score_prefix + tag; port_t const port_stats = priv::port_stats_prefix + tag; d->tags.push_back(tag); port_flags_t required; required.insert(flag_required); declare_input_port(port_score, boost::make_shared<port_info>( "score", required, port_description_t("The \'" + tag + "\' score component."))); declare_input_port(port_stats, boost::make_shared<port_info>( "statistics/score", port_flags_t(), port_description_t("The \'" + tag + "\' score statistics component."))); } } return process::_input_port_info(port); } component_score_json_writer_process::priv ::priv() { } component_score_json_writer_process::priv ::priv(path_t const& output_path, tags_t const& tags_) : path(output_path) , tags(tags_) { } component_score_json_writer_process::priv ::~priv() { } } <|endoftext|>
<commit_before>#include <stan/math/error_handling/matrix/check_cov_matrix.hpp> #include <gtest/gtest.h> <commit_msg>moving check_cov_matrix tests out of math/matrix_error_handling_test.cpp<commit_after>#include <stan/math/error_handling/matrix/check_cov_matrix.hpp> #include <gtest/gtest.h> TEST(MathErrorHandlingMatrix, checkCovMatrix) { Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y; double result; y.resize(3,3); y << 2, -1, 0, -1, 2, -1, 0, -1, 2; EXPECT_TRUE(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y", &result)); EXPECT_TRUE(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y")); y << 1, 2, 3, 2, 1, 2, 3, 2, 1; EXPECT_THROW(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y", &result), std::domain_error); EXPECT_THROW(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y"), std::domain_error); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "ICUBridgeCollationCompareFunctor.hpp" #include "ICUBridge.hpp" #include <PlatformSupport/DOMStringHelper.hpp> #include <unicode/coll.h> const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor ICUBridgeCollationCompareFunctor::s_defaultFunctor; ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() : m_isValid(false), m_collator(0) { UErrorCode theStatus = U_ZERO_ERROR; m_collator = Collator::createInstance(theStatus); if (theStatus == U_ZERO_ERROR || theStatus == U_USING_DEFAULT_ERROR) { m_isValid = true; } } ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor() { delete m_collator; } static UChar dummy = 0; int ICUBridgeCollationCompareFunctor::operator()( const XalanDOMChar* theLHS, const XalanDOMChar* theRHS) const { if (isValid() == false) { return s_defaultFunctor(theLHS, theRHS); } else { assert(m_collator != 0); return m_collator->compare( theLHS, length(theLHS), theRHS, length(theRHS)); } } <commit_msg>Cast to (wchar_t*) for AIX.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "ICUBridgeCollationCompareFunctor.hpp" #include "ICUBridge.hpp" #include <PlatformSupport/DOMStringHelper.hpp> #include <unicode/coll.h> const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor ICUBridgeCollationCompareFunctor::s_defaultFunctor; ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() : m_isValid(false), m_collator(0) { UErrorCode theStatus = U_ZERO_ERROR; m_collator = Collator::createInstance(theStatus); if (theStatus == U_ZERO_ERROR || theStatus == U_USING_DEFAULT_ERROR) { m_isValid = true; } } ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor() { delete m_collator; } static UChar dummy = 0; int ICUBridgeCollationCompareFunctor::operator()( const XalanDOMChar* theLHS, const XalanDOMChar* theRHS) const { if (isValid() == false) { return s_defaultFunctor(theLHS, theRHS); } else { assert(m_collator != 0); return m_collator->compare( (wchar_t*)theLHS, length(theLHS), (wchar_t*)theRHS, length(theRHS)); } } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <iostream> #include <math.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include "pong.hpp" #include "util.hpp" typedef struct { float x; float y; float vx; float vy; } ball; typedef struct { int x; int y; int width; int height; int score; int speed; } player; float calc_angle(float y1, float y2, int height) { float rely = y1 + height/2 - y2; rely /= height/2.0; // Normalise return rely * MAX_ANGLE; } int main(int argc, char* argv[]) { std::cout << "Starting SDL Application..." << std::endl; SDL_Event e; SDL_Renderer *ren = nullptr; SDL_Window *win = nullptr; Initialise(&ren,&win); int board_width; int board_height; SDL_Texture *squareTex = IMG_LoadTexture(ren, "../img/pong_board.png"); SDL_QueryTexture(squareTex, NULL, NULL, &board_width, &board_height); SDL_Color whiteColor = {255, 255, 255}; SDL_Surface *fpsCounter; // Define Players player p1; player p2; // Define Ball ball b; b.x = SCREEN_WIDTH / 2; b.y = SCREEN_HEIGHT / 2; b.vx = (rand() % 2 == 0)? BALL_INIT_SPEED : -1 * BALL_INIT_SPEED; b.vy = -0.5f; p1.score = p2.score = 0; p1.width = p2.width = board_width; p1.height = p2.height = 150; p1.speed = p2.speed = 10; p1.x = board_width/2 + 10; p2.x = SCREEN_WIDTH - p2.width - 10 - p2.width/2; p1.y = SCREEN_HEIGHT/2 - p1.height/2; p2.y = SCREEN_HEIGHT/2 - p2.height/2; std::cout << "Starting Game Loop" << std::endl; uint prevTime = SDL_GetTicks(); bool quit = false; int frames = 0; float fps; char buffer[512]; const Uint8 *keystates = SDL_GetKeyboardState(NULL); while(!quit) { // FPS Calculation ++frames; uint currTime = SDL_GetTicks(); float elapsed = (currTime - prevTime); if(elapsed > 100) { fps = round(frames / (elapsed / 1000.0)); frames = 0; prevTime = currTime; } while(SDL_PollEvent(&e)) { if(e.type == SDL_QUIT) quit = true; if(e.type == SDL_KEYDOWN) { switch(e.key.keysym.scancode) { case SDL_SCANCODE_ESCAPE: quit = true; break; } } } // Player Movement if(keystates[SDL_SCANCODE_UP]) p1.y -= p1.speed; if(keystates[SDL_SCANCODE_DOWN]) p1.y += p1.speed; // Basic AI if(b.y < p2.y + p2.height/2) { p2.y -= p2.speed; } if(b.y > p2.y + p2.height/2) { p2.y += p2.speed; } // Update Ball coordinates b.x += b.vx; b.y += b.vy; // Boundary Collision if(b.y < 0) { b.y = 0; b.vy *= -1; } if(b.y >= SCREEN_HEIGHT) { b.y = SCREEN_HEIGHT - 1; b.vy *= -1; } if(b.x < 0) { p2.score += 1; b.x = p1.x + p1.width; b.y = p1.y + p1.height/2; b.vx = BALL_INIT_SPEED; } if(b.x >= SCREEN_WIDTH) { p1.score += 1; b.x = p2.x; b.y = p2.y + p2.height/2; b.vx = -1 * BALL_INIT_SPEED; } if(p1.y < 0) p1.y = 0; if(p1.y + p1.height > SCREEN_HEIGHT) p1.y = SCREEN_HEIGHT - p1.height; if(p2.y < 0) p2.y = 0; if(p2.y + p2.height > SCREEN_HEIGHT) p2.y = SCREEN_HEIGHT - p2.height; // Player Collision if(b.x > p1.x && b.x < p1.x + p1.width && b.y > p1.y && b.y < p1.y + p1.height) { b.x = p1.x + p1.width; float angle = calc_angle(p1.y, b.y, p1.height); b.vx = BALL_INIT_SPEED * cos(angle); b.vy = BALL_INIT_SPEED * -1 * sin(angle); } if(b.x > p2.x && b.x < p2.x + p2.width && b.y > p2.y && b.y < p2.y + p2.height) { b.x = p2.x; float angle = calc_angle(p2.y, b.y, p2.height); b.vx = -1 * BALL_INIT_SPEED * cos(angle); b.vy = BALL_INIT_SPEED * -1 * sin(angle); } SDL_RenderClear(ren); renderTexture(squareTex, ren, p1.x, p1.y, p1.width, p1.height); renderTexture(squareTex, ren, p2.x, p2.y, p1.width, p1.height); // Draw the center line renderTexture(squareTex, ren, SCREEN_WIDTH/2 - CENTER_WIDTH/2, 0, CENTER_WIDTH, SCREEN_HEIGHT); // Draw the Ball renderTexture(squareTex, ren, b.x - BALL_WIDTH/2, b.y - BALL_HEIGHT/2, BALL_WIDTH, BALL_HEIGHT); // Display the score sprintf(buffer, "%d", p1.score); SDL_Texture *p1score = renderText(buffer, "../fonts/sample.ttf", whiteColor, 40, ren); sprintf(buffer, "%d", p2.score); SDL_Texture *p2score = renderText(buffer, "../fonts/sample.ttf", whiteColor, 40, ren); int width; SDL_QueryTexture(p1score, NULL, NULL, &width, NULL); renderTexture(p1score, ren, SCREEN_WIDTH/2 - width - 10, 10); renderTexture(p2score, ren, SCREEN_WIDTH/2 + 10, 10); SDL_DestroyTexture(p1score); SDL_DestroyTexture(p2score); // Extremely ineffecient way of displaying text sprintf(buffer, "%.0f", fps); SDL_Texture *fpsCounter = renderText(buffer, "../fonts/sample.ttf", whiteColor, 20, ren); renderTexture(fpsCounter, ren, SCREEN_WIDTH - 20, 0); SDL_DestroyTexture(fpsCounter); SDL_RenderPresent(ren); } SDL_DestroyTexture(squareTex); Cleanup(&ren, &win); return 0; } void Initialise(SDL_Renderer **ren, SDL_Window **win) { if(SDL_Init(SDL_INIT_EVERYTHING) == -1) sdl_bomb("Failed to Initialise SDL"); *win = SDL_CreateWindow( "SDL Pong by Michael Aquilina", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if(*win == nullptr) sdl_bomb("Failed to create SDL Window"); *ren = SDL_CreateRenderer(*win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(*ren == nullptr) sdl_bomb("Failed to create SDL Renderer"); const int flags = IMG_INIT_PNG | IMG_INIT_JPG; if(IMG_Init(flags) !=flags) sdl_bomb("Failed to load the Image loading extensions"); if(TTF_Init() != 0) sdl_bomb("Failed to load TTF extension"); } void Cleanup(SDL_Renderer **ren, SDL_Window **win) { SDL_DestroyRenderer(*ren); SDL_DestroyWindow(*win); TTF_Quit(); IMG_Quit(); SDL_Quit(); } <commit_msg>Improve change of y direction on collision<commit_after>#include <stdio.h> #include <stdlib.h> #include <iostream> #include <math.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include "pong.hpp" #include "util.hpp" typedef struct { float x; float y; float vx; float vy; } ball; typedef struct { int x; int y; int width; int height; int score; int speed; } player; float calc_angle(float y1, float y2, int height) { float rely = y1 + height/2 - y2; rely /= height/2.0; // Normalise return rely * MAX_ANGLE; } int main(int argc, char* argv[]) { std::cout << "Starting SDL Application..." << std::endl; SDL_Event e; SDL_Renderer *ren = nullptr; SDL_Window *win = nullptr; Initialise(&ren,&win); int board_width; int board_height; SDL_Texture *squareTex = IMG_LoadTexture(ren, "../img/pong_board.png"); SDL_QueryTexture(squareTex, NULL, NULL, &board_width, &board_height); SDL_Color whiteColor = {255, 255, 255}; SDL_Surface *fpsCounter; // Define Players player p1; player p2; // Define Ball ball b; b.x = SCREEN_WIDTH / 2; b.y = SCREEN_HEIGHT / 2; b.vx = (rand() % 2 == 0)? BALL_INIT_SPEED : -1 * BALL_INIT_SPEED; b.vy = -0.5f; p1.score = p2.score = 0; p1.width = p2.width = board_width; p1.height = p2.height = 150; p1.speed = p2.speed = 10; p1.x = board_width/2 + 10; p2.x = SCREEN_WIDTH - p2.width - 10 - p2.width/2; p1.y = SCREEN_HEIGHT/2 - p1.height/2; p2.y = SCREEN_HEIGHT/2 - p2.height/2; std::cout << "Starting Game Loop" << std::endl; uint prevTime = SDL_GetTicks(); bool quit = false; int frames = 0; float fps; char buffer[512]; const Uint8 *keystates = SDL_GetKeyboardState(NULL); while(!quit) { // FPS Calculation ++frames; uint currTime = SDL_GetTicks(); float elapsed = (currTime - prevTime); if(elapsed > 100) { fps = round(frames / (elapsed / 1000.0)); frames = 0; prevTime = currTime; } while(SDL_PollEvent(&e)) { if(e.type == SDL_QUIT) quit = true; if(e.type == SDL_KEYDOWN) { switch(e.key.keysym.scancode) { case SDL_SCANCODE_ESCAPE: quit = true; break; } } } // Player Movement if(keystates[SDL_SCANCODE_UP]) p1.y -= p1.speed; if(keystates[SDL_SCANCODE_DOWN]) p1.y += p1.speed; // Basic AI if(b.y < p2.y + p2.height/2) { p2.y -= p2.speed; } if(b.y > p2.y + p2.height/2) { p2.y += p2.speed; } // Update Ball coordinates b.x += b.vx; b.y += b.vy; // Boundary Collision if(b.y < 0) { b.y = 0; b.vy *= -1; } if(b.y >= SCREEN_HEIGHT) { b.y = SCREEN_HEIGHT - 1; b.vy *= -1; } if(b.x < 0) { p2.score += 1; b.x = p1.x + p1.width; b.y = p1.y + p1.height/2; b.vx = BALL_INIT_SPEED; } if(b.x >= SCREEN_WIDTH) { p1.score += 1; b.x = p2.x; b.y = p2.y + p2.height/2; b.vx = -1 * BALL_INIT_SPEED; } if(p1.y < 0) p1.y = 0; if(p1.y + p1.height > SCREEN_HEIGHT) p1.y = SCREEN_HEIGHT - p1.height; if(p2.y < 0) p2.y = 0; if(p2.y + p2.height > SCREEN_HEIGHT) p2.y = SCREEN_HEIGHT - p2.height; // Player Collision if(b.x > p1.x && b.x < p1.x + p1.width && b.y > p1.y && b.y < p1.y + p1.height) { b.x = p1.x + p1.width; float angle = calc_angle(p1.y, b.y, p1.height); b.vx = BALL_INIT_SPEED * cos(angle); b.vy = ((b.vy>0)? -1 : 1) * BALL_INIT_SPEED * sin(angle); } if(b.x > p2.x && b.x < p2.x + p2.width && b.y > p2.y && b.y < p2.y + p2.height) { b.x = p2.x; float angle = calc_angle(p2.y, b.y, p2.height); b.vx = -1 * BALL_INIT_SPEED * cos(angle); b.vy = ((b.vy>0)? -1 : 1) * BALL_INIT_SPEED * sin(angle); } SDL_RenderClear(ren); renderTexture(squareTex, ren, p1.x, p1.y, p1.width, p1.height); renderTexture(squareTex, ren, p2.x, p2.y, p1.width, p1.height); // Draw the center line renderTexture(squareTex, ren, SCREEN_WIDTH/2 - CENTER_WIDTH/2, 0, CENTER_WIDTH, SCREEN_HEIGHT); // Draw the Ball renderTexture(squareTex, ren, b.x - BALL_WIDTH/2, b.y - BALL_HEIGHT/2, BALL_WIDTH, BALL_HEIGHT); // Display the score sprintf(buffer, "%d", p1.score); SDL_Texture *p1score = renderText(buffer, "../fonts/sample.ttf", whiteColor, 40, ren); sprintf(buffer, "%d", p2.score); SDL_Texture *p2score = renderText(buffer, "../fonts/sample.ttf", whiteColor, 40, ren); int width; SDL_QueryTexture(p1score, NULL, NULL, &width, NULL); renderTexture(p1score, ren, SCREEN_WIDTH/2 - width - 10, 10); renderTexture(p2score, ren, SCREEN_WIDTH/2 + 10, 10); SDL_DestroyTexture(p1score); SDL_DestroyTexture(p2score); // Extremely ineffecient way of displaying text sprintf(buffer, "%.0f", fps); SDL_Texture *fpsCounter = renderText(buffer, "../fonts/sample.ttf", whiteColor, 20, ren); renderTexture(fpsCounter, ren, SCREEN_WIDTH - 20, 0); SDL_DestroyTexture(fpsCounter); SDL_RenderPresent(ren); } SDL_DestroyTexture(squareTex); Cleanup(&ren, &win); return 0; } void Initialise(SDL_Renderer **ren, SDL_Window **win) { if(SDL_Init(SDL_INIT_EVERYTHING) == -1) sdl_bomb("Failed to Initialise SDL"); *win = SDL_CreateWindow( "SDL Pong by Michael Aquilina", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if(*win == nullptr) sdl_bomb("Failed to create SDL Window"); *ren = SDL_CreateRenderer(*win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(*ren == nullptr) sdl_bomb("Failed to create SDL Renderer"); const int flags = IMG_INIT_PNG | IMG_INIT_JPG; if(IMG_Init(flags) !=flags) sdl_bomb("Failed to load the Image loading extensions"); if(TTF_Init() != 0) sdl_bomb("Failed to load TTF extension"); } void Cleanup(SDL_Renderer **ren, SDL_Window **win) { SDL_DestroyRenderer(*ren); SDL_DestroyWindow(*win); TTF_Quit(); IMG_Quit(); SDL_Quit(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <cstdio> #include "libmv/logging/logging.h" #include "libmv/simple_pipeline/modal_solver.h" #include "libmv/simple_pipeline/rigid_registration.h" #ifdef _MSC_VER # define snprintf _snprintf #endif namespace libmv { static void ProjectMarkerOnSphere(Marker &marker, Vec3 &X) { X(0) = marker.x; X(1) = marker.y; X(2) = 1.0; X *= 5.0 / X.norm(); } static void ModalSolverLogProress(ProgressUpdateCallback *update_callback, double progress) { if (update_callback) { char message[256]; snprintf(message, sizeof(message), "Solving progress %d%%", (int)(progress * 100)); update_callback->invoke(progress, message); } } void ModalSolver(Tracks &tracks, EuclideanReconstruction *reconstruction, ProgressUpdateCallback *update_callback) { int max_image = tracks.MaxImage(); int max_track = tracks.MaxTrack(); LG << "Max image: " << max_image; LG << "Max track: " << max_track; Mat3 R = Mat3::Identity(); for (int image = 0; image <= max_image; ++image) { vector<Marker> all_markers = tracks.MarkersInImage(image); ModalSolverLogProress(update_callback, (float) image / max_image); // Skip empty frames without doing anything if (all_markers.size() == 0) { LG << "Skipping frame: " << image; continue; } vector<Vec3> points, reference_points; // Cnstruct pairs of markers from current and previous image, // to reproject them and find rigid transformation between // previous and current image for (int track = 0; track <= max_track; ++track) { EuclideanPoint *point = reconstruction->PointForTrack(track); if (point) { Marker marker = tracks.MarkerInImageForTrack(image, track); if (marker.image == image) { Vec3 X; LG << "Use track " << track << " for rigid registration between image " << image - 1 << " and " << image; ProjectMarkerOnSphere(marker, X); points.push_back(R * point->X); reference_points.push_back(X); } } } if (points.size()) { Mat3 dR = Mat3::Identity(); // Find rigid delta transformation from previous image to current image RigidRegistration(reference_points, points, dR); R *= dR; } reconstruction->InsertCamera(image, R, Vec3::Zero()); // Review if there's new tracks for which position might be reconstructed for (int track = 0; track <= max_track; ++track) { if (!reconstruction->PointForTrack(track)) { Marker marker = tracks.MarkerInImageForTrack(image, track); if (marker.image == image) { // New track appeared on this image, project it's position onto sphere LG << "Projecting track " << track << " at image " << image; Vec3 X; ProjectMarkerOnSphere(marker, X); reconstruction->InsertPoint(track, R.inverse() * X); } } } } } } // namespace libmv <commit_msg>Modal solver: Detect rigid transformation between initial frame and current instead of detecting it between two neighbour frames.<commit_after>// Copyright (c) 2012 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <cstdio> #include "libmv/logging/logging.h" #include "libmv/simple_pipeline/modal_solver.h" #include "libmv/simple_pipeline/rigid_registration.h" #ifdef _MSC_VER # define snprintf _snprintf #endif namespace libmv { static void ProjectMarkerOnSphere(Marker &marker, Vec3 &X) { X(0) = marker.x; X(1) = marker.y; X(2) = 1.0; X *= 5.0 / X.norm(); } static void ModalSolverLogProress(ProgressUpdateCallback *update_callback, double progress) { if (update_callback) { char message[256]; snprintf(message, sizeof(message), "Solving progress %d%%", (int)(progress * 100)); update_callback->invoke(progress, message); } } void ModalSolver(Tracks &tracks, EuclideanReconstruction *reconstruction, ProgressUpdateCallback *update_callback) { int max_image = tracks.MaxImage(); int max_track = tracks.MaxTrack(); LG << "Max image: " << max_image; LG << "Max track: " << max_track; Mat3 R = Mat3::Identity(); for (int image = 0; image <= max_image; ++image) { vector<Marker> all_markers = tracks.MarkersInImage(image); ModalSolverLogProress(update_callback, (float) image / max_image); // Skip empty frames without doing anything if (all_markers.size() == 0) { LG << "Skipping frame: " << image; continue; } vector<Vec3> points, reference_points; // Cnstruct pairs of markers from current and previous image, // to reproject them and find rigid transformation between // previous and current image for (int track = 0; track <= max_track; ++track) { EuclideanPoint *point = reconstruction->PointForTrack(track); if (point) { Marker marker = tracks.MarkerInImageForTrack(image, track); if (marker.image == image) { Vec3 X; LG << "Use track " << track << " for rigid registration between image " << image - 1 << " and " << image; ProjectMarkerOnSphere(marker, X); points.push_back(point->X); reference_points.push_back(X); } } } if (points.size()) { // Find rigid delta transformation to current image RigidRegistration(reference_points, points, R); } reconstruction->InsertCamera(image, R, Vec3::Zero()); // Review if there's new tracks for which position might be reconstructed for (int track = 0; track <= max_track; ++track) { if (!reconstruction->PointForTrack(track)) { Marker marker = tracks.MarkerInImageForTrack(image, track); if (marker.image == image) { // New track appeared on this image, project it's position onto sphere LG << "Projecting track " << track << " at image " << image; Vec3 X; ProjectMarkerOnSphere(marker, X); reconstruction->InsertPoint(track, R.inverse() * X); } } } } } } // namespace libmv <|endoftext|>
<commit_before>#include "InitState.hpp" const int rd::InitState::LOGIN_SUCCESSFUL = 1; rd::InitState::InitState(rd::RdNetworkManager *networkManager, rd::RdImageManager *imageManager, rd::RdInputManager *inputManager, rd::RdMentalMap *mentalMap, rd::RdRobotManager *robotManager, AudioManager *audioManager) : ManagerHub(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager) { state_id = "InitState"; login = false; logged_in = false; } rd::InitState::~InitState() { } bool rd::InitState::setup() { //-- Show Robot Devastation start screen: if( ! screen.init() ) return false; screen.show(); //-- Start Robot Devastation music theme: audioManager->start(); audioManager->play("RD_THEME", -1); //-- Wait for input (set listener): inputManager->addInputEventListener(this); inputManager->start(); //-- Setup network manager networkManager->addNetworkEventListener(mentalMap); mentalMap->addMentalMapEventListener((RdYarpNetworkManager *)networkManager); if( ! networkManager->start() ) return false; return true; } bool rd::InitState::loop() { if (login) { //-- Log in networkManager->login(); if( ! robotManager->connect() ) return false; robotManager->setEnabled(false); imageManager->start(); logged_in = true; } return true; } bool rd::InitState::cleanup() { RD_DEBUG("Cleanup!!\n"); audioManager->stopMusic(); inputManager->removeInputEventListeners(); screen.cleanup(); return true; } int rd::InitState::evaluateConditions() { if (logged_in) return LOGIN_SUCCESSFUL; return -1; } bool rd::InitState::onKeyDown(rd::RdKey k) { return true; } bool rd::InitState::onKeyUp(rd::RdKey k) { if (k.getValue() == RdKey::KEY_ENTER) { RD_DEBUG("Enter was pressed!\n"); login = true; } } <commit_msg>InitState check if imageManager->start() fails, #65<commit_after>#include "InitState.hpp" const int rd::InitState::LOGIN_SUCCESSFUL = 1; rd::InitState::InitState(rd::RdNetworkManager *networkManager, rd::RdImageManager *imageManager, rd::RdInputManager *inputManager, rd::RdMentalMap *mentalMap, rd::RdRobotManager *robotManager, AudioManager *audioManager) : ManagerHub(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager) { state_id = "InitState"; login = false; logged_in = false; } rd::InitState::~InitState() { } bool rd::InitState::setup() { //-- Show Robot Devastation start screen: if( ! screen.init() ) return false; screen.show(); //-- Start Robot Devastation music theme: audioManager->start(); audioManager->play("RD_THEME", -1); //-- Wait for input (set listener): inputManager->addInputEventListener(this); inputManager->start(); //-- Setup network manager networkManager->addNetworkEventListener(mentalMap); mentalMap->addMentalMapEventListener((RdYarpNetworkManager *)networkManager); if( ! networkManager->start() ) return false; return true; } bool rd::InitState::loop() { if (login) { //-- Log in networkManager->login(); if( ! robotManager->connect() ) return false; robotManager->setEnabled(false); if( ! imageManager->start() ) return false; logged_in = true; } return true; } bool rd::InitState::cleanup() { RD_DEBUG("Cleanup!!\n"); audioManager->stopMusic(); inputManager->removeInputEventListeners(); screen.cleanup(); return true; } int rd::InitState::evaluateConditions() { if (logged_in) return LOGIN_SUCCESSFUL; return -1; } bool rd::InitState::onKeyDown(rd::RdKey k) { return true; } bool rd::InitState::onKeyUp(rd::RdKey k) { if (k.getValue() == RdKey::KEY_ENTER) { RD_DEBUG("Enter was pressed!\n"); login = true; } } <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "cluceneindexmanager.h" #include <strigi/strigiconfig.h> #include <CLucene.h> #include <CLucene/store/RAMDirectory.h> #include "cluceneindexwriter.h" #include "cluceneindexreader.h" #include "indexplugin.h" #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include "timeofday.h" #include "stgdirent.h" //our dirent compatibility header... uses native if available using namespace std; /* define and export the index factory */ REGISTER_STRIGI_INDEXMANAGER(CLuceneIndexManager) using namespace lucene::index; using lucene::analysis::standard::StandardAnalyzer; using lucene::store::FSDirectory; Strigi::IndexManager* createCLuceneIndexManager(const char* path) { return new CLuceneIndexManager(path); } int CLuceneIndexManager::numberOfManagers = 0; CLuceneIndexManager::CLuceneIndexManager(const std::string& path) {//: bitsets(this) { ++numberOfManagers; dbdir = path; indexwriter = 0; writer = new CLuceneIndexWriter(this); analyzer = new StandardAnalyzer(); if (path == ":memory:") { ramdirectory = new lucene::store::RAMDirectory(); } else { ramdirectory = 0; } gettimeofday(&mtime, 0); //remove any old segments lying around from crashes, etc //writer->cleanUp(); // make sure there's at least an index openWriter(); } CLuceneIndexManager::~CLuceneIndexManager() { // close the writer and analyzer delete writer; std::map<STRIGI_THREAD_TYPE, CLuceneIndexReader*>::iterator r; for (r = readers.begin(); r != readers.end(); ++r) { delete r->second; r->second = 0; } closeWriter(); delete ramdirectory; delete analyzer; if (--numberOfManagers == 0) { // temporarily commented out because of problem with clucene // _lucene_shutdown(); } } Strigi::IndexReader* CLuceneIndexManager::indexReader() { return luceneReader(); } CLuceneIndexReader* CLuceneIndexManager::luceneReader() { // TODO check if we should update/reopen the reader STRIGI_THREAD_TYPE self = STRIGI_THREAD_SELF(); CLuceneIndexReader* r; lock.lock(); r = readers[self]; lock.unlock(); if (r == 0) { r = new CLuceneIndexReader(this, dbdir); lock.lock(); readers[self] = r; lock.unlock(); } return r; } Strigi::IndexWriter* CLuceneIndexManager::indexWriter() { return writer; } IndexWriter* CLuceneIndexManager::refWriter() { writelock.lock(); if (indexwriter == 0) { openWriter(); } return indexwriter; } void CLuceneIndexManager::derefWriter() { writelock.unlock(); } void CLuceneIndexManager::openWriter(bool truncate) { try { if (ramdirectory) { indexwriter = new IndexWriter(ramdirectory, analyzer, true); } else if (!truncate && IndexReader::indexExists(dbdir.c_str())) { if (IndexReader::isLocked(dbdir.c_str())) { IndexReader::unlock(dbdir.c_str()); } indexwriter = new IndexWriter(dbdir.c_str(), analyzer, false); } else { indexwriter = new IndexWriter(dbdir.c_str(), analyzer, true); } } catch (CLuceneError& err) { fprintf(stderr, "could not create writer: %s\n", err.what()); indexwriter = 0; } } void CLuceneIndexManager::closeWriter() { refWriter(); if (indexwriter == 0) { derefWriter(); return; } // update the timestamp on the index, so that the readers will reopen try { indexwriter->close(); delete indexwriter; } catch (CLuceneError& err) { printf("could not close writer: %s\n", err.what()); } indexwriter = 0; // clear the cache //bitsets.clear(); derefWriter(); setIndexMTime(); } int64_t CLuceneIndexManager::indexSize() { // sum the sizes of the files in the index // loop over directory entries DIR* dir = opendir(dbdir.c_str()); if (dir == 0) { fprintf(stderr, "could not open index directory %s (%s)\n", dbdir.c_str(), strerror(errno)); return -1; } struct dirent* e = readdir(dir); int64_t size = 0; while (e != 0) { string filename = dbdir+'/'+e->d_name; struct stat s; int r = stat(filename.c_str(), &s); if (r == 0) { if ( S_ISREG(s.st_mode)) { size += s.st_size; } } else { fprintf(stderr, "could not open file %s (%s)\n", filename.c_str(), strerror(errno)); } e = readdir(dir); } closedir(dir); return size; } void CLuceneIndexManager::deleteIndex() { closeWriter(); setIndexMTime(); openWriter(true); } struct timeval CLuceneIndexManager::indexMTime() { struct timeval t; lock.lock(); t = mtime; lock.unlock(); return t; } void CLuceneIndexManager::setIndexMTime() { lock.lock(); gettimeofday(&mtime, 0); lock.unlock(); } <commit_msg>Do not recreate index in RAMDirectory every time.<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "cluceneindexmanager.h" #include <strigi/strigiconfig.h> #include <CLucene.h> #include <CLucene/store/RAMDirectory.h> #include "cluceneindexwriter.h" #include "cluceneindexreader.h" #include "indexplugin.h" #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include "timeofday.h" #include "stgdirent.h" //our dirent compatibility header... uses native if available using namespace std; /* define and export the index factory */ REGISTER_STRIGI_INDEXMANAGER(CLuceneIndexManager) using namespace lucene::index; using lucene::analysis::standard::StandardAnalyzer; using lucene::store::FSDirectory; Strigi::IndexManager* createCLuceneIndexManager(const char* path) { return new CLuceneIndexManager(path); } int CLuceneIndexManager::numberOfManagers = 0; CLuceneIndexManager::CLuceneIndexManager(const std::string& path) {//: bitsets(this) { ++numberOfManagers; dbdir = path; indexwriter = 0; writer = new CLuceneIndexWriter(this); analyzer = new StandardAnalyzer(); if (path == ":memory:") { ramdirectory = new lucene::store::RAMDirectory(); } else { ramdirectory = 0; } gettimeofday(&mtime, 0); //remove any old segments lying around from crashes, etc //writer->cleanUp(); // make sure there's at least an index openWriter(); } CLuceneIndexManager::~CLuceneIndexManager() { // close the writer and analyzer delete writer; std::map<STRIGI_THREAD_TYPE, CLuceneIndexReader*>::iterator r; for (r = readers.begin(); r != readers.end(); ++r) { delete r->second; r->second = 0; } closeWriter(); delete ramdirectory; delete analyzer; if (--numberOfManagers == 0) { // temporarily commented out because of problem with clucene // _lucene_shutdown(); } } Strigi::IndexReader* CLuceneIndexManager::indexReader() { return luceneReader(); } CLuceneIndexReader* CLuceneIndexManager::luceneReader() { // TODO check if we should update/reopen the reader STRIGI_THREAD_TYPE self = STRIGI_THREAD_SELF(); CLuceneIndexReader* r; lock.lock(); r = readers[self]; lock.unlock(); if (r == 0) { r = new CLuceneIndexReader(this, dbdir); lock.lock(); readers[self] = r; lock.unlock(); } return r; } Strigi::IndexWriter* CLuceneIndexManager::indexWriter() { return writer; } IndexWriter* CLuceneIndexManager::refWriter() { writelock.lock(); if (indexwriter == 0) { openWriter(); } return indexwriter; } void CLuceneIndexManager::derefWriter() { writelock.unlock(); } void CLuceneIndexManager::openWriter(bool truncate) { try { if (ramdirectory) { indexwriter = new IndexWriter(ramdirectory, analyzer, !IndexReader::indexExists(ramdirectory)); } else if (!truncate && IndexReader::indexExists(dbdir.c_str())) { if (IndexReader::isLocked(dbdir.c_str())) { IndexReader::unlock(dbdir.c_str()); } indexwriter = new IndexWriter(dbdir.c_str(), analyzer, false); } else { indexwriter = new IndexWriter(dbdir.c_str(), analyzer, true); } } catch (CLuceneError& err) { fprintf(stderr, "could not create writer: %s\n", err.what()); indexwriter = 0; } } void CLuceneIndexManager::closeWriter() { refWriter(); if (indexwriter == 0) { derefWriter(); return; } // update the timestamp on the index, so that the readers will reopen try { indexwriter->close(); delete indexwriter; } catch (CLuceneError& err) { printf("could not close writer: %s\n", err.what()); } indexwriter = 0; // clear the cache //bitsets.clear(); derefWriter(); setIndexMTime(); } int64_t CLuceneIndexManager::indexSize() { // sum the sizes of the files in the index // loop over directory entries DIR* dir = opendir(dbdir.c_str()); if (dir == 0) { fprintf(stderr, "could not open index directory %s (%s)\n", dbdir.c_str(), strerror(errno)); return -1; } struct dirent* e = readdir(dir); int64_t size = 0; while (e != 0) { string filename = dbdir+'/'+e->d_name; struct stat s; int r = stat(filename.c_str(), &s); if (r == 0) { if ( S_ISREG(s.st_mode)) { size += s.st_size; } } else { fprintf(stderr, "could not open file %s (%s)\n", filename.c_str(), strerror(errno)); } e = readdir(dir); } closedir(dir); return size; } void CLuceneIndexManager::deleteIndex() { closeWriter(); setIndexMTime(); openWriter(true); } struct timeval CLuceneIndexManager::indexMTime() { struct timeval t; lock.lock(); t = mtime; lock.unlock(); return t; } void CLuceneIndexManager::setIndexMTime() { lock.lock(); gettimeofday(&mtime, 0); lock.unlock(); } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ #include <vw/Stereo/StereoModel.h> #include <vw/Cartography/Datum.h> #include <asp/Camera/OpticalBarModel.h> #include <boost/scoped_ptr.hpp> #include <test/Helpers.h> using namespace vw; using namespace asp; using namespace asp::camera; using namespace vw::test; using namespace vw::camera; TEST(OpticalBarModel, CreateCamera) { vw::cartography::Datum d("WGS84"); //Vector3 llh(-122.065046, 37.419733, 250000); Vector3 llh(0.0, 90.0, 250000); Vector3 angles(0,0,0); // Looking down at the north pole Vector3 gcc = d.geodetic_to_cartesian(llh); double pixel_size = 7*10e-6; Vector2i image_size(12000, 4000); Vector2 center_loc_pixels(-4.3, -1.2) + image_size/2; double focal_length = 609.602/1000.0; double scan_angle_radians = 70 * M_PI/180; double scan_rate_radians = 192 * M_PI/180; Vector3 initial_position(gcc); Vector3 initial_orientation(angles); double velocity = 7800; bool use_motion_comp = true; OpticalBarModel* raw_ptr = new OpticalBarModel(image_size, center_loc_pixels, pixel_size, focal_length, scan_angle_radians, scan_rate_radians, initial_position, initial_orientation, velocity, use_motion_comp); // Basic file I/O OpticalBarModel cpy; EXPECT_NO_THROW(raw_ptr->write("test.tsai")); EXPECT_NO_THROW(cpy.read ("test.tsai")); EXPECT_VECTOR_EQ(raw_ptr->get_image_size(), cpy.get_image_size()); typedef boost::shared_ptr<vw::camera::CameraModel> CameraModelPtr; CameraModelPtr cam1; cam1 = CameraModelPtr(raw_ptr); ASSERT_TRUE( cam1.get() != 0 ); // A more accurate test is just to project out and back into the same camera for ( size_t i = 0; i < 3000; i += 500 ) { for ( size_t j = 0; j < 2400; j += 500 ) { Vector2 pixel(i,j); Vector3 center = cam1->camera_center(pixel); EXPECT_VECTOR_NEAR( pixel, cam1->point_to_pixel( center + 2e4*cam1->pixel_to_vector(pixel) ), 1e-1 /*pixels*/); } } } <commit_msg>Make TestOpticalBar complie<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ #include <vw/Stereo/StereoModel.h> #include <vw/Cartography/Datum.h> #include <asp/Camera/OpticalBarModel.h> #include <boost/scoped_ptr.hpp> #include <test/Helpers.h> using namespace vw; using namespace asp; using namespace asp::camera; using namespace vw::test; using namespace vw::camera; TEST(OpticalBarModel, CreateCamera) { vw::cartography::Datum d("WGS84"); //Vector3 llh(-122.065046, 37.419733, 250000); Vector3 llh(0.0, 90.0, 250000); Vector3 angles(0,0,0); // Looking down at the north pole Vector3 gcc = d.geodetic_to_cartesian(llh); double pixel_size = 7*10e-6; Vector2i image_size(12000, 4000); Vector2 center_loc_pixels = Vector2(-4.3, -1.2) + image_size/2; double focal_length = 609.602/1000.0; double scan_angle_radians = 70 * M_PI/180; double scan_rate_radians = 192 * M_PI/180; Vector3 initial_position(gcc); Vector3 initial_orientation(angles); double velocity = 7800; bool use_motion_comp = true; OpticalBarModel* raw_ptr = new OpticalBarModel(image_size, center_loc_pixels, pixel_size, focal_length, scan_angle_radians, scan_rate_radians, initial_position, initial_orientation, velocity, use_motion_comp); // Basic file I/O OpticalBarModel cpy; EXPECT_NO_THROW(raw_ptr->write("test.tsai")); EXPECT_NO_THROW(cpy.read ("test.tsai")); EXPECT_VECTOR_EQ(raw_ptr->get_image_size(), cpy.get_image_size()); typedef boost::shared_ptr<vw::camera::CameraModel> CameraModelPtr; CameraModelPtr cam1; cam1 = CameraModelPtr(raw_ptr); ASSERT_TRUE( cam1.get() != 0 ); // A more accurate test is just to project out and back into the same camera for ( size_t i = 0; i < 3000; i += 500 ) { for ( size_t j = 0; j < 2400; j += 500 ) { Vector2 pixel(i,j); Vector3 center = cam1->camera_center(pixel); EXPECT_VECTOR_NEAR( pixel, cam1->point_to_pixel( center + 2e4*cam1->pixel_to_vector(pixel) ), 1e-1 /*pixels*/); } } } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // nested_loop_join_executor.cpp // // Identification: src/backend/executor/nested_loop_join_executor.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <vector> #include <unordered_set> #include "backend/common/types.h" #include "backend/common/logger.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/nested_loop_join_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/container_tuple.h" namespace peloton { namespace executor { /** * @brief Constructor for nested loop join executor. * @param node Nested loop join node corresponding to this executor. */ NestedLoopJoinExecutor::NestedLoopJoinExecutor( const planner::AbstractPlan *node, ExecutorContext *executor_context) : AbstractJoinExecutor(node, executor_context) {} /** * @brief Do some basic checks and create the schema for the output logical * tiles. * @return true on success, false otherwise. */ bool NestedLoopJoinExecutor::DInit() { auto status = AbstractJoinExecutor::DInit(); if (status == false) { return status; } assert(right_result_tiles_.empty()); right_child_done_ = false; right_result_itr_ = 0; assert(left_result_tiles_.empty()); return true; } /** * @brief Creates logical tiles from the two input logical tiles after applying * join predicate. * @return true on success, false otherwise. */ bool NestedLoopJoinExecutor::DExecute() { LOG_INFO("********** Nested Loop %s Join executor :: 2 children \n", GetJoinTypeString()); for(;;){ // Loop until we have non-empty result tile or exit LogicalTile* left_tile = nullptr; LogicalTile* right_tile = nullptr; bool advance_left_child = false; if(right_child_done_){ // If we have already retrieved all right child's results in buffer LOG_TRACE("Advance the right buffer iterator."); assert(!left_result_tiles_.empty()); assert(!right_result_tiles_.empty()); right_result_itr_++; if(right_result_itr_ >= right_result_tiles_.size()){ advance_left_child = true; right_result_itr_ = 0; } } else { // Otherwise, we must attempt to execute the right child if(false == children_[1]->Execute()){ // right child is finished, no more tiles LOG_TRACE("My right child is exhausted."); if(right_result_tiles_.empty()){ assert(left_result_tiles_.empty()); LOG_TRACE("Right child returns nothing totally. Exit."); return false; } right_child_done_ = true; right_result_itr_ = 0; advance_left_child = true; } else { // Buffer the right child's result LOG_TRACE("Retrieve a new tile from right child"); right_result_tiles_.push_back(children_[1]->GetOutput()); right_result_itr_ = right_result_tiles_.size() - 1; } } if(advance_left_child || left_result_tiles_.empty()){ assert(0 == right_result_itr_); // Need to advance the left child if(false == children_[0]->Execute()){ LOG_TRACE("Left child is exhausted. Returning false."); // Left child exhausted. // The whole executor is done. // Release cur left tile. Clear right child's result buffer and return. assert(right_result_tiles_.size() > 0); return false; } else{ LOG_TRACE("Advance the left child."); // Insert left child's result to buffer left_result_tiles_.push_back(children_[0]->GetOutput()); } } left_tile = left_result_tiles_.back(); right_tile = right_result_tiles_[right_result_itr_]; // Check the input logical tiles. assert(left_tile != nullptr); assert(right_tile != nullptr); // Construct output logical tile. std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile()); auto left_tile_schema = left_tile->GetSchema(); auto right_tile_schema = right_tile->GetSchema(); for (auto &col : right_tile_schema) { col.position_list_idx += left_tile->GetPositionLists().size(); } /* build the schema given the projection */ auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema); // Set the output logical tile schema output_tile->SetSchema(std::move(output_tile_schema)); // Now, let's compute the position lists for the output tile // Cartesian product // Add everything from two logical tiles auto left_tile_position_lists = left_tile->GetPositionLists(); auto right_tile_position_lists = right_tile->GetPositionLists(); // Compute output tile column count size_t left_tile_column_count = left_tile_position_lists.size(); size_t right_tile_column_count = right_tile_position_lists.size(); size_t output_tile_column_count = left_tile_column_count + right_tile_column_count; assert(left_tile_column_count > 0); assert(right_tile_column_count > 0); // Construct position lists for output tile // TODO: We don't have to copy position lists for each column, // as there are likely duplications of them. // But must pay attention to the output schema (see how it is constructed!) std::vector<std::vector<oid_t>> position_lists; for (size_t column_itr = 0; column_itr < output_tile_column_count; column_itr++) position_lists.push_back(std::vector<oid_t>()); LOG_TRACE("left col count: %lu, right col count: %lu", left_tile_column_count, right_tile_column_count); LOG_TRACE("left col count: %lu, right col count: %lu", left_tile->GetColumnCount(), right_tile->GetColumnCount()); LOG_TRACE("left row count: %lu, right row count: %lu", left_tile_row_count, right_tile_row_count); unsigned int removed = 0; // Go over every pair of tuples in left and right logical tiles // Right Join, Outer Join // this set contains row id in right tile that none of the row in left tile matches // this set is initialized with all ids in right tile and // as the nested loop goes, id in the set are removed if a match is made, // After nested looping, ids left are rows with no matching. std::unordered_set<oid_t> no_match_rows; // only initialize if we are doing right or outer join if (join_type_ == JOIN_TYPE_RIGHT || join_type_ == JOIN_TYPE_OUTER) { no_match_rows.insert(right_tile->begin(), right_tile->end()); } for(auto left_tile_row_itr : *left_tile){ bool has_right_match = false; for(auto right_tile_row_itr : *right_tile){ // TODO: OPTIMIZATION : Can split the control flow into two paths - // one for Cartesian product and one for join // Then, we can skip this branch atleast for the Cartesian product path. // Join predicate exists if (predicate_ != nullptr) { expression::ContainerTuple<executor::LogicalTile> left_tuple( left_tile, left_tile_row_itr); expression::ContainerTuple<executor::LogicalTile> right_tuple( right_tile, right_tile_row_itr); // Join predicate is false. Skip pair and continue. if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_) .IsFalse()) { removed++; continue; } } // Right Outer Join, Full Outer Join: // Remove a matched right row if (join_type_ == JOIN_TYPE_RIGHT || join_type_ == JOIN_TYPE_OUTER) { no_match_rows.erase(right_tile_row_itr); } // Left Outer Join, Full Outer Join: has_right_match = true; // Insert a tuple into the output logical tile // First, copy the elements in left logical tile's tuple for (size_t output_tile_column_itr = 0; output_tile_column_itr < left_tile_column_count; output_tile_column_itr++) { position_lists[output_tile_column_itr].push_back( left_tile_position_lists[output_tile_column_itr] [left_tile_row_itr]); } // Then, copy the elements in right logical tile's tuple for (size_t output_tile_column_itr = 0; output_tile_column_itr < right_tile_column_count; output_tile_column_itr++) { position_lists[left_tile_column_count + output_tile_column_itr] .push_back(right_tile_position_lists[output_tile_column_itr] [right_tile_row_itr]); } } // inner loop of NLJ // Left Outer Join, Full Outer Join: if ((join_type_ == JOIN_TYPE_LEFT || join_type_ == JOIN_TYPE_OUTER) && !has_right_match) { LOG_INFO("Left or ful outer: Null row, left id %lu", left_tile_row_itr); // no right tuple matched, if we are doing left outer join or full outer join // we should also emit a tuple in which right parts are null for (size_t output_tile_column_itr = 0; output_tile_column_itr < left_tile_column_count; output_tile_column_itr++) { position_lists[output_tile_column_itr].push_back( left_tile_position_lists[output_tile_column_itr] [left_tile_row_itr]); } // Then, copy the elements in right logical tile's tuple for (size_t output_tile_column_itr = 0; output_tile_column_itr < right_tile_column_count; output_tile_column_itr++) { position_lists[left_tile_column_count + output_tile_column_itr] .push_back(NULL_OID); } } } // outer loop of NLJ // Right Outer Join, Full Outer Join: // For each row in right tile // it it has no match in left, we should emit a row whose left parts // are null if (join_type_ == JOIN_TYPE_RIGHT || join_type_ == JOIN_TYPE_OUTER) { for (auto left_null_row_itr : no_match_rows) { LOG_INFO("right or full outer: Null row, right id %lu", left_null_row_itr); for (size_t output_tile_column_itr = 0; output_tile_column_itr < left_tile_column_count; output_tile_column_itr++) { position_lists[output_tile_column_itr].push_back(NULL_OID); } for (size_t output_tile_column_itr = 0; output_tile_column_itr < right_tile_column_count; output_tile_column_itr++) { position_lists[left_tile_column_count + output_tile_column_itr] .push_back(right_tile_position_lists[output_tile_column_itr][left_null_row_itr]); } } } LOG_INFO("Predicate removed %d rows", removed); // Check if we have any matching tuples. if (position_lists[0].size() > 0) { output_tile->SetPositionListsAndVisibility(std::move(position_lists)); SetOutput(output_tile.release()); return true; } LOG_TRACE("This pair produces empty join result. Loop."); } // End large for-loop } NestedLoopJoinExecutor::~NestedLoopJoinExecutor(){ for(auto tile : left_result_tiles_){ delete tile; left_result_tiles_.clear(); } for(auto tile : right_result_tiles_){ delete tile; right_result_tiles_.clear(); } } } // namespace executor } // namespace peloton <commit_msg>Minor changes<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // nested_loop_join_executor.cpp // // Identification: src/backend/executor/nested_loop_join_executor.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <vector> #include <unordered_set> #include "backend/common/types.h" #include "backend/common/logger.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/nested_loop_join_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/container_tuple.h" namespace peloton { namespace executor { /** * @brief Constructor for nested loop join executor. * @param node Nested loop join node corresponding to this executor. */ NestedLoopJoinExecutor::NestedLoopJoinExecutor( const planner::AbstractPlan *node, ExecutorContext *executor_context) : AbstractJoinExecutor(node, executor_context) { } /** * @brief Do some basic checks and create the schema for the output logical * tiles. * @return true on success, false otherwise. */ bool NestedLoopJoinExecutor::DInit() { auto status = AbstractJoinExecutor::DInit(); if (status == false) { return status; } assert(right_result_tiles_.empty()); right_child_done_ = false; right_result_itr_ = 0; assert(left_result_tiles_.empty()); return true; } /** * @brief Creates logical tiles from the two input logical tiles after applying * join predicate. * @return true on success, false otherwise. */ bool NestedLoopJoinExecutor::DExecute() { LOG_INFO("********** Nested Loop %s Join executor :: 2 children \n", GetJoinTypeString()); for (;;) { // Loop until we have non-empty result tile or exit LogicalTile* left_tile = nullptr; LogicalTile* right_tile = nullptr; bool advance_left_child = false; if (right_child_done_) { // If we have already retrieved all right child's results in buffer LOG_TRACE("Advance the right buffer iterator."); assert(!left_result_tiles_.empty()); assert(!right_result_tiles_.empty()); right_result_itr_++; if (right_result_itr_ >= right_result_tiles_.size()) { advance_left_child = true; right_result_itr_ = 0; } } else { // Otherwise, we must attempt to execute the right child if (false == children_[1]->Execute()) { // right child is finished, no more tiles LOG_TRACE("My right child is exhausted."); if (right_result_tiles_.empty()) { assert(left_result_tiles_.empty()); LOG_TRACE("Right child returns nothing totally. Exit."); return false; } right_child_done_ = true; right_result_itr_ = 0; advance_left_child = true; } else { // Buffer the right child's result LOG_TRACE("Retrieve a new tile from right child"); right_result_tiles_.push_back(children_[1]->GetOutput()); right_result_itr_ = right_result_tiles_.size() - 1; } } if (advance_left_child || left_result_tiles_.empty()) { assert(0 == right_result_itr_); // Need to advance the left child if (false == children_[0]->Execute()) { LOG_TRACE("Left child is exhausted. Returning false."); // Left child exhausted. // The whole executor is done. // Release cur left tile. Clear right child's result buffer and return. assert(right_result_tiles_.size() > 0); return false; } else { LOG_TRACE("Advance the left child."); // Insert left child's result to buffer left_result_tiles_.push_back(children_[0]->GetOutput()); } } left_tile = left_result_tiles_.back(); right_tile = right_result_tiles_[right_result_itr_]; // Check the input logical tiles. assert(left_tile != nullptr); assert(right_tile != nullptr); // Construct output logical tile. std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile()); auto left_tile_schema = left_tile->GetSchema(); auto right_tile_schema = right_tile->GetSchema(); for (auto &col : right_tile_schema) { col.position_list_idx += left_tile->GetPositionLists().size(); } /* build the schema given the projection */ auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema); // Set the output logical tile schema output_tile->SetSchema(std::move(output_tile_schema)); // Now, let's compute the position lists for the output tile // Cartesian product // Add everything from two logical tiles auto left_tile_position_lists = left_tile->GetPositionLists(); auto right_tile_position_lists = right_tile->GetPositionLists(); // Compute output tile column count size_t left_tile_column_count = left_tile_position_lists.size(); size_t right_tile_column_count = right_tile_position_lists.size(); size_t output_tile_column_count = left_tile_column_count + right_tile_column_count; assert(left_tile_column_count > 0); assert(right_tile_column_count > 0); // Construct position lists for output tile // TODO: We don't have to copy position lists for each column, // as there are likely duplications of them. // But must pay attention to the output schema (see how it is constructed!) std::vector<std::vector<oid_t>> position_lists; for (size_t column_itr = 0; column_itr < output_tile_column_count; column_itr++) position_lists.push_back(std::vector<oid_t>()); LOG_TRACE("left col count: %lu, right col count: %lu", left_tile_column_count, right_tile_column_count); LOG_TRACE("left col count: %lu, right col count: %lu", left_tile->GetColumnCount(), right_tile->GetColumnCount()); LOG_TRACE("left row count: %lu, right row count: %lu", left_tile_row_count, right_tile_row_count); unsigned int removed = 0; // Go over every pair of tuples in left and right logical tiles // Right Join, Outer Join // this set contains row id in right tile that none of the row in left tile matches // this set is initialized with all ids in right tile and // as the nested loop goes, id in the set are removed if a match is made, // After nested looping, ids left are rows with no matching. std::unordered_set<oid_t> no_match_rows; // only initialize if we are doing right or outer join if (join_type_ == JOIN_TYPE_RIGHT || join_type_ == JOIN_TYPE_OUTER) { no_match_rows.insert(right_tile->begin(), right_tile->end()); } for (auto left_tile_row_itr : *left_tile) { bool has_right_match = false; for (auto right_tile_row_itr : *right_tile) { // TODO: OPTIMIZATION : Can split the control flow into two paths - // one for Cartesian product and one for join // Then, we can skip this branch atleast for the Cartesian product path. // Join predicate exists if (predicate_ != nullptr) { expression::ContainerTuple<executor::LogicalTile> left_tuple( left_tile, left_tile_row_itr); expression::ContainerTuple<executor::LogicalTile> right_tuple( right_tile, right_tile_row_itr); // Join predicate is false. Skip pair and continue. if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_) .IsFalse()) { removed++; continue; } } // Right Outer Join, Full Outer Join: // Remove a matched right row if (join_type_ == JOIN_TYPE_RIGHT || join_type_ == JOIN_TYPE_OUTER) { no_match_rows.erase(right_tile_row_itr); } // Left Outer Join, Full Outer Join: has_right_match = true; // Insert a tuple into the output logical tile // First, copy the elements in left logical tile's tuple for (size_t output_tile_column_itr = 0; output_tile_column_itr < left_tile_column_count; output_tile_column_itr++) { position_lists[output_tile_column_itr].push_back( left_tile_position_lists[output_tile_column_itr][left_tile_row_itr]); } // Then, copy the elements in right logical tile's tuple for (size_t output_tile_column_itr = 0; output_tile_column_itr < right_tile_column_count; output_tile_column_itr++) { position_lists[left_tile_column_count + output_tile_column_itr] .push_back( right_tile_position_lists[output_tile_column_itr][right_tile_row_itr]); } } // inner loop of NLJ // Left Outer Join, Full Outer Join: if ((join_type_ == JOIN_TYPE_LEFT || join_type_ == JOIN_TYPE_OUTER) && !has_right_match) { LOG_INFO("Left or ful outer: Null row, left id %lu", left_tile_row_itr); // no right tuple matched, if we are doing left outer join or full outer join // we should also emit a tuple in which right parts are null for (size_t output_tile_column_itr = 0; output_tile_column_itr < left_tile_column_count; output_tile_column_itr++) { position_lists[output_tile_column_itr].push_back( left_tile_position_lists[output_tile_column_itr][left_tile_row_itr]); } // Then, copy the elements in right logical tile's tuple for (size_t output_tile_column_itr = 0; output_tile_column_itr < right_tile_column_count; output_tile_column_itr++) { position_lists[left_tile_column_count + output_tile_column_itr] .push_back(NULL_OID); } } } // outer loop of NLJ // Right Outer Join, Full Outer Join: // For each row in right tile // it it has no match in left, we should emit a row whose left parts // are null if (join_type_ == JOIN_TYPE_RIGHT || join_type_ == JOIN_TYPE_OUTER) { for (auto left_null_row_itr : no_match_rows) { LOG_INFO("right or full outer: Null row, right id %lu", left_null_row_itr); for (size_t output_tile_column_itr = 0; output_tile_column_itr < left_tile_column_count; output_tile_column_itr++) { position_lists[output_tile_column_itr].push_back(NULL_OID); } for (size_t output_tile_column_itr = 0; output_tile_column_itr < right_tile_column_count; output_tile_column_itr++) { position_lists[left_tile_column_count + output_tile_column_itr] .push_back( right_tile_position_lists[output_tile_column_itr][left_null_row_itr]); } } } LOG_INFO("Predicate removed %d rows", removed); // Check if we have any matching tuples. if (position_lists[0].size() > 0) { output_tile->SetPositionListsAndVisibility(std::move(position_lists)); SetOutput(output_tile.release()); return true; } LOG_TRACE("This pair produces empty join result. Loop."); } // End large for-loop } NestedLoopJoinExecutor::~NestedLoopJoinExecutor() { for (auto tile : left_result_tiles_) { delete tile; left_result_tiles_.clear(); } for (auto tile : right_result_tiles_) { delete tile; right_result_tiles_.clear(); } } } // namespace executor } // namespace peloton <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "core/block.h" #include "core/transaction.h" #include "main.h" #include "rpcserver.h" #include "streams.h" #include "sync.h" #include "utilstrencodings.h" #include "version.h" #include <boost/algorithm/string.hpp> using namespace std; using namespace json_spirit; enum RetFormat { RF_BINARY, RF_HEX, RF_JSON, }; static const struct { enum RetFormat rf; const char *name; } rf_names[] = { { RF_BINARY, "binary" }, // default, if match not found { RF_HEX, "hex" }, { RF_JSON, "json" }, }; class RestErr { public: enum HTTPStatusCode status; string message; }; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry); extern Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex); static RestErr RESTERR(enum HTTPStatusCode status, string message) { RestErr re; re.status = status; re.message = message; return re; } static enum RetFormat ParseDataFormat(const string& format) { for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++) if (format == rf_names[i].name) return rf_names[i].rf; return rf_names[0].rf; } static bool ParseHashStr(const string& strReq, uint256& v) { if (!IsHex(strReq) || (strReq.size() != 64)) return false; v.SetHex(strReq); return true; } static bool rest_block(AcceptedConnection *conn, string& strReq, map<string, string>& mapHeaders, bool fRun) { vector<string> params; boost::split(params, strReq, boost::is_any_of("/")); enum RetFormat rf = ParseDataFormat(params.size() > 1 ? params[1] : string("")); string hashStr = params[0]; uint256 hash; if (!ParseHashStr(hashStr, hash)) throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); CBlock block; CBlockIndex* pblockindex = NULL; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found"); pblockindex = mapBlockIndex[hash]; if (!ReadBlockFromDisk(block, pblockindex)) throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found"); } CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; switch (rf) { case RF_BINARY: { string binaryBlock = ssBlock.str(); conn->stream() << HTTPReply(HTTP_OK, binaryBlock, fRun, true, "application/octet-stream") << binaryBlock << std::flush; return true; } case RF_HEX: { string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";; conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush; return true; } case RF_JSON: { Object objBlock = blockToJSON(block, pblockindex); string strJSON = write_string(Value(objBlock), false) + "\n"; conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush; return true; } } // not reached return true; // continue to process further HTTP reqs on this cxn } static bool rest_tx(AcceptedConnection *conn, string& strReq, map<string, string>& mapHeaders, bool fRun) { vector<string> params; boost::split(params, strReq, boost::is_any_of("/")); enum RetFormat rf = ParseDataFormat(params.size() > 1 ? params[1] : string("")); string hashStr = params[0]; uint256 hash; if (!ParseHashStr(hashStr, hash)) throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock, true)) throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; switch (rf) { case RF_BINARY: { string binaryTx = ssTx.str(); conn->stream() << HTTPReply(HTTP_OK, binaryTx, fRun, true, "application/octet-stream") << binaryTx << std::flush; return true; } case RF_HEX: { string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";; conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush; return true; } case RF_JSON: { Object objTx; TxToJSON(tx, hashBlock, objTx); string strJSON = write_string(Value(objTx), false) + "\n"; conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush; return true; } } // not reached return true; // continue to process further HTTP reqs on this cxn } static const struct { const char *prefix; bool (*handler)(AcceptedConnection *conn, string& strURI, map<string, string>& mapHeaders, bool fRun); } uri_prefixes[] = { { "/rest/tx/", rest_tx }, { "/rest/block/", rest_block }, }; bool HTTPReq_REST(AcceptedConnection *conn, string& strURI, map<string, string>& mapHeaders, bool fRun) { try { for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++) { unsigned int plen = strlen(uri_prefixes[i].prefix); if (strURI.substr(0, plen) == uri_prefixes[i].prefix) { string strReq = strURI.substr(plen); return uri_prefixes[i].handler(conn, strReq, mapHeaders, fRun); } } } catch (RestErr& re) { conn->stream() << HTTPReply(re.status, re.message + "\r\n", false, false, "text/plain") << std::flush; return false; } conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush; return false; } <commit_msg>[REST] fix headersonly flag for BINARY responses<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "core/block.h" #include "core/transaction.h" #include "main.h" #include "rpcserver.h" #include "streams.h" #include "sync.h" #include "utilstrencodings.h" #include "version.h" #include <boost/algorithm/string.hpp> using namespace std; using namespace json_spirit; enum RetFormat { RF_BINARY, RF_HEX, RF_JSON, }; static const struct { enum RetFormat rf; const char *name; } rf_names[] = { { RF_BINARY, "binary" }, // default, if match not found { RF_HEX, "hex" }, { RF_JSON, "json" }, }; class RestErr { public: enum HTTPStatusCode status; string message; }; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry); extern Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex); static RestErr RESTERR(enum HTTPStatusCode status, string message) { RestErr re; re.status = status; re.message = message; return re; } static enum RetFormat ParseDataFormat(const string& format) { for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++) if (format == rf_names[i].name) return rf_names[i].rf; return rf_names[0].rf; } static bool ParseHashStr(const string& strReq, uint256& v) { if (!IsHex(strReq) || (strReq.size() != 64)) return false; v.SetHex(strReq); return true; } static bool rest_block(AcceptedConnection *conn, string& strReq, map<string, string>& mapHeaders, bool fRun) { vector<string> params; boost::split(params, strReq, boost::is_any_of("/")); enum RetFormat rf = ParseDataFormat(params.size() > 1 ? params[1] : string("")); string hashStr = params[0]; uint256 hash; if (!ParseHashStr(hashStr, hash)) throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); CBlock block; CBlockIndex* pblockindex = NULL; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found"); pblockindex = mapBlockIndex[hash]; if (!ReadBlockFromDisk(block, pblockindex)) throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found"); } CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; switch (rf) { case RF_BINARY: { string binaryBlock = ssBlock.str(); conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryBlock.size(), "application/octet-stream") << binaryBlock << std::flush; return true; } case RF_HEX: { string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";; conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush; return true; } case RF_JSON: { Object objBlock = blockToJSON(block, pblockindex); string strJSON = write_string(Value(objBlock), false) + "\n"; conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush; return true; } } // not reached return true; // continue to process further HTTP reqs on this cxn } static bool rest_tx(AcceptedConnection *conn, string& strReq, map<string, string>& mapHeaders, bool fRun) { vector<string> params; boost::split(params, strReq, boost::is_any_of("/")); enum RetFormat rf = ParseDataFormat(params.size() > 1 ? params[1] : string("")); string hashStr = params[0]; uint256 hash; if (!ParseHashStr(hashStr, hash)) throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock, true)) throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; switch (rf) { case RF_BINARY: { string binaryTx = ssTx.str(); conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryTx.size(), "application/octet-stream") << binaryTx << std::flush; return true; } case RF_HEX: { string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";; conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush; return true; } case RF_JSON: { Object objTx; TxToJSON(tx, hashBlock, objTx); string strJSON = write_string(Value(objTx), false) + "\n"; conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush; return true; } } // not reached return true; // continue to process further HTTP reqs on this cxn } static const struct { const char *prefix; bool (*handler)(AcceptedConnection *conn, string& strURI, map<string, string>& mapHeaders, bool fRun); } uri_prefixes[] = { { "/rest/tx/", rest_tx }, { "/rest/block/", rest_block }, }; bool HTTPReq_REST(AcceptedConnection *conn, string& strURI, map<string, string>& mapHeaders, bool fRun) { try { for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++) { unsigned int plen = strlen(uri_prefixes[i].prefix); if (strURI.substr(0, plen) == uri_prefixes[i].prefix) { string strReq = strURI.substr(plen); return uri_prefixes[i].handler(conn, strReq, mapHeaders, fRun); } } } catch (RestErr& re) { conn->stream() << HTTPReply(re.status, re.message + "\r\n", false, false, "text/plain") << std::flush; return false; } conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush; return false; } <|endoftext|>
<commit_before>#include "rule.h" #include "logger.h" #include <boost/fusion/include/adapt_struct.hpp> #include <boost/lexical_cast.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/variant/recursive_variant.hpp> #include <boost/variant/apply_visitor.hpp> using namespace wotreplay; namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; BOOST_FUSION_ADAPT_STRUCT( operation_t, (operator_t, op) (operand_t, left) (operand_t, right) ) BOOST_FUSION_ADAPT_STRUCT( draw_rule_t, (uint32_t, color) (operation_t, expr) ) BOOST_FUSION_ADAPT_STRUCT( draw_rules_t, (std::vector<draw_rule_t>, rules) ) struct error_handler_ { template <typename, typename, typename> struct result { typedef void type; }; template <typename Iterator> void operator()( qi::info const& what , Iterator err_pos, Iterator last) const { std::cout << "Error! Expecting " << what // what failed? << " here: \"" << std::string(err_pos, last) // iterators to error-pos, end << "\"" << std::endl ; } }; boost::phoenix::function<error_handler_> const error_handler = error_handler_(); template<typename Iterator> struct draw_rules_grammar_t : qi::grammar<Iterator, draw_rules_t(), ascii::space_type> { draw_rules_grammar_t() : draw_rules_grammar_t::base_type(rules) { using qi::char_; using namespace qi::labels; using boost::phoenix::at_c; using boost::phoenix::push_back; qi::_2_type _2; qi::_3_type _3; qi::_4_type _4; using qi::on_error; using qi::fail; // define operator operators.add("=" , operator_t::EQUAL) ("!=", operator_t::NOT_EQUAL) (">=", operator_t::GREATER_THAN_OR_EQUAL) (">" , operator_t::GREATER_THAN) ("<=", operator_t::LESS_THAN_OR_EQUAL) ("<" , operator_t::LESS_THAN); // define logical operators logical_operators.add("and", operator_t::AND) ("or" , operator_t::OR); // define symbols symbols.add("player", symbol_t::PLAYER) ("clock" , symbol_t::CLOCK) ("team" , symbol_t::TEAM); rules = rule[push_back(at_c<0>(_val), _1)] >> *(';' >> rule[push_back(at_c<0>(_val), _1)]); rule %= color >> ":=" >> expression; color %= '#' >> qi::hex; expression = (operation[at_c<1>(_val) = _1] >> logical_operators[at_c<0>(_val) = _1] >> expression[at_c<2>(_val) = _1]) | (operation[at_c<1>(_val) = _1] >> logical_operators[at_c<0>(_val) = _1] >> operation[at_c<2>(_val) = _1]) | (operation[_val = _1]); operation = operand [at_c<1>(_val) = _1] > operators[at_c<0>(_val) = _1] > operand [at_c<2>(_val) = _1]; operand %= symbols | value; value = '\'' >> +qi::char_("a-zA-Z0-9\\-_")[_val += _1] >> '\''; // Debugging and error handling and reporting support. BOOST_SPIRIT_DEBUG_NODES( (expression)(operation)(operand)(value)); // Error handling on_error<fail>(expression, error_handler(_4, _3, _2)); } // parsing rules qi::rule<Iterator, draw_rules_t(), ascii::space_type> rules; qi::rule<Iterator, draw_rule_t() , ascii::space_type> rule; qi::rule<Iterator, uint32_t() , ascii::space_type> color; qi::rule<Iterator, operation_t() , ascii::space_type> expression; qi::rule<Iterator, operation_t() , ascii::space_type> operation; qi::rule<Iterator, operand_t() , ascii::space_type> operand; qi::rule<Iterator, std::string() , ascii::space_type> value; // symbol maps qi::symbols<char, operator_t> operators; qi::symbols<char, operator_t> logical_operators; qi::symbols<char, symbol_t> symbols; }; draw_rules_t wotreplay::parse_draw_rules(const std::string &expr) { draw_rules_grammar_t<std::string::const_iterator> grammar; draw_rules_t rules; std::string::const_iterator iter = expr.begin(); std::string::const_iterator end = expr.end(); bool r = qi::phrase_parse(iter, end, grammar, ascii::space, rules); if (r && iter == end) { logger.writef(log_level_t::info, "Parsing succesfull\n"); print(rules); } else { logger.writef(log_level_t::warning, "Parsing failed, remaining: %1%\n", std::string(iter, end)); } return rules; } class printer : public boost::static_visitor<void> { public: printer(const draw_rules_t &rules) : rules(rules) {} void operator()() { logger.writef(log_level_t::info, "Number of rules: %1%\n", rules.rules.size()); for (int i = 0; i < rules.rules.size(); i += 1) { pad(); logger.writef(log_level_t::debug, "Rule #%1%\n", i); (*this)(rules.rules[i]); } } void operator()(std::string str) { logger.write(log_level_t::debug, str); } void operator()(nil_t nil) { logger.write(log_level_t::debug, "nil"); } void operator()(symbol_t symbol) { switch(symbol) { case wotreplay::PLAYER: logger.write(log_level_t::debug, "PLAYER"); break; case wotreplay::TEAM: logger.write(log_level_t::debug, "TEAM"); break; case wotreplay::CLOCK: logger.write(log_level_t::debug, "CLOCK"); break; default: logger.write(log_level_t::debug, "<invalid symbol>"); break; } } void operator()(operator_t op) { switch(op) { case wotreplay::AND: logger.write(log_level_t::debug, "and"); break; case wotreplay::OR: logger.write(log_level_t::debug, "or"); break; case wotreplay::EQUAL: logger.write(log_level_t::debug, "="); break; case wotreplay::NOT_EQUAL: logger.write(log_level_t::debug, "!="); break; case wotreplay::GREATER_THAN: logger.write(log_level_t::debug, ">"); break; case wotreplay::GREATER_THAN_OR_EQUAL: logger.write(log_level_t::debug, ">="); break; case wotreplay::LESS_THAN: logger.write(log_level_t::debug, "<"); break; case wotreplay::LESS_THAN_OR_EQUAL: logger.write(log_level_t::debug, "<="); break; default: break; } } void operator()(operation_t operation) { logger.write(log_level_t::debug, "("); (*this)(operation.op); logger.write(log_level_t::debug, ", "); boost::apply_visitor(*this, operation.left); logger.write(log_level_t::debug, ", "); boost::apply_visitor(*this, operation.right); logger.write(log_level_t::debug, ")"); } void operator()(draw_rule_t &rule) { indent++; pad(); logger.writef(log_level_t::debug, "Color: #%1$06x\n", rule.color); pad(); logger.write(log_level_t::debug, "Expression: "); (*this)(rule.expr); logger.write(log_level_t::debug, "\n"); indent--; } void pad() { std::string pad(indent * 3, ' '); logger.write(log_level_t::debug, pad); } draw_rules_t rules; int indent = 0; }; void wotreplay::print(const draw_rules_t& rules) { printer p(rules); p(); } virtual_machine::virtual_machine(const game_t &game, const draw_rules_t &rules) : rules(rules), game(game) {} int virtual_machine::operator()(const packet_t &packet) { this->p = &packet; for (int i = 0; i < rules.rules.size(); i += 1) { if ((*this)(rules.rules[i])) return i; } return -1; } bool virtual_machine::operator()(const draw_rule_t rule) { return (*this)(rule.expr) == "true"; } std::string virtual_machine::operator()(nil_t nil) { return "(nil)"; } std::string virtual_machine::operator()(std::string str) { return "'" + str + "'"; } std::string virtual_machine::operator()(symbol_t symbol) { switch(symbol) { case symbol_t::PLAYER: return p->has_property(property_t::player_id) ? boost::lexical_cast<std::string>(p->player_id()) : ""; case symbol_t::TEAM: return p->has_property(property_t::player_id) ? boost::lexical_cast<std::string>(game.get_team_id(p->player_id())) : ""; case symbol_t::CLOCK: return p->has_property(property_t::clock) ? boost::lexical_cast<std::string>(p->clock()) : ""; default: return ""; } } std::string virtual_machine::operator()(operation_t operation) { std::string lhs = boost::apply_visitor(*this, operation.left); std::string rhs = boost::apply_visitor(*this, operation.right); bool result = false; switch(operation.op) { case operator_t::EQUAL: result = lhs == rhs; break; case operator_t::NOT_EQUAL: result = lhs != rhs; break; case operator_t::LESS_THAN: result = boost::lexical_cast<double>(lhs) < boost::lexical_cast<double>(rhs); break; case operator_t::GREATER_THAN: result = boost::lexical_cast<double>(lhs) > boost::lexical_cast<double>(rhs); break; case operator_t::LESS_THAN_OR_EQUAL: result = boost::lexical_cast<double>(lhs) <= boost::lexical_cast<double>(rhs); break; case operator_t::GREATER_THAN_OR_EQUAL: result = boost::lexical_cast<double>(lhs) >= boost::lexical_cast<double>(rhs); break; case operator_t::AND: result = lhs == "true" && rhs == "true"; break; case operator_t::OR: result = lhs == "true" || rhs == "true"; break; default: result = false; } return result ? "true" : "false"; } <commit_msg>#4 Fix error in expression evaluator<commit_after>#include "rule.h" #include "logger.h" #include <boost/fusion/include/adapt_struct.hpp> #include <boost/lexical_cast.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/variant/recursive_variant.hpp> #include <boost/variant/apply_visitor.hpp> using namespace wotreplay; namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; BOOST_FUSION_ADAPT_STRUCT( operation_t, (operator_t, op) (operand_t, left) (operand_t, right) ) BOOST_FUSION_ADAPT_STRUCT( draw_rule_t, (uint32_t, color) (operation_t, expr) ) BOOST_FUSION_ADAPT_STRUCT( draw_rules_t, (std::vector<draw_rule_t>, rules) ) struct error_handler_ { template <typename, typename, typename> struct result { typedef void type; }; template <typename Iterator> void operator()( qi::info const& what , Iterator err_pos, Iterator last) const { std::cout << "Error! Expecting " << what // what failed? << " here: \"" << std::string(err_pos, last) // iterators to error-pos, end << "\"" << std::endl ; } }; boost::phoenix::function<error_handler_> const error_handler = error_handler_(); template<typename Iterator> struct draw_rules_grammar_t : qi::grammar<Iterator, draw_rules_t(), ascii::space_type> { draw_rules_grammar_t() : draw_rules_grammar_t::base_type(rules) { using qi::char_; using namespace qi::labels; using boost::phoenix::at_c; using boost::phoenix::push_back; qi::_2_type _2; qi::_3_type _3; qi::_4_type _4; using qi::on_error; using qi::fail; // define operator operators.add("=" , operator_t::EQUAL) ("!=", operator_t::NOT_EQUAL) (">=", operator_t::GREATER_THAN_OR_EQUAL) (">" , operator_t::GREATER_THAN) ("<=", operator_t::LESS_THAN_OR_EQUAL) ("<" , operator_t::LESS_THAN); // define logical operators logical_operators.add("and", operator_t::AND) ("or" , operator_t::OR); // define symbols symbols.add("player", symbol_t::PLAYER) ("clock" , symbol_t::CLOCK) ("team" , symbol_t::TEAM); rules = rule[push_back(at_c<0>(_val), _1)] >> *(';' >> rule[push_back(at_c<0>(_val), _1)]); rule %= color >> ":=" >> expression; color %= '#' >> qi::hex; expression = (operation[at_c<1>(_val) = _1] >> logical_operators[at_c<0>(_val) = _1] >> expression[at_c<2>(_val) = _1]) | (operation[at_c<1>(_val) = _1] >> logical_operators[at_c<0>(_val) = _1] >> operation[at_c<2>(_val) = _1]) | (operation[_val = _1]); operation = operand [at_c<1>(_val) = _1] > operators[at_c<0>(_val) = _1] > operand [at_c<2>(_val) = _1]; operand %= symbols | value; value = '\'' >> +qi::char_("a-zA-Z0-9\\-_")[_val += _1] >> '\''; // Debugging and error handling and reporting support. BOOST_SPIRIT_DEBUG_NODES( (expression)(operation)(operand)(value)); // Error handling on_error<fail>(expression, error_handler(_4, _3, _2)); } // parsing rules qi::rule<Iterator, draw_rules_t(), ascii::space_type> rules; qi::rule<Iterator, draw_rule_t() , ascii::space_type> rule; qi::rule<Iterator, uint32_t() , ascii::space_type> color; qi::rule<Iterator, operation_t() , ascii::space_type> expression; qi::rule<Iterator, operation_t() , ascii::space_type> operation; qi::rule<Iterator, operand_t() , ascii::space_type> operand; qi::rule<Iterator, std::string() , ascii::space_type> value; // symbol maps qi::symbols<char, operator_t> operators; qi::symbols<char, operator_t> logical_operators; qi::symbols<char, symbol_t> symbols; }; draw_rules_t wotreplay::parse_draw_rules(const std::string &expr) { draw_rules_grammar_t<std::string::const_iterator> grammar; draw_rules_t rules; std::string::const_iterator iter = expr.begin(); std::string::const_iterator end = expr.end(); bool r = qi::phrase_parse(iter, end, grammar, ascii::space, rules); if (r && iter == end) { logger.writef(log_level_t::info, "Parsing succesfull\n"); print(rules); } else { logger.writef(log_level_t::warning, "Parsing failed, remaining: %1%\n", std::string(iter, end)); } return rules; } class printer : public boost::static_visitor<void> { public: printer(const draw_rules_t &rules) : rules(rules) {} void operator()() { logger.writef(log_level_t::info, "Number of rules: %1%\n", rules.rules.size()); for (int i = 0; i < rules.rules.size(); i += 1) { pad(); logger.writef(log_level_t::debug, "Rule #%1%\n", i); (*this)(rules.rules[i]); } } void operator()(std::string str) { logger.writef(log_level_t::debug, "'%1%'", str); } void operator()(nil_t nil) { logger.write(log_level_t::debug, "(nil)"); } void operator()(symbol_t symbol) { switch(symbol) { case wotreplay::PLAYER: logger.write(log_level_t::debug, "PLAYER"); break; case wotreplay::TEAM: logger.write(log_level_t::debug, "TEAM"); break; case wotreplay::CLOCK: logger.write(log_level_t::debug, "CLOCK"); break; default: logger.write(log_level_t::debug, "<invalid symbol>"); break; } } void operator()(operator_t op) { switch(op) { case wotreplay::AND: logger.write(log_level_t::debug, "and"); break; case wotreplay::OR: logger.write(log_level_t::debug, "or"); break; case wotreplay::EQUAL: logger.write(log_level_t::debug, "="); break; case wotreplay::NOT_EQUAL: logger.write(log_level_t::debug, "!="); break; case wotreplay::GREATER_THAN: logger.write(log_level_t::debug, ">"); break; case wotreplay::GREATER_THAN_OR_EQUAL: logger.write(log_level_t::debug, ">="); break; case wotreplay::LESS_THAN: logger.write(log_level_t::debug, "<"); break; case wotreplay::LESS_THAN_OR_EQUAL: logger.write(log_level_t::debug, "<="); break; default: break; } } void operator()(operation_t operation) { logger.write(log_level_t::debug, "("); (*this)(operation.op); logger.write(log_level_t::debug, ", "); boost::apply_visitor(*this, operation.left); logger.write(log_level_t::debug, ", "); boost::apply_visitor(*this, operation.right); logger.write(log_level_t::debug, ")"); } void operator()(draw_rule_t &rule) { indent++; pad(); logger.writef(log_level_t::debug, "Color: #%1$06x\n", rule.color); pad(); logger.write(log_level_t::debug, "Expression: "); (*this)(rule.expr); logger.write(log_level_t::debug, "\n"); indent--; } void pad() { std::string pad(indent * 3, ' '); logger.write(log_level_t::debug, pad); } draw_rules_t rules; int indent = 0; }; void wotreplay::print(const draw_rules_t& rules) { printer p(rules); p(); } virtual_machine::virtual_machine(const game_t &game, const draw_rules_t &rules) : rules(rules), game(game) {} int virtual_machine::operator()(const packet_t &packet) { this->p = &packet; for (int i = 0; i < rules.rules.size(); i += 1) { if ((*this)(rules.rules[i])) return i; } return -1; } bool virtual_machine::operator()(const draw_rule_t rule) { return (*this)(rule.expr) == "true"; } std::string virtual_machine::operator()(nil_t nil) { return "nil"; } std::string virtual_machine::operator()(std::string str) { return str; } std::string virtual_machine::operator()(symbol_t symbol) { switch(symbol) { case symbol_t::PLAYER: return p->has_property(property_t::player_id) ? boost::lexical_cast<std::string>(p->player_id()) : ""; case symbol_t::TEAM: return p->has_property(property_t::player_id) ? boost::lexical_cast<std::string>(game.get_team_id(p->player_id())) : ""; case symbol_t::CLOCK: return p->has_property(property_t::clock) ? boost::lexical_cast<std::string>(p->clock()) : ""; default: return ""; } } std::string virtual_machine::operator()(operation_t operation) { std::string lhs = boost::apply_visitor(*this, operation.left); std::string rhs = boost::apply_visitor(*this, operation.right); bool result = false; switch(operation.op) { case operator_t::EQUAL: result = lhs == rhs; break; case operator_t::NOT_EQUAL: result = lhs != rhs; break; case operator_t::LESS_THAN: result = boost::lexical_cast<double>(lhs) < boost::lexical_cast<double>(rhs); break; case operator_t::GREATER_THAN: result = boost::lexical_cast<double>(lhs) > boost::lexical_cast<double>(rhs); break; case operator_t::LESS_THAN_OR_EQUAL: result = boost::lexical_cast<double>(lhs) <= boost::lexical_cast<double>(rhs); break; case operator_t::GREATER_THAN_OR_EQUAL: result = boost::lexical_cast<double>(lhs) >= boost::lexical_cast<double>(rhs); break; case operator_t::AND: result = lhs == "true" && rhs == "true"; break; case operator_t::OR: result = lhs == "true" || rhs == "true"; break; default: result = false; } return result ? "true" : "false"; } <|endoftext|>
<commit_before>#include <unistd.h> #include <errno.h> #include <sys/stat.h> #include <string.h> #include <time.h> #include <stdlib.h> #include "game.h" #include "io.h" #include "os.h" #include "wizard.h" #include "rogue.h" #include "level.h" #include "death.h" #include "score.h" #define LOCKFILE ".rogue14_lockfile" struct score { unsigned uid; int score; int flags; int death_type; char name[MAXSTR]; int level; unsigned time; }; static FILE* scoreboard = nullptr; /* File descriptor for score file */ static FILE* lock = nullptr; static bool lock_sc(void) { lock = fopen(LOCKFILE, "w+"); if (lock != nullptr) return true; for (int cnt = 0; cnt < 5; cnt++) { sleep(1); lock = fopen(LOCKFILE, "w+"); if (lock != nullptr) return true; } struct stat sbuf; if (stat(LOCKFILE, &sbuf) < 0) { lock = fopen(LOCKFILE, "w+"); return true; } if (time(nullptr) - sbuf.st_mtime > 10) return unlink(LOCKFILE) < 0 ? false : lock_sc(); printf("The score file is very busy. Do you want to wait longer\n" "for it to become free so your score can get posted?\n" "If so, type \"y\"\n"); return Game::io->readchar(true) == 'y' ? lock_sc() : false; } static void unlock_sc(void) { if (lock != nullptr) fclose(lock); lock = nullptr; unlink(LOCKFILE); } static void score_read(struct score* top_ten) { if (scoreboard == nullptr || !lock_sc()) return; rewind(scoreboard); for (unsigned i = 0; i < SCORE_MAX; i++) { char buf[100]; io_encread(top_ten[i].name, MAXSTR, scoreboard); io_encread(buf, sizeof(buf), scoreboard); sscanf(buf, " %u %d %d %d %d %x \n", &top_ten[i].uid, &top_ten[i].score, &top_ten[i].flags, &top_ten[i].death_type, &top_ten[i].level, &top_ten[i].time); } rewind(scoreboard); unlock_sc(); } static void score_write(struct score* top_ten) { if (scoreboard == nullptr || !lock_sc()) return; rewind(scoreboard); for(unsigned i = 0; i < SCORE_MAX; i++) { char buf[100]; io_encwrite(top_ten[i].name, MAXSTR, scoreboard); memset(buf, '\0', sizeof(buf)); sprintf(buf, " %u %d %d %d %d %x \n", top_ten[i].uid, top_ten[i].score, top_ten[i].flags, top_ten[i].death_type, top_ten[i].level, top_ten[i].time); io_encwrite(buf, sizeof(buf), scoreboard); } rewind(scoreboard); unlock_sc(); } static void score_insert(struct score* top_ten, int amount, int flags, int death_type) { unsigned uid = getuid(); for (unsigned i = 0; i < SCORE_MAX; ++i) if (amount > top_ten[i].score) { /* Move all scores a step down */ size_t scores_to_move = SCORE_MAX - i - 1; memmove(&top_ten[i +1], &top_ten[i], sizeof(*top_ten) * scores_to_move); /* Add new scores */ top_ten[i].score = amount; strcpy(top_ten[i].name, Game::whoami->c_str()); top_ten[i].flags = flags; top_ten[i].level = Game::current_level; top_ten[i].death_type = death_type; top_ten[i].uid = uid; /* Write score to disk */ score_write(top_ten); break; } } static void score_print(struct score* top_ten) { endwin(); printf("Top %d %s:\n Score Name\n", SCORE_MAX, "Scores"); for (unsigned i = 0; i < SCORE_MAX; ++i) { if (!top_ten[i].score) break; printf("%2d %5d %s: " ,i + 1 /* Position */ ,top_ten[i].score /* Score */ ,top_ten[i].name /* Name */ ); if (top_ten[i].flags == 0) printf("%s", death_reason(top_ten[i].death_type).c_str()); else if (top_ten[i].flags == 1) printf("Quit"); else if (top_ten[i].flags == 2) printf("A total winner"); else if (top_ten[i].flags == 3) printf("%s while holding the amulet", death_reason(top_ten[i].death_type).c_str()); printf(" on level %d.\n", top_ten[i].level); } } int score_open(void) { scoreboard = fopen(SCOREPATH, "r+"); if (scoreboard == nullptr) { fprintf(stderr, "Could not open %s for writing: %s\n" "Your highscore will not be saved if you die!\n" "[Press return key to continue]", SCOREPATH, strerror(errno)); getchar(); return 1; } return 0; } void score_show_and_exit(int amount, int flags, int death_type) { if (flags >= 0 || wizard) { char buf[2*MAXSTR]; mvaddstr(LINES - 1, 0 , "[Press return to continue]"); refresh(); wgetnstr(stdscr, buf, 80); putchar('\n'); } struct score top_ten[SCORE_MAX]; memset(top_ten, 0, SCORE_MAX * sizeof(*top_ten)); score_read(top_ten); /* Insert her in list if need be */ score_insert(top_ten, amount, flags, death_type); /* Print the highscore */ score_print(top_ten); Game::exit(); } void score_win_and_exit(void) { clear(); addstr( " \n" " @ @ @ @ @ @@@ @ @ \n" " @ @ @@ @@ @ @ @ @ \n" " @ @ @@@ @ @ @ @ @ @@@ @@@@ @@@ @ @@@ @ \n" " @@@@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ \n" " @ @ @ @ @ @ @ @@@@ @ @ @@@@@ @ @ @ \n" " @ @ @ @ @ @@ @ @ @ @ @ @ @ @ @ @ \n" " @@@ @@@ @@ @ @ @ @@@@ @@@@ @@@ @@@ @@ @ \n" " \n" " Congratulations, you have made it to the light of day! \n" "\n" "You have joined the elite ranks of those who have escaped the\n" "Dungeons of Doom alive. You journey home and sell all your loot at\n" "a great profit and are admitted to the Fighters' Guild.\n" ); mvaddstr(LINES - 1, 0, "--Press space to continue--"); refresh(); Game::io->wait_for_key(KEY_SPACE); player->give_gold(static_cast<int>(player->pack_print_value())); score_show_and_exit(player->get_gold(), 2, ' '); } <commit_msg>stop wizard from appearing in highscore<commit_after>#include <unistd.h> #include <errno.h> #include <sys/stat.h> #include <string.h> #include <time.h> #include <stdlib.h> #include "game.h" #include "io.h" #include "os.h" #include "wizard.h" #include "rogue.h" #include "level.h" #include "death.h" #include "score.h" #define LOCKFILE ".rogue14_lockfile" struct score { unsigned uid; int score; int flags; int death_type; char name[MAXSTR]; int level; unsigned time; }; static FILE* scoreboard = nullptr; /* File descriptor for score file */ static FILE* lock = nullptr; static bool lock_sc(void) { lock = fopen(LOCKFILE, "w+"); if (lock != nullptr) return true; for (int cnt = 0; cnt < 5; cnt++) { sleep(1); lock = fopen(LOCKFILE, "w+"); if (lock != nullptr) return true; } struct stat sbuf; if (stat(LOCKFILE, &sbuf) < 0) { lock = fopen(LOCKFILE, "w+"); return true; } if (time(nullptr) - sbuf.st_mtime > 10) return unlink(LOCKFILE) < 0 ? false : lock_sc(); printf("The score file is very busy. Do you want to wait longer\n" "for it to become free so your score can get posted?\n" "If so, type \"y\"\n"); return Game::io->readchar(true) == 'y' ? lock_sc() : false; } static void unlock_sc(void) { if (lock != nullptr) fclose(lock); lock = nullptr; unlink(LOCKFILE); } static void score_read(struct score* top_ten) { if (scoreboard == nullptr || !lock_sc()) return; rewind(scoreboard); for (unsigned i = 0; i < SCORE_MAX; i++) { char buf[100]; io_encread(top_ten[i].name, MAXSTR, scoreboard); io_encread(buf, sizeof(buf), scoreboard); sscanf(buf, " %u %d %d %d %d %x \n", &top_ten[i].uid, &top_ten[i].score, &top_ten[i].flags, &top_ten[i].death_type, &top_ten[i].level, &top_ten[i].time); } rewind(scoreboard); unlock_sc(); } static void score_write(struct score* top_ten) { if (scoreboard == nullptr || !lock_sc()) return; rewind(scoreboard); for(unsigned i = 0; i < SCORE_MAX; i++) { char buf[100]; io_encwrite(top_ten[i].name, MAXSTR, scoreboard); memset(buf, '\0', sizeof(buf)); sprintf(buf, " %u %d %d %d %d %x \n", top_ten[i].uid, top_ten[i].score, top_ten[i].flags, top_ten[i].death_type, top_ten[i].level, top_ten[i].time); io_encwrite(buf, sizeof(buf), scoreboard); } rewind(scoreboard); unlock_sc(); } static void score_insert(struct score* top_ten, int amount, int flags, int death_type) { unsigned uid = getuid(); for (unsigned i = 0; i < SCORE_MAX; ++i) if (amount > top_ten[i].score) { /* Move all scores a step down */ size_t scores_to_move = SCORE_MAX - i - 1; memmove(&top_ten[i +1], &top_ten[i], sizeof(*top_ten) * scores_to_move); /* Add new scores */ top_ten[i].score = amount; strcpy(top_ten[i].name, Game::whoami->c_str()); top_ten[i].flags = flags; top_ten[i].level = Game::current_level; top_ten[i].death_type = death_type; top_ten[i].uid = uid; /* Write score to disk */ score_write(top_ten); break; } } static void score_print(struct score* top_ten) { endwin(); printf("Top %d %s:\n Score Name\n", SCORE_MAX, "Scores"); for (unsigned i = 0; i < SCORE_MAX; ++i) { if (!top_ten[i].score) break; printf("%2d %5d %s: " ,i + 1 /* Position */ ,top_ten[i].score /* Score */ ,top_ten[i].name /* Name */ ); if (top_ten[i].flags == 0) printf("%s", death_reason(top_ten[i].death_type).c_str()); else if (top_ten[i].flags == 1) printf("Quit"); else if (top_ten[i].flags == 2) printf("A total winner"); else if (top_ten[i].flags == 3) printf("%s while holding the amulet", death_reason(top_ten[i].death_type).c_str()); printf(" on level %d.\n", top_ten[i].level); } } int score_open(void) { scoreboard = fopen(SCOREPATH, "r+"); if (scoreboard == nullptr) { fprintf(stderr, "Could not open %s for writing: %s\n" "Your highscore will not be saved if you die!\n" "[Press return key to continue]", SCOREPATH, strerror(errno)); getchar(); return 1; } return 0; } void score_show_and_exit(int amount, int flags, int death_type) { if (flags >= 0 || wizard) { char buf[2*MAXSTR]; mvaddstr(LINES - 1, 0 , "[Press return to continue]"); refresh(); wgetnstr(stdscr, buf, 80); putchar('\n'); } struct score top_ten[SCORE_MAX]; memset(top_ten, 0, SCORE_MAX * sizeof(*top_ten)); score_read(top_ten); /* Insert her in list if need be */ if (!wizard) { score_insert(top_ten, amount, flags, death_type); } /* Print the highscore */ score_print(top_ten); Game::exit(); } void score_win_and_exit(void) { clear(); addstr( " \n" " @ @ @ @ @ @@@ @ @ \n" " @ @ @@ @@ @ @ @ @ \n" " @ @ @@@ @ @ @ @ @ @@@ @@@@ @@@ @ @@@ @ \n" " @@@@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ \n" " @ @ @ @ @ @ @ @@@@ @ @ @@@@@ @ @ @ \n" " @ @ @ @ @ @@ @ @ @ @ @ @ @ @ @ @ \n" " @@@ @@@ @@ @ @ @ @@@@ @@@@ @@@ @@@ @@ @ \n" " \n" " Congratulations, you have made it to the light of day! \n" "\n" "You have joined the elite ranks of those who have escaped the\n" "Dungeons of Doom alive. You journey home and sell all your loot at\n" "a great profit and are admitted to the Fighters' Guild.\n" ); mvaddstr(LINES - 1, 0, "--Press space to continue--"); refresh(); Game::io->wait_for_key(KEY_SPACE); player->give_gold(static_cast<int>(player->pack_print_value())); score_show_and_exit(player->get_gold(), 2, ' '); } <|endoftext|>
<commit_before>// // Copyright (c) 2014,2015,2016, 2018 CNRS // Authors: Florent Lamiraux, Joseph Mirabel, Diane Bury // // This file is part of hpp-core // hpp-core 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. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #include <hpp/core/continuous-validation/solid-solid-collision.hh> #include <pinocchio/multibody/model.hpp> #include <hpp/fcl/collision_data.h> #include <hpp/fcl/collision.h> #include <hpp/pinocchio/body.hh> #include <hpp/pinocchio/collision-object.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/device.hh> #include <hpp/core/deprecated.hh> namespace hpp { namespace core { namespace continuousValidation { SolidSolidCollisionPtr_t SolidSolidCollision::create(const JointPtr_t& joint_a, const ConstObjectStdVector_t& objects_b, value_type tolerance) { SolidSolidCollision* ptr (new SolidSolidCollision(joint_a, objects_b, tolerance)); SolidSolidCollisionPtr_t shPtr(ptr); ptr->init(shPtr); return shPtr; } SolidSolidCollisionPtr_t SolidSolidCollision::create(const JointPtr_t& joint_a, const JointPtr_t& joint_b, value_type tolerance) { SolidSolidCollision* ptr = new SolidSolidCollision (joint_a, joint_b, tolerance); SolidSolidCollisionPtr_t shPtr (ptr); ptr->init(shPtr); return shPtr; } SolidSolidCollisionPtr_t SolidSolidCollision::createCopy (const SolidSolidCollisionPtr_t& other) { SolidSolidCollision* ptr = new SolidSolidCollision (*other); SolidSolidCollisionPtr_t shPtr (ptr); ptr->init(shPtr); return shPtr; } IntervalValidationPtr_t SolidSolidCollision::copy () const { return createCopy(weak_.lock()); } value_type SolidSolidCollision::computeMaximalVelocity(vector_t& Vb) const { value_type maximalVelocity_a_b = 0; for (const auto& coeff : m_->coefficients) { const JointPtr_t& joint = coeff.joint_; maximalVelocity_a_b += coeff.value_ * Vb.segment(joint->rankInVelocity(), joint->numberDof()).norm(); } if(m_->joint_b) { value_type maximalVelocity_b_a = 0; for (const auto& coeff : m_->coefficients_reverse) { const JointPtr_t& joint = coeff.joint_; maximalVelocity_b_a += coeff.value_ * Vb.segment(joint->rankInVelocity(), joint->numberDof()).norm(); } if (maximalVelocity_b_a < maximalVelocity_a_b) { return maximalVelocity_b_a; } } return maximalVelocity_a_b; } bool SolidSolidCollision::removeObjectTo_b (const CollisionObjectConstPtr_t& object) { CollisionPairs_t& prs (pairs()); CollisionRequests_t& rqsts (requests()); const int s = (int)prs.size(); // Remove all reference to object int last = 0; for (int i = 0; i < s; ++i) { if (object != prs[i].second) { // Different -> keep if (last != i) { // If one has been removed, then move. prs[last] = std::move(prs[i]); rqsts[last] = std::move(rqsts[i]); } last++; } } prs.erase(prs.begin() + last, prs.end()); rqsts.erase(rqsts.begin() + last, rqsts.end()); return last != s; } void SolidSolidCollision::addCollisionPair (const CollisionObjectConstPtr_t& left, const CollisionObjectConstPtr_t& right) { // std::cout << "size = " << pairs().size() << std::endl; // std::cout << "capacity = " << pairs().capacity() << std::endl; pairs().emplace_back (left, right); requests().emplace_back (fcl::DISTANCE_LOWER_BOUND, 1); requests().back().enable_cached_gjk_guess = true; } std::string SolidSolidCollision::name () const { std::ostringstream oss; oss << "(" << m_->joint_a->name () << ","; if (m_->joint_b) oss << m_->joint_b->name (); else oss << "obstacles"; oss << ")"; return oss.str (); } std::ostream& SolidSolidCollision::print (std::ostream& os) const { const pinocchio::Model& model = joint_a()->robot ()->model(); os << "SolidSolidCollision: " << m_->joint_a->name() << " - " << (m_->joint_b ? m_->joint_b->name() : model.names[0]) << '\n'; JointIndices_t joints = m_->computeSequenceOfJoints (); for (auto i : joints) os << model.names[i] << ", "; os << '\n'; for (std::size_t i = 0; i < m_->coefficients.size(); ++i) os << m_->coefficients[i].value_ << ", "; return os; } SolidSolidCollision::JointIndices_t SolidSolidCollision::Model::computeSequenceOfJoints () const { JointIndices_t joints; assert(joint_a); const pinocchio::Model& model = joint_a->robot ()->model(); const JointIndex id_a = joint_a->index(), id_b = (joint_b ? joint_b->index() : 0); JointIndex ia = id_a, ib = id_b; std::vector<JointIndex> fromA, fromB; while (ia != ib) { if (ia > ib) { fromA.push_back(ia); ia = model.parents[ia]; } else /* if (ia < ib) */ { fromB.push_back(ib); ib = model.parents[ib]; } } assert (ia == ib); fromA.push_back(ia); // Check joint vectors if (fromB.empty()) assert (fromA.back() == id_b); else assert (model.parents[fromB.back()] == ia); // Build sequence joints = std::move(fromA); joints.insert(joints.end(), fromB.rbegin(), fromB.rend()); assert(joints.front() == id_a); assert(joints.back() == id_b); assert(joints.size() > 1); return joints; } CoefficientVelocities_t SolidSolidCollision::Model::computeCoefficients(const JointIndices_t& joints) const { const pinocchio::Model& model = joint_a->robot ()->model(); JointPtr_t child; assert (joints.size () > 1); CoefficientVelocities_t coeff; coeff.resize (joints.size () - 1); pinocchio::DevicePtr_t robot =joint_a->robot (); // Store r0 + sum of T_{i/i+1} in a variable value_type cumulativeLength = joint_a->linkedBody ()->radius (); value_type distance; std::size_t i = 0; while (i + 1 < joints.size()) { if (model.parents[joints[i]] == joints[i+1]) child = Joint::create (robot, joints[i]); else if (model.parents[joints[i+1]] == joints[i]) child = Joint::create (robot, joints[i+1]); else abort (); assert(child); coeff [i].joint_ = child; // Go through all known types of joints // TODO: REPLACE THESE FUNCTIONS WITH NEW API distance = child->maximalDistanceToParent (); coeff [i].value_ = child->upperBoundLinearVelocity () + cumulativeLength * child->upperBoundAngularVelocity (); cumulativeLength += distance; ++i; } return coeff; } void SolidSolidCollision::Model::setCoefficients (const JointIndices_t& joints) { // Compute coefficients going from joint a to joint b coefficients = computeCoefficients (joints); // Compute coefficients going from joint b to joint a if(joint_b) { JointIndices_t joints_reverse(joints); std::reverse(joints_reverse.begin(),joints_reverse.end()); coefficients_reverse = computeCoefficients (joints_reverse); } } SolidSolidCollision::SolidSolidCollision (const JointPtr_t& joint_a, const JointPtr_t& joint_b, value_type tolerance) : BodyPairCollision(tolerance), m_ (new Model) { m_->joint_a = joint_a; m_->joint_b = joint_b; assert (joint_a); if (joint_b && joint_b->robot () != joint_a->robot ()) { throw std::runtime_error ("Joints do not belong to the same device."); } if (indexJointA() == indexJointB()) { throw std::runtime_error ("Bodies should be different"); } if (tolerance < 0) { throw std::runtime_error ("tolerance should be non-negative."); } if (joint_a) { assert(joint_a->linkedBody ()); } if (joint_b) { assert(joint_b->linkedBody ()); } // Find sequence of joints JointIndices_t joints (m_->computeSequenceOfJoints ()); m_->setCoefficients (joints); } SolidSolidCollision::SolidSolidCollision (const JointPtr_t& joint_a, const ConstObjectStdVector_t& objects_b, value_type tolerance) : BodyPairCollision(tolerance), m_ (new Model) { m_->joint_a = joint_a; assert (joint_a); BodyPtr_t body_a = joint_a->linkedBody (); assert (body_a); for (size_type i = 0; i < body_a->nbInnerObjects(); ++i) { CollisionObjectConstPtr_t obj = body_a->innerObjectAt(i); for (ConstObjectStdVector_t::const_iterator it = objects_b.begin (); it != objects_b.end (); ++it) { assert (!(*it)->joint () || (*it)->joint ()->robot () != joint_a->robot ()); addCollisionPair(obj, *it); } } // Find sequence of joints JointIndices_t joints (m_->computeSequenceOfJoints ()); m_->computeCoefficients (joints); } void SolidSolidCollision::init(const SolidSolidCollisionWkPtr_t& weak) { weak_ = weak; } } // namespace continuousValidation } // namespace core } // namespace hpp <commit_msg>[continuousValidation] Fix computation of coefficients<commit_after>// // Copyright (c) 2014,2015,2016, 2018 CNRS // Authors: Florent Lamiraux, Joseph Mirabel, Diane Bury // // This file is part of hpp-core // hpp-core 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. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #include <hpp/core/continuous-validation/solid-solid-collision.hh> #include <pinocchio/multibody/model.hpp> #include <hpp/fcl/collision_data.h> #include <hpp/fcl/collision.h> #include <hpp/pinocchio/body.hh> #include <hpp/pinocchio/collision-object.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/device.hh> #include <hpp/core/deprecated.hh> namespace hpp { namespace core { namespace continuousValidation { SolidSolidCollisionPtr_t SolidSolidCollision::create(const JointPtr_t& joint_a, const ConstObjectStdVector_t& objects_b, value_type tolerance) { SolidSolidCollision* ptr (new SolidSolidCollision(joint_a, objects_b, tolerance)); SolidSolidCollisionPtr_t shPtr(ptr); ptr->init(shPtr); return shPtr; } SolidSolidCollisionPtr_t SolidSolidCollision::create(const JointPtr_t& joint_a, const JointPtr_t& joint_b, value_type tolerance) { SolidSolidCollision* ptr = new SolidSolidCollision (joint_a, joint_b, tolerance); SolidSolidCollisionPtr_t shPtr (ptr); ptr->init(shPtr); return shPtr; } SolidSolidCollisionPtr_t SolidSolidCollision::createCopy (const SolidSolidCollisionPtr_t& other) { SolidSolidCollision* ptr = new SolidSolidCollision (*other); SolidSolidCollisionPtr_t shPtr (ptr); ptr->init(shPtr); return shPtr; } IntervalValidationPtr_t SolidSolidCollision::copy () const { return createCopy(weak_.lock()); } value_type SolidSolidCollision::computeMaximalVelocity(vector_t& Vb) const { value_type maximalVelocity_a_b = 0; for (const auto& coeff : m_->coefficients) { const JointPtr_t& joint = coeff.joint_; maximalVelocity_a_b += coeff.value_ * Vb.segment(joint->rankInVelocity(), joint->numberDof()).norm(); } if(m_->joint_b) { value_type maximalVelocity_b_a = 0; for (const auto& coeff : m_->coefficients_reverse) { const JointPtr_t& joint = coeff.joint_; maximalVelocity_b_a += coeff.value_ * Vb.segment(joint->rankInVelocity(), joint->numberDof()).norm(); } if (maximalVelocity_b_a < maximalVelocity_a_b) { return maximalVelocity_b_a; } } return maximalVelocity_a_b; } bool SolidSolidCollision::removeObjectTo_b (const CollisionObjectConstPtr_t& object) { CollisionPairs_t& prs (pairs()); CollisionRequests_t& rqsts (requests()); const int s = (int)prs.size(); // Remove all reference to object int last = 0; for (int i = 0; i < s; ++i) { if (object != prs[i].second) { // Different -> keep if (last != i) { // If one has been removed, then move. prs[last] = std::move(prs[i]); rqsts[last] = std::move(rqsts[i]); } last++; } } prs.erase(prs.begin() + last, prs.end()); rqsts.erase(rqsts.begin() + last, rqsts.end()); return last != s; } void SolidSolidCollision::addCollisionPair (const CollisionObjectConstPtr_t& left, const CollisionObjectConstPtr_t& right) { // std::cout << "size = " << pairs().size() << std::endl; // std::cout << "capacity = " << pairs().capacity() << std::endl; pairs().emplace_back (left, right); requests().emplace_back (fcl::DISTANCE_LOWER_BOUND, 1); requests().back().enable_cached_gjk_guess = true; } std::string SolidSolidCollision::name () const { std::ostringstream oss; oss << "(" << m_->joint_a->name () << ","; if (m_->joint_b) oss << m_->joint_b->name (); else oss << "obstacles"; oss << ")"; return oss.str (); } std::ostream& SolidSolidCollision::print (std::ostream& os) const { const pinocchio::Model& model = joint_a()->robot ()->model(); os << "SolidSolidCollision: " << m_->joint_a->name() << " - " << (m_->joint_b ? m_->joint_b->name() : model.names[0]) << '\n'; JointIndices_t joints = m_->computeSequenceOfJoints (); for (auto i : joints) os << model.names[i] << ", "; os << '\n'; for (std::size_t i = 0; i < m_->coefficients.size(); ++i) os << m_->coefficients[i].value_ << ", "; return os; } SolidSolidCollision::JointIndices_t SolidSolidCollision::Model::computeSequenceOfJoints () const { JointIndices_t joints; assert(joint_a); const pinocchio::Model& model = joint_a->robot ()->model(); const JointIndex id_a = joint_a->index(), id_b = (joint_b ? joint_b->index() : 0); JointIndex ia = id_a, ib = id_b; std::vector<JointIndex> fromA, fromB; while (ia != ib) { if (ia > ib) { fromA.push_back(ia); ia = model.parents[ia]; } else /* if (ia < ib) */ { fromB.push_back(ib); ib = model.parents[ib]; } } assert (ia == ib); fromA.push_back(ia); // Check joint vectors if (fromB.empty()) assert (fromA.back() == id_b); else assert (model.parents[fromB.back()] == ia); // Build sequence joints = std::move(fromA); joints.insert(joints.end(), fromB.rbegin(), fromB.rend()); assert(joints.front() == id_a); assert(joints.back() == id_b); assert(joints.size() > 1); return joints; } CoefficientVelocities_t SolidSolidCollision::Model::computeCoefficients(const JointIndices_t& joints) const { const pinocchio::Model& model = joint_a->robot ()->model(); JointPtr_t child; assert (joints.size () > 1); CoefficientVelocities_t coeff; coeff.resize (joints.size () - 1); pinocchio::DevicePtr_t robot =joint_a->robot (); // Store r0 + sum of T_{i/i+1} in a variable value_type cumulativeLength = joint_a->linkedBody ()->radius (); value_type distance; std::size_t i = 0; while (i + 1 < joints.size()) { if (model.parents[joints[i]] == joints[i+1]) child = Joint::create (robot, joints[i]); else if (model.parents[joints[i+1]] == joints[i]) child = Joint::create (robot, joints[i+1]); else abort (); assert(child); coeff [i].joint_ = child; // Go through all known types of joints // TODO: REPLACE THESE FUNCTIONS WITH NEW API distance = child->maximalDistanceToParent (); coeff [i].value_ = child->upperBoundLinearVelocity () + cumulativeLength * child->upperBoundAngularVelocity (); cumulativeLength += distance; ++i; } return coeff; } void SolidSolidCollision::Model::setCoefficients (const JointIndices_t& joints) { // Compute coefficients going from joint a to joint b coefficients = computeCoefficients (joints); // Compute coefficients going from joint b to joint a if(joint_b) { JointIndices_t joints_reverse(joints); std::reverse(joints_reverse.begin(),joints_reverse.end()); coefficients_reverse = computeCoefficients (joints_reverse); } } SolidSolidCollision::SolidSolidCollision (const JointPtr_t& joint_a, const JointPtr_t& joint_b, value_type tolerance) : BodyPairCollision(tolerance), m_ (new Model) { m_->joint_a = joint_a; m_->joint_b = joint_b; assert (joint_a); if (joint_b && joint_b->robot () != joint_a->robot ()) { throw std::runtime_error ("Joints do not belong to the same device."); } if (indexJointA() == indexJointB()) { throw std::runtime_error ("Bodies should be different"); } if (tolerance < 0) { throw std::runtime_error ("tolerance should be non-negative."); } if (joint_a) { assert(joint_a->linkedBody ()); } if (joint_b) { assert(joint_b->linkedBody ()); } // Find sequence of joints JointIndices_t joints (m_->computeSequenceOfJoints ()); m_->setCoefficients (joints); } SolidSolidCollision::SolidSolidCollision (const JointPtr_t& joint_a, const ConstObjectStdVector_t& objects_b, value_type tolerance) : BodyPairCollision(tolerance), m_ (new Model) { m_->joint_a = joint_a; assert (joint_a); BodyPtr_t body_a = joint_a->linkedBody (); assert (body_a); for (size_type i = 0; i < body_a->nbInnerObjects(); ++i) { CollisionObjectConstPtr_t obj = body_a->innerObjectAt(i); for (ConstObjectStdVector_t::const_iterator it = objects_b.begin (); it != objects_b.end (); ++it) { assert (!(*it)->joint () || (*it)->joint ()->robot () != joint_a->robot ()); addCollisionPair(obj, *it); } } // Find sequence of joints JointIndices_t joints (m_->computeSequenceOfJoints ()); m_->setCoefficients (joints); } void SolidSolidCollision::init(const SolidSolidCollisionWkPtr_t& weak) { weak_ = weak; } } // namespace continuousValidation } // namespace core } // namespace hpp <|endoftext|>
<commit_before>#include <cubez/cubez.h> #include <cubez/utils.h> #include "defs.h" #include "private_universe.h" #include "byte_vector.h" #include "component.h" #include "system_impl.h" #include "utils_internal.h" #include "coro_scheduler.h" #define AS_PRIVATE(expr) ((PrivateUniverse*)(universe_->self))->expr const qbVar qbNone = { QB_TAG_VOID, 0 }; const qbVar qbUnset = { QB_TAG_UNSET, 0 }; static qbUniverse* universe_ = nullptr; Coro main; CoroScheduler* coro_scheduler; qbResult qb_init(qbUniverse* u) { utils_initialize(); universe_ = u; universe_->self = new PrivateUniverse(); main = coro_initialize(); coro_scheduler = new CoroScheduler(4); return AS_PRIVATE(init()); } qbResult qb_start() { return AS_PRIVATE(start()); } qbResult qb_stop() { qbResult ret = AS_PRIVATE(stop()); universe_ = nullptr; return ret; } qbResult qb_loop() { qbResult result = AS_PRIVATE(loop()); coro_scheduler->run_sync(); return result; } qbId qb_create_program(const char* name) { return AS_PRIVATE(create_program(name)); } qbResult qb_run_program(qbId program) { return AS_PRIVATE(run_program(program)); } qbResult qb_detach_program(qbId program) { return AS_PRIVATE(detach_program(program)); } qbResult qb_join_program(qbId program) { return AS_PRIVATE(join_program(program)); } qbResult qb_system_enable(qbSystem system) { return AS_PRIVATE(enable_system(system)); } qbResult qb_system_disable(qbSystem system) { return AS_PRIVATE(disable_system(system)); } qbResult qb_componentattr_create(qbComponentAttr* attr) { *attr = (qbComponentAttr)calloc(1, sizeof(qbComponentAttr_)); new (*attr) qbComponentAttr_; (*attr)->is_shared = false; (*attr)->type = qbComponentType::QB_COMPONENT_TYPE_RAW; return qbResult::QB_OK; } qbResult qb_componentattr_destroy(qbComponentAttr* attr) { delete *attr; *attr = nullptr; return qbResult::QB_OK; } qbResult qb_componentattr_setdatasize(qbComponentAttr attr, size_t size) { attr->data_size = size; return qbResult::QB_OK; } qbResult qb_componentattr_settype(qbComponentAttr attr, qbComponentType type) { attr->type = type; return qbResult::QB_OK; } qbResult qb_componentattr_setshared(qbComponentAttr attr) { attr->is_shared = true; return qbResult::QB_OK; } qbResult qb_component_create( qbComponent* component, qbComponentAttr attr) { return AS_PRIVATE(component_create(component, attr)); } qbResult qb_component_destroy(qbComponent*) { return qbResult::QB_OK; } size_t qb_component_getcount(qbComponent component) { return AS_PRIVATE(component_getcount(component)); } qbResult qb_entityattr_create(qbEntityAttr* attr) { *attr = (qbEntityAttr)calloc(1, sizeof(qbEntityAttr_)); new (*attr) qbEntityAttr_; return qbResult::QB_OK; } qbResult qb_entityattr_destroy(qbEntityAttr* attr) { delete *attr; *attr = nullptr; return qbResult::QB_OK; } qbResult qb_entityattr_addcomponent(qbEntityAttr attr, qbComponent component, void* instance_data) { attr->component_list.push_back({component, instance_data}); return qbResult::QB_OK; } qbResult qb_entity_create(qbEntity* entity, qbEntityAttr attr) { return AS_PRIVATE(entity_create(entity, *attr)); } qbResult qb_entity_destroy(qbEntity entity) { return AS_PRIVATE(entity_destroy(entity)); } bool qb_entity_hascomponent(qbEntity entity, qbComponent component) { return AS_PRIVATE(entity_hascomponent(entity, component)); } qbResult qb_entity_addcomponent(qbEntity entity, qbComponent component, void* instance_data) { return AS_PRIVATE(entity_addcomponent(entity, component, instance_data)); } qbResult qb_entity_removecomponent(qbEntity entity, qbComponent component) { return AS_PRIVATE(entity_removecomponent(entity, component)); } qbId qb_entity_getid(qbEntity entity) { return entity; } qbResult qb_barrier_create(qbBarrier* barrier) { *barrier = AS_PRIVATE(barrier_create()); return QB_OK; } qbResult qb_barrier_destroy(qbBarrier* barrier) { AS_PRIVATE(barrier_destroy(*barrier)); return QB_OK; } qbResult qb_systemattr_create(qbSystemAttr* attr) { *attr = (qbSystemAttr)calloc(1, sizeof(qbSystemAttr_)); new (*attr) qbSystemAttr_; return qbResult::QB_OK; } qbResult qb_systemattr_destroy(qbSystemAttr* attr) { delete *attr; *attr = nullptr; return qbResult::QB_OK; } qbResult qb_systemattr_setprogram(qbSystemAttr attr, qbId program) { attr->program = program; return qbResult::QB_OK; } qbResult qb_systemattr_addconst(qbSystemAttr attr, qbComponent component) { attr->constants.push_back(component); attr->components.push_back(component); return qbResult::QB_OK; } qbResult qb_systemattr_addmutable(qbSystemAttr attr, qbComponent component) { attr->mutables.push_back(component); attr->components.push_back(component); return qbResult::QB_OK; } qbResult qb_systemattr_setfunction(qbSystemAttr attr, qbTransform transform) { attr->transform = transform; return qbResult::QB_OK; } qbResult qb_systemattr_setcallback(qbSystemAttr attr, qbCallback callback) { attr->callback = callback; return qbResult::QB_OK; } qbResult qb_systemattr_setcondition(qbSystemAttr attr, qbCondition condition) { attr->condition = condition; return qbResult::QB_OK; } qbResult qb_systemattr_settrigger(qbSystemAttr attr, qbTrigger trigger) { attr->trigger = trigger; return qbResult::QB_OK; } qbResult qb_systemattr_setpriority(qbSystemAttr attr, int16_t priority) { attr->priority = priority; return qbResult::QB_OK; } qbResult qb_systemattr_setjoin(qbSystemAttr attr, qbComponentJoin join) { attr->join = join; return qbResult::QB_OK; } qbResult qb_systemattr_setuserstate(qbSystemAttr attr, void* state) { attr->state = state; return qbResult::QB_OK; } qbResult qb_systemattr_addbarrier(qbSystemAttr attr, qbBarrier barrier) { qbTicket_* t = new qbTicket_; t->impl = ((Barrier*)barrier->impl)->MakeTicket().release(); t->lock = [ticket{ t->impl }]() { ((Barrier::Ticket*)ticket)->lock(); }; t->unlock = [ticket{ t->impl }]() { ((Barrier::Ticket*)ticket)->unlock(); }; attr->tickets.push_back(t); return QB_OK; } qbResult qb_system_create(qbSystem* system, qbSystemAttr attr) { if (!attr->program) { attr->program = 0; } #ifdef __ENGINE_DEBUG__ DEBUG_ASSERT(attr->transform || attr->callback, qbResult::QB_ERROR_SYSTEMATTR_HAS_FUNCTION_OR_CALLBACK); #endif AS_PRIVATE(system_create(system, *attr)); return qbResult::QB_OK; } qbResult qb_system_destroy(qbSystem*) { return qbResult::QB_OK; } qbResult qb_eventattr_create(qbEventAttr* attr) { *attr = (qbEventAttr)calloc(1, sizeof(qbEventAttr_)); new (*attr) qbEventAttr_; return qbResult::QB_OK; } qbResult qb_eventattr_destroy(qbEventAttr* attr) { delete *attr; *attr = nullptr; return qbResult::QB_OK; } qbResult qb_eventattr_setprogram(qbEventAttr attr, qbId program) { attr->program = program; return qbResult::QB_OK; } qbResult qb_eventattr_setmessagesize(qbEventAttr attr, size_t size) { attr->message_size = size; return qbResult::QB_OK; } qbResult qb_event_create(qbEvent* event, qbEventAttr attr) { if (!attr->program) { attr->program = 0; } #ifdef __ENGINE_DEBUG__ DEBUG_ASSERT(attr->message_size > 0, qbResult::QB_ERROR_EVENTATTR_MESSAGE_SIZE_IS_ZERO); #endif return AS_PRIVATE(event_create(event, attr)); } qbResult qb_event_destroy(qbEvent* event) { return AS_PRIVATE(event_destroy(event)); } qbResult qb_event_flushall(qbProgram program) { return AS_PRIVATE(event_flushall(program)); } qbResult qb_event_subscribe(qbEvent event, qbSystem system) { return AS_PRIVATE(event_subscribe(event, system)); } qbResult qb_event_unsubscribe(qbEvent event, qbSystem system) { return AS_PRIVATE(event_unsubscribe(event, system)); } qbResult qb_event_send(qbEvent event, void* message) { return AS_PRIVATE(event_send(event, message)); } qbResult qb_event_sendsync(qbEvent event, void* message) { return AS_PRIVATE(event_sendsync(event, message)); } qbResult qb_instance_oncreate(qbComponent component, qbInstanceOnCreate on_create) { return AS_PRIVATE(instance_oncreate(component, on_create)); } qbResult qb_instance_ondestroy(qbComponent component, qbInstanceOnDestroy on_destroy) { return AS_PRIVATE(instance_ondestroy(component, on_destroy)); } qbEntity qb_instance_getentity(qbInstance instance) { return instance->entity; } qbResult qb_instance_getconst(qbInstance instance, void* pbuffer) { return AS_PRIVATE(instance_getconst(instance, pbuffer)); } qbResult qb_instance_getmutable(qbInstance instance, void* pbuffer) { return AS_PRIVATE(instance_getmutable(instance, pbuffer)); } qbResult qb_instance_getcomponent(qbInstance instance, qbComponent component, void* pbuffer) { return AS_PRIVATE(instance_getcomponent(instance, component, pbuffer)); } bool qb_instance_hascomponent(qbInstance instance, qbComponent component) { return AS_PRIVATE(instance_hascomponent(instance, component)); } qbResult qb_instance_find(qbComponent component, qbEntity entity, void* pbuffer) { return AS_PRIVATE(instance_find(component, entity, pbuffer)); } qbCoro qb_coro_create(qbVar(*entry)(qbVar var)) { qbCoro ret = new qbCoro_(); ret->ret = qbUnset; ret->main = coro_new(entry); return ret; } qbCoro qb_coro_create_unsafe(qbVar(*entry)(qbVar var), void* stack, size_t stack_size) { qbCoro ret = new qbCoro_(); ret->ret = qbUnset; ret->main = coro_new_unsafe(entry, (uintptr_t)stack, stack_size); return ret; } qbResult qb_coro_destroy(qbCoro* coro) { coro_free((*coro)->main); delete *coro; *coro = nullptr; return QB_OK; } qbVar qb_coro_call(qbCoro coro, qbVar var) { coro->arg = var; return coro_call(coro->main, var); } qbCoro qb_coro_sync(qbVar(*entry)(qbVar), qbVar var) { return coro_scheduler->schedule_sync(entry, var); } qbCoro qb_coro_async(qbVar(*entry)(qbVar), qbVar var) { return coro_scheduler->schedule_async(entry, var); } qbVar qb_coro_await(qbCoro coro) { return coro_scheduler->await(coro); } qbVar qb_coro_peek(qbCoro coro) { return coro_scheduler->peek(coro); } qbVar qb_coro_yield(qbVar var) { return coro_yield(var); } void qb_coro_wait(double seconds) { double start = (double)qb_timer_query() / 1e9; double end = start + seconds; while ((double)qb_timer_query() / 1e9 < end) { qb_coro_yield(qbUnset); } } void qb_coro_waitframes(uint32_t frames) { uint32_t frames_waited = 0; while (frames_waited < frames) { qb_coro_yield(qbUnset); ++frames_waited; } } qbVar qbVoid(void* p) { qbVar v; v.tag = QB_TAG_VOID; v.p = p; return v; } qbVar qbUint(uint64_t u) { qbVar v; v.tag = QB_TAG_UINT; v.u = u; return v; } qbVar qbInt(int64_t i) { qbVar v; v.tag = QB_TAG_INT; v.i = i; return v; } qbVar qbDouble(double d) { qbVar v; v.tag = QB_TAG_DOUBLE; v.d = d; return v; } qbVar qbChar(char c) { qbVar v; v.tag = QB_TAG_CHAR; v.c = c; return v; } <commit_msg>Add qb_coro_done<commit_after>#include <cubez/cubez.h> #include <cubez/utils.h> #include "defs.h" #include "private_universe.h" #include "byte_vector.h" #include "component.h" #include "system_impl.h" #include "utils_internal.h" #include "coro_scheduler.h" #define AS_PRIVATE(expr) ((PrivateUniverse*)(universe_->self))->expr const qbVar qbNone = { QB_TAG_VOID, 0 }; const qbVar qbUnset = { QB_TAG_UNSET, 0 }; static qbUniverse* universe_ = nullptr; Coro main; CoroScheduler* coro_scheduler; qbResult qb_init(qbUniverse* u) { utils_initialize(); universe_ = u; universe_->self = new PrivateUniverse(); main = coro_initialize(); coro_scheduler = new CoroScheduler(4); return AS_PRIVATE(init()); } qbResult qb_start() { return AS_PRIVATE(start()); } qbResult qb_stop() { qbResult ret = AS_PRIVATE(stop()); universe_ = nullptr; return ret; } qbResult qb_loop() { qbResult result = AS_PRIVATE(loop()); coro_scheduler->run_sync(); return result; } qbId qb_create_program(const char* name) { return AS_PRIVATE(create_program(name)); } qbResult qb_run_program(qbId program) { return AS_PRIVATE(run_program(program)); } qbResult qb_detach_program(qbId program) { return AS_PRIVATE(detach_program(program)); } qbResult qb_join_program(qbId program) { return AS_PRIVATE(join_program(program)); } qbResult qb_system_enable(qbSystem system) { return AS_PRIVATE(enable_system(system)); } qbResult qb_system_disable(qbSystem system) { return AS_PRIVATE(disable_system(system)); } qbResult qb_componentattr_create(qbComponentAttr* attr) { *attr = (qbComponentAttr)calloc(1, sizeof(qbComponentAttr_)); new (*attr) qbComponentAttr_; (*attr)->is_shared = false; (*attr)->type = qbComponentType::QB_COMPONENT_TYPE_RAW; return qbResult::QB_OK; } qbResult qb_componentattr_destroy(qbComponentAttr* attr) { delete *attr; *attr = nullptr; return qbResult::QB_OK; } qbResult qb_componentattr_setdatasize(qbComponentAttr attr, size_t size) { attr->data_size = size; return qbResult::QB_OK; } qbResult qb_componentattr_settype(qbComponentAttr attr, qbComponentType type) { attr->type = type; return qbResult::QB_OK; } qbResult qb_componentattr_setshared(qbComponentAttr attr) { attr->is_shared = true; return qbResult::QB_OK; } qbResult qb_component_create( qbComponent* component, qbComponentAttr attr) { return AS_PRIVATE(component_create(component, attr)); } qbResult qb_component_destroy(qbComponent*) { return qbResult::QB_OK; } size_t qb_component_getcount(qbComponent component) { return AS_PRIVATE(component_getcount(component)); } qbResult qb_entityattr_create(qbEntityAttr* attr) { *attr = (qbEntityAttr)calloc(1, sizeof(qbEntityAttr_)); new (*attr) qbEntityAttr_; return qbResult::QB_OK; } qbResult qb_entityattr_destroy(qbEntityAttr* attr) { delete *attr; *attr = nullptr; return qbResult::QB_OK; } qbResult qb_entityattr_addcomponent(qbEntityAttr attr, qbComponent component, void* instance_data) { attr->component_list.push_back({component, instance_data}); return qbResult::QB_OK; } qbResult qb_entity_create(qbEntity* entity, qbEntityAttr attr) { return AS_PRIVATE(entity_create(entity, *attr)); } qbResult qb_entity_destroy(qbEntity entity) { return AS_PRIVATE(entity_destroy(entity)); } bool qb_entity_hascomponent(qbEntity entity, qbComponent component) { return AS_PRIVATE(entity_hascomponent(entity, component)); } qbResult qb_entity_addcomponent(qbEntity entity, qbComponent component, void* instance_data) { return AS_PRIVATE(entity_addcomponent(entity, component, instance_data)); } qbResult qb_entity_removecomponent(qbEntity entity, qbComponent component) { return AS_PRIVATE(entity_removecomponent(entity, component)); } qbId qb_entity_getid(qbEntity entity) { return entity; } qbResult qb_barrier_create(qbBarrier* barrier) { *barrier = AS_PRIVATE(barrier_create()); return QB_OK; } qbResult qb_barrier_destroy(qbBarrier* barrier) { AS_PRIVATE(barrier_destroy(*barrier)); return QB_OK; } qbResult qb_systemattr_create(qbSystemAttr* attr) { *attr = (qbSystemAttr)calloc(1, sizeof(qbSystemAttr_)); new (*attr) qbSystemAttr_; return qbResult::QB_OK; } qbResult qb_systemattr_destroy(qbSystemAttr* attr) { delete *attr; *attr = nullptr; return qbResult::QB_OK; } qbResult qb_systemattr_setprogram(qbSystemAttr attr, qbId program) { attr->program = program; return qbResult::QB_OK; } qbResult qb_systemattr_addconst(qbSystemAttr attr, qbComponent component) { attr->constants.push_back(component); attr->components.push_back(component); return qbResult::QB_OK; } qbResult qb_systemattr_addmutable(qbSystemAttr attr, qbComponent component) { attr->mutables.push_back(component); attr->components.push_back(component); return qbResult::QB_OK; } qbResult qb_systemattr_setfunction(qbSystemAttr attr, qbTransform transform) { attr->transform = transform; return qbResult::QB_OK; } qbResult qb_systemattr_setcallback(qbSystemAttr attr, qbCallback callback) { attr->callback = callback; return qbResult::QB_OK; } qbResult qb_systemattr_setcondition(qbSystemAttr attr, qbCondition condition) { attr->condition = condition; return qbResult::QB_OK; } qbResult qb_systemattr_settrigger(qbSystemAttr attr, qbTrigger trigger) { attr->trigger = trigger; return qbResult::QB_OK; } qbResult qb_systemattr_setpriority(qbSystemAttr attr, int16_t priority) { attr->priority = priority; return qbResult::QB_OK; } qbResult qb_systemattr_setjoin(qbSystemAttr attr, qbComponentJoin join) { attr->join = join; return qbResult::QB_OK; } qbResult qb_systemattr_setuserstate(qbSystemAttr attr, void* state) { attr->state = state; return qbResult::QB_OK; } qbResult qb_systemattr_addbarrier(qbSystemAttr attr, qbBarrier barrier) { qbTicket_* t = new qbTicket_; t->impl = ((Barrier*)barrier->impl)->MakeTicket().release(); t->lock = [ticket{ t->impl }]() { ((Barrier::Ticket*)ticket)->lock(); }; t->unlock = [ticket{ t->impl }]() { ((Barrier::Ticket*)ticket)->unlock(); }; attr->tickets.push_back(t); return QB_OK; } qbResult qb_system_create(qbSystem* system, qbSystemAttr attr) { if (!attr->program) { attr->program = 0; } #ifdef __ENGINE_DEBUG__ DEBUG_ASSERT(attr->transform || attr->callback, qbResult::QB_ERROR_SYSTEMATTR_HAS_FUNCTION_OR_CALLBACK); #endif AS_PRIVATE(system_create(system, *attr)); return qbResult::QB_OK; } qbResult qb_system_destroy(qbSystem*) { return qbResult::QB_OK; } qbResult qb_eventattr_create(qbEventAttr* attr) { *attr = (qbEventAttr)calloc(1, sizeof(qbEventAttr_)); new (*attr) qbEventAttr_; return qbResult::QB_OK; } qbResult qb_eventattr_destroy(qbEventAttr* attr) { delete *attr; *attr = nullptr; return qbResult::QB_OK; } qbResult qb_eventattr_setprogram(qbEventAttr attr, qbId program) { attr->program = program; return qbResult::QB_OK; } qbResult qb_eventattr_setmessagesize(qbEventAttr attr, size_t size) { attr->message_size = size; return qbResult::QB_OK; } qbResult qb_event_create(qbEvent* event, qbEventAttr attr) { if (!attr->program) { attr->program = 0; } #ifdef __ENGINE_DEBUG__ DEBUG_ASSERT(attr->message_size > 0, qbResult::QB_ERROR_EVENTATTR_MESSAGE_SIZE_IS_ZERO); #endif return AS_PRIVATE(event_create(event, attr)); } qbResult qb_event_destroy(qbEvent* event) { return AS_PRIVATE(event_destroy(event)); } qbResult qb_event_flushall(qbProgram program) { return AS_PRIVATE(event_flushall(program)); } qbResult qb_event_subscribe(qbEvent event, qbSystem system) { return AS_PRIVATE(event_subscribe(event, system)); } qbResult qb_event_unsubscribe(qbEvent event, qbSystem system) { return AS_PRIVATE(event_unsubscribe(event, system)); } qbResult qb_event_send(qbEvent event, void* message) { return AS_PRIVATE(event_send(event, message)); } qbResult qb_event_sendsync(qbEvent event, void* message) { return AS_PRIVATE(event_sendsync(event, message)); } qbResult qb_instance_oncreate(qbComponent component, qbInstanceOnCreate on_create) { return AS_PRIVATE(instance_oncreate(component, on_create)); } qbResult qb_instance_ondestroy(qbComponent component, qbInstanceOnDestroy on_destroy) { return AS_PRIVATE(instance_ondestroy(component, on_destroy)); } qbEntity qb_instance_getentity(qbInstance instance) { return instance->entity; } qbResult qb_instance_getconst(qbInstance instance, void* pbuffer) { return AS_PRIVATE(instance_getconst(instance, pbuffer)); } qbResult qb_instance_getmutable(qbInstance instance, void* pbuffer) { return AS_PRIVATE(instance_getmutable(instance, pbuffer)); } qbResult qb_instance_getcomponent(qbInstance instance, qbComponent component, void* pbuffer) { return AS_PRIVATE(instance_getcomponent(instance, component, pbuffer)); } bool qb_instance_hascomponent(qbInstance instance, qbComponent component) { return AS_PRIVATE(instance_hascomponent(instance, component)); } qbResult qb_instance_find(qbComponent component, qbEntity entity, void* pbuffer) { return AS_PRIVATE(instance_find(component, entity, pbuffer)); } qbCoro qb_coro_create(qbVar(*entry)(qbVar var)) { qbCoro ret = new qbCoro_(); ret->ret = qbUnset; ret->main = coro_new(entry); return ret; } qbCoro qb_coro_create_unsafe(qbVar(*entry)(qbVar var), void* stack, size_t stack_size) { qbCoro ret = new qbCoro_(); ret->ret = qbUnset; ret->main = coro_new_unsafe(entry, (uintptr_t)stack, stack_size); return ret; } qbResult qb_coro_destroy(qbCoro* coro) { coro_free((*coro)->main); delete *coro; *coro = nullptr; return QB_OK; } qbVar qb_coro_call(qbCoro coro, qbVar var) { coro->arg = var; return coro_call(coro->main, var); } qbCoro qb_coro_sync(qbVar(*entry)(qbVar), qbVar var) { return coro_scheduler->schedule_sync(entry, var); } qbCoro qb_coro_async(qbVar(*entry)(qbVar), qbVar var) { return coro_scheduler->schedule_async(entry, var); } qbVar qb_coro_await(qbCoro coro) { return coro_scheduler->await(coro); } qbVar qb_coro_peek(qbCoro coro) { return coro_scheduler->peek(coro); } qbVar qb_coro_yield(qbVar var) { return coro_yield(var); } void qb_coro_wait(double seconds) { double start = (double)qb_timer_query() / 1e9; double end = start + seconds; while ((double)qb_timer_query() / 1e9 < end) { qb_coro_yield(qbUnset); } } void qb_coro_waitframes(uint32_t frames) { uint32_t frames_waited = 0; while (frames_waited < frames) { qb_coro_yield(qbUnset); ++frames_waited; } } bool qb_coro_done(qbCoro coro) { return qb_coro_peek(coro).tag != QB_TAG_UNSET; } qbVar qbVoid(void* p) { qbVar v; v.tag = QB_TAG_VOID; v.p = p; return v; } qbVar qbUint(uint64_t u) { qbVar v; v.tag = QB_TAG_UINT; v.u = u; return v; } qbVar qbInt(int64_t i) { qbVar v; v.tag = QB_TAG_INT; v.i = i; return v; } qbVar qbDouble(double d) { qbVar v; v.tag = QB_TAG_DOUBLE; v.d = d; return v; } qbVar qbChar(char c) { qbVar v; v.tag = QB_TAG_CHAR; v.c = c; return v; } <|endoftext|>
<commit_before>/* Copyright 2017 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/reduce_precision_insertion.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/core/platform/logging.h" namespace xla { // For now, ReducePrecision is only implemented for F32 arrays, so this // ignores instructions that produce other data. In particular, this // currently ignores instructions producing tuples, even if those tuples // contain F32 arrays inside them. The assumption is that in most cases // equivalent behavior can be obtained by adding ReducePrecision // instructions after the instructions that pull the F32 arrays out of // the tuples. // // TODO(b/64093391): Remove the IsScalar check once this won't cause // failures on the GPU backend if the ReducePrecision instruction ends up // inserted between a scalar constant and the init_value argument of a // Reduce operation. std::vector<HloInstruction*> ReducePrecisionInsertion::instructions_to_suffix( const HloComputation* computation) { std::vector<HloInstruction*> instructions_to_suffix; switch (pass_timing_) { case HloReducePrecisionOptions::BEFORE_OP_FUSION: case HloReducePrecisionOptions::AFTER_OP_FUSION: for (auto& instruction : computation->instructions()) { VLOG(3) << "Visited instruction: " << instruction->ToString(); if (instruction->shape().element_type() == PrimitiveType::F32 && !ShapeUtil::IsScalar(instruction->shape()) && instruction_filter_function_(instruction.get())) { instructions_to_suffix.push_back(instruction.get()); } } break; case HloReducePrecisionOptions::FUSION_BY_CONTENT: for (auto& instruction : computation->instructions()) { VLOG(3) << "Visited instruction: " << instruction->ToString(); if (instruction->opcode() != HloOpcode::kFusion || instruction->shape().element_type() != PrimitiveType::F32 || ShapeUtil::IsScalar(instruction->shape())) { continue; } for (auto& fused_instruction : instruction->fused_instructions_computation()->instructions()) { VLOG(3) << "Checking sub-instruction: " << fused_instruction->ToString(); if (instruction_filter_function_(fused_instruction.get())) { instructions_to_suffix.push_back(instruction.get()); break; } } } break; default: break; } VLOG(1) << "Adding " << instructions_to_suffix.size() << " reduce-precision operations."; return instructions_to_suffix; } StatusOr<bool> ReducePrecisionInsertion::Run(HloModule* module) { bool changed = false; VLOG(1) << "Running ReducePrecisionInsertion pass on " << module->name(); for (auto& computation : module->computations()) { if (computation->IsFusionComputation()) { continue; } for (auto& instruction : instructions_to_suffix(computation.get())) { HloInstruction* reduced = computation->AddInstruction(HloInstruction::CreateReducePrecision( instruction->shape(), instruction, exponent_bits_, mantissa_bits_)); TF_RETURN_IF_ERROR( computation->ReplaceUsesOfInstruction(instruction, reduced)); VLOG(2) << "Inserted new op after instruction: " << instruction->ToString(); changed = true; } } return changed; } ReducePrecisionInsertion::InstructionFilterFunction ReducePrecisionInsertion::make_filter_function( const HloReducePrecisionOptions& reduce_precision_options) { // Implement the filter function with a lookup table. std::vector<bool> opcode_filter(HloOpcodeCount(), false); for (const auto& opcode : reduce_precision_options.opcodes_to_suffix()) { opcode_filter[opcode] = true; } if (reduce_precision_options.opname_substrings_to_suffix_size() == 0) { return [opcode_filter](const HloInstruction* instruction) { return opcode_filter[static_cast<unsigned int>(instruction->opcode())]; }; } else { std::vector<string> opname_substrings; for (const auto& substring : reduce_precision_options.opname_substrings_to_suffix()) { opname_substrings.push_back(substring); } return [opcode_filter, opname_substrings](const HloInstruction* instruction) { if (!opcode_filter[static_cast<unsigned int>(instruction->opcode())]) { return false; } const auto& opname = instruction->metadata().op_name(); for (const auto& substring : opname_substrings) { if (opname.find(substring) != string::npos) { return true; } } return false; }; } } HloReducePrecisionOptions ReducePrecisionInsertion::make_options_proto( const HloReducePrecisionOptions::PassTiming pass_timing, const int exponent_bits, const int mantissa_bits, const std::function<bool(HloOpcode)>& opcode_filter_function, const std::vector<string>& opname_substring_list) { HloReducePrecisionOptions options; options.set_pass_timing(pass_timing); options.set_exponent_bits(exponent_bits); options.set_mantissa_bits(mantissa_bits); for (uint32_t opcode = 0; opcode < HloOpcodeCount(); opcode++) { if (opcode_filter_function(static_cast<HloOpcode>(opcode))) { options.add_opcodes_to_suffix(opcode); } } for (auto& string : opname_substring_list) { options.add_opname_substrings_to_suffix(string); } return options; } bool ReducePrecisionInsertion::AddPasses( HloPassPipeline* pipeline, const DebugOptions& debug_options, const HloReducePrecisionOptions::PassTiming pass_timing) { bool passes_added = false; for (const auto& pass_options : debug_options.hlo_reduce_precision_options()) { if (pass_options.pass_timing() == pass_timing) { pipeline->AddPass<ReducePrecisionInsertion>(pass_options); passes_added = true; } } return passes_added; } } // namespace xla <commit_msg>[XLA] Optionally log computations that have had reduce-precision instructions added.<commit_after>/* Copyright 2017 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/reduce_precision_insertion.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/core/platform/logging.h" namespace xla { // For now, ReducePrecision is only implemented for F32 arrays, so this // ignores instructions that produce other data. In particular, this // currently ignores instructions producing tuples, even if those tuples // contain F32 arrays inside them. The assumption is that in most cases // equivalent behavior can be obtained by adding ReducePrecision // instructions after the instructions that pull the F32 arrays out of // the tuples. // // TODO(b/64093391): Remove the IsScalar check once this won't cause // failures on the GPU backend if the ReducePrecision instruction ends up // inserted between a scalar constant and the init_value argument of a // Reduce operation. std::vector<HloInstruction*> ReducePrecisionInsertion::instructions_to_suffix( const HloComputation* computation) { std::vector<HloInstruction*> instructions_to_suffix; switch (pass_timing_) { case HloReducePrecisionOptions::BEFORE_OP_FUSION: case HloReducePrecisionOptions::AFTER_OP_FUSION: for (auto& instruction : computation->instructions()) { VLOG(4) << "Visited instruction: " << instruction->ToString(); if (instruction->shape().element_type() == PrimitiveType::F32 && !ShapeUtil::IsScalar(instruction->shape()) && instruction_filter_function_(instruction.get())) { instructions_to_suffix.push_back(instruction.get()); } } break; case HloReducePrecisionOptions::FUSION_BY_CONTENT: for (auto& instruction : computation->instructions()) { VLOG(4) << "Visited instruction: " << instruction->ToString(); if (instruction->opcode() != HloOpcode::kFusion || instruction->shape().element_type() != PrimitiveType::F32 || ShapeUtil::IsScalar(instruction->shape())) { continue; } for (auto& fused_instruction : instruction->fused_instructions_computation()->instructions()) { VLOG(4) << "Checking sub-instruction: " << fused_instruction->ToString(); if (instruction_filter_function_(fused_instruction.get())) { instructions_to_suffix.push_back(instruction.get()); break; } } } break; default: break; } VLOG(1) << "Adding " << instructions_to_suffix.size() << " reduce-precision operations."; return instructions_to_suffix; } StatusOr<bool> ReducePrecisionInsertion::Run(HloModule* module) { bool changed = false; VLOG(1) << "Running ReducePrecisionInsertion pass on " << module->name(); for (auto& computation : module->computations()) { if (computation->IsFusionComputation()) { continue; } bool computation_changed = false; for (auto& instruction : instructions_to_suffix(computation.get())) { HloInstruction* reduced = computation->AddInstruction(HloInstruction::CreateReducePrecision( instruction->shape(), instruction, exponent_bits_, mantissa_bits_)); TF_RETURN_IF_ERROR( computation->ReplaceUsesOfInstruction(instruction, reduced)); VLOG(2) << "Inserted new op after instruction: " << instruction->ToString(); computation_changed = true; } if (computation_changed) { changed = true; VLOG(3) << "Computation after reduce-precision insertion:"; XLA_VLOG_LINES(3, computation->ToString()); } else { VLOG(3) << "Computation " << computation->name() << " unchanged"; } } return changed; } ReducePrecisionInsertion::InstructionFilterFunction ReducePrecisionInsertion::make_filter_function( const HloReducePrecisionOptions& reduce_precision_options) { // Implement the filter function with a lookup table. std::vector<bool> opcode_filter(HloOpcodeCount(), false); for (const auto& opcode : reduce_precision_options.opcodes_to_suffix()) { opcode_filter[opcode] = true; } if (reduce_precision_options.opname_substrings_to_suffix_size() == 0) { return [opcode_filter](const HloInstruction* instruction) { return opcode_filter[static_cast<unsigned int>(instruction->opcode())]; }; } else { std::vector<string> opname_substrings; for (const auto& substring : reduce_precision_options.opname_substrings_to_suffix()) { opname_substrings.push_back(substring); } return [opcode_filter, opname_substrings](const HloInstruction* instruction) { if (!opcode_filter[static_cast<unsigned int>(instruction->opcode())]) { return false; } const auto& opname = instruction->metadata().op_name(); for (const auto& substring : opname_substrings) { if (opname.find(substring) != string::npos) { return true; } } return false; }; } } HloReducePrecisionOptions ReducePrecisionInsertion::make_options_proto( const HloReducePrecisionOptions::PassTiming pass_timing, const int exponent_bits, const int mantissa_bits, const std::function<bool(HloOpcode)>& opcode_filter_function, const std::vector<string>& opname_substring_list) { HloReducePrecisionOptions options; options.set_pass_timing(pass_timing); options.set_exponent_bits(exponent_bits); options.set_mantissa_bits(mantissa_bits); for (uint32_t opcode = 0; opcode < HloOpcodeCount(); opcode++) { if (opcode_filter_function(static_cast<HloOpcode>(opcode))) { options.add_opcodes_to_suffix(opcode); } } for (auto& string : opname_substring_list) { options.add_opname_substrings_to_suffix(string); } return options; } bool ReducePrecisionInsertion::AddPasses( HloPassPipeline* pipeline, const DebugOptions& debug_options, const HloReducePrecisionOptions::PassTiming pass_timing) { bool passes_added = false; for (const auto& pass_options : debug_options.hlo_reduce_precision_options()) { if (pass_options.pass_timing() == pass_timing) { pipeline->AddPass<ReducePrecisionInsertion>(pass_options); passes_added = true; } } return passes_added; } } // namespace xla <|endoftext|>
<commit_before>/* * Daemon.node: A node.JS addon that allows creating Unix/Linux Daemons in pure Javascript. * * Copyright 2010 (c) <[email protected]> * Modified By: Pedro Teixeira 2010 * Modified By: James Haliday 2010 * Modified By: Charlie Robbins 2010 * Modified By: Zak Taylor 2010 * Modified By: Daniel Bartlett 2011 * Modified By: Charlie Robbins 2011 * * Under MIT License. See LICENSE file. * */ #include <v8.h> #include <node.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <pwd.h> #define PID_MAXLEN 10 using namespace v8; using namespace node; // // Go through special routines to become a daemon. // if successful, returns daemon pid // static Handle<Value> Start(const Arguments& args) { HandleScope scope; pid_t sid, pid = fork(); int i, new_fd; if (pid < 0) exit(1); else if (pid > 0) exit(0); if (pid == 0) { // Child process: We need to tell libev that we are forking because // kqueue can't deal with this gracefully. // // See: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_fork_code_the_audacity_to_re ev_default_fork(); sid = setsid(); if(sid < 0) exit(1); // Close stdin freopen("/dev/null", "r", stdin); if (args.Length() > 0 && args[0]->IsInt32()) { new_fd = args[0]->Int32Value(); dup2(new_fd, STDOUT_FILENO); dup2(new_fd, STDERR_FILENO); } else { freopen("/dev/null", "w", stderr); freopen("/dev/null", "w", stdout); } } return scope.Close(Number::New(getpid())); } // // Close stdin by redirecting it to /dev/null // Handle<Value> CloseStdin(const Arguments& args) { freopen("/dev/null", "r", stdin); } // // Close stderr by redirecting to /dev/null // Handle<Value> CloseStderr(const Arguments& args) { freopen("/dev/null", "w", stderr); } // // Close stdout by redirecting to /dev/null // Handle<Value> CloseStdout(const Arguments& args) { freopen("/dev/null", "w", stdout); } // // Closes all stdio by redirecting to /dev/null // Handle<Value> CloseStdio(const Arguments& args) { freopen("/dev/null", "r", stdin); freopen("/dev/null", "w", stderr); freopen("/dev/null", "w", stdout); } // // File-lock to make sure that only one instance of daemon is running, also for storing pid // lock (filename) // @filename: a path to a lock-file. // // Note: if filename doesn't exist, it will be created when function is called. // Handle<Value> LockD(const Arguments& args) { if (!args[0]->IsString()) return Boolean::New(false); String::Utf8Value data(args[0]->ToString()); char pid_str[PID_MAXLEN+1]; int lfp = open(*data, O_RDWR | O_CREAT | O_TRUNC, 0640); if(lfp < 0) exit(1); if(lockf(lfp, F_TLOCK, 0) < 0) return Boolean::New(false); int len = snprintf(pid_str, PID_MAXLEN, "%d", getpid()); write(lfp, pid_str, len); fsync(lfp); return Boolean::New(true); } Handle<Value> SetSid(const Arguments& args) { pid_t sid; sid = setsid(); return Integer::New(sid); } const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } // // Set the chroot of this process. You probably want to be sure stuff is in here. // chroot (folder) // @folder {string}: The new root // Handle<Value> Chroot(const Arguments& args) { if (args.Length() < 1) { return ThrowException(Exception::TypeError( String::New("Must have one argument; a string of the folder to chroot to.") )); } uid_t uid; int rv; String::Utf8Value folderUtf8(args[0]->ToString()); const char *folder = ToCString(folderUtf8); rv = chroot(folder); if (rv != 0) { return ThrowException(ErrnoException(errno, "chroot")); } chdir("/"); return Boolean::New(true); } // // Allow changing the real and effective user ID of this process // so a root process can become unprivileged // Handle<Value> SetReuid(const Arguments& args) { if (args.Length() == 0 || (!args[0]->IsString() && !args[0]->IsInt32())) return ThrowException(Exception::Error( String::New("Must give a uid or username to become") )); if (args[0]->IsString()) { String::AsciiValue username(args[0]); struct passwd* pwd_entry = getpwnam(*username); if (pwd_entry) { setreuid(pwd_entry->pw_uid, pwd_entry->pw_uid); } else { return ThrowException(Exception::Error( String::New("User not found") )); } } else if (args[0]->IsInt32()) { uid_t uid; uid = args[0]->Int32Value(); setreuid(uid, uid); } } // // Initialize this add-on // extern "C" void init(Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "start", Start); NODE_SET_METHOD(target, "lock", LockD); NODE_SET_METHOD(target, "setsid", SetSid); NODE_SET_METHOD(target, "chroot", Chroot); NODE_SET_METHOD(target, "setreuid", SetReuid); NODE_SET_METHOD(target, "closeStderr", CloseStderr); NODE_SET_METHOD(target, "closeStdout", CloseStdout); NODE_SET_METHOD(target, "closeStdin", CloseStdin); NODE_SET_METHOD(target, "closeStdio", CloseStdio); }<commit_msg>[minor] Lets have return true on user change, so we know it's good.<commit_after>/* * Daemon.node: A node.JS addon that allows creating Unix/Linux Daemons in pure Javascript. * * Copyright 2010 (c) <[email protected]> * Modified By: Pedro Teixeira 2010 * Modified By: James Haliday 2010 * Modified By: Charlie Robbins 2010 * Modified By: Zak Taylor 2010 * Modified By: Daniel Bartlett 2011 * Modified By: Charlie Robbins 2011 * * Under MIT License. See LICENSE file. * */ #include <v8.h> #include <node.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <pwd.h> #define PID_MAXLEN 10 using namespace v8; using namespace node; // // Go through special routines to become a daemon. // if successful, returns daemon pid // static Handle<Value> Start(const Arguments& args) { HandleScope scope; pid_t sid, pid = fork(); int i, new_fd; if (pid < 0) exit(1); else if (pid > 0) exit(0); if (pid == 0) { // Child process: We need to tell libev that we are forking because // kqueue can't deal with this gracefully. // // See: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_fork_code_the_audacity_to_re ev_default_fork(); sid = setsid(); if(sid < 0) exit(1); // Close stdin freopen("/dev/null", "r", stdin); if (args.Length() > 0 && args[0]->IsInt32()) { new_fd = args[0]->Int32Value(); dup2(new_fd, STDOUT_FILENO); dup2(new_fd, STDERR_FILENO); } else { freopen("/dev/null", "w", stderr); freopen("/dev/null", "w", stdout); } } return scope.Close(Number::New(getpid())); } // // Close stdin by redirecting it to /dev/null // Handle<Value> CloseStdin(const Arguments& args) { freopen("/dev/null", "r", stdin); } // // Close stderr by redirecting to /dev/null // Handle<Value> CloseStderr(const Arguments& args) { freopen("/dev/null", "w", stderr); } // // Close stdout by redirecting to /dev/null // Handle<Value> CloseStdout(const Arguments& args) { freopen("/dev/null", "w", stdout); } // // Closes all stdio by redirecting to /dev/null // Handle<Value> CloseStdio(const Arguments& args) { freopen("/dev/null", "r", stdin); freopen("/dev/null", "w", stderr); freopen("/dev/null", "w", stdout); } // // File-lock to make sure that only one instance of daemon is running, also for storing pid // lock (filename) // @filename: a path to a lock-file. // // Note: if filename doesn't exist, it will be created when function is called. // Handle<Value> LockD(const Arguments& args) { if (!args[0]->IsString()) return Boolean::New(false); String::Utf8Value data(args[0]->ToString()); char pid_str[PID_MAXLEN+1]; int lfp = open(*data, O_RDWR | O_CREAT | O_TRUNC, 0640); if(lfp < 0) exit(1); if(lockf(lfp, F_TLOCK, 0) < 0) return Boolean::New(false); int len = snprintf(pid_str, PID_MAXLEN, "%d", getpid()); write(lfp, pid_str, len); fsync(lfp); return Boolean::New(true); } Handle<Value> SetSid(const Arguments& args) { pid_t sid; sid = setsid(); return Integer::New(sid); } const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } // // Set the chroot of this process. You probably want to be sure stuff is in here. // chroot (folder) // @folder {string}: The new root // Handle<Value> Chroot(const Arguments& args) { if (args.Length() < 1) { return ThrowException(Exception::TypeError( String::New("Must have one argument; a string of the folder to chroot to.") )); } uid_t uid; int rv; String::Utf8Value folderUtf8(args[0]->ToString()); const char *folder = ToCString(folderUtf8); rv = chroot(folder); if (rv != 0) { return ThrowException(ErrnoException(errno, "chroot")); } chdir("/"); return Boolean::New(true); } // // Allow changing the real and effective user ID of this process // so a root process can become unprivileged // Handle<Value> SetReuid(const Arguments& args) { if (args.Length() == 0 || (!args[0]->IsString() && !args[0]->IsInt32())) return ThrowException(Exception::Error( String::New("Must give a uid or username to become") )); if (args[0]->IsString()) { String::AsciiValue username(args[0]); struct passwd* pwd_entry = getpwnam(*username); if (pwd_entry) { setreuid(pwd_entry->pw_uid, pwd_entry->pw_uid); return Boolean::New(true); } else { return ThrowException(Exception::Error( String::New("User not found") )); } } else if (args[0]->IsInt32()) { uid_t uid; uid = args[0]->Int32Value(); setreuid(uid, uid); return Boolean::New(true); } } // // Initialize this add-on // extern "C" void init(Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "start", Start); NODE_SET_METHOD(target, "lock", LockD); NODE_SET_METHOD(target, "setsid", SetSid); NODE_SET_METHOD(target, "chroot", Chroot); NODE_SET_METHOD(target, "setreuid", SetReuid); NODE_SET_METHOD(target, "closeStderr", CloseStderr); NODE_SET_METHOD(target, "closeStdout", CloseStdout); NODE_SET_METHOD(target, "closeStdin", CloseStdin); NODE_SET_METHOD(target, "closeStdio", CloseStdio); }<|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include <QApplication> #include <QCloseEvent> #include <QDir> #include <QMenu> #include <QSignalSpy> #include <QWindow> #include <candevicemodel.h> #include <canrawviewmodel.h> #include <catch.hpp> #include <fakeit.hpp> #include <log.h> #include <nodes/FlowScene> #include <pcinterface.h> #include <projectconfig.h> #include <projectconfigvalidator.h> #include "ui_projectconfig.h" #include <QPushButton> #include <iconlabel.h> #include <plugins.hpp> std::shared_ptr<spdlog::logger> kDefaultLogger; TEST_CASE("Loading and saving", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig.cds")); ProjectConfig pc(new QWidget); QByteArray outConfig; CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); REQUIRE_NOTHROW(pc.load(inConfig)); REQUIRE_NOTHROW(outConfig = pc.save()); REQUIRE_NOTHROW(pc.clearGraphView()); REQUIRE_NOTHROW(pc.load(outConfig)); } TEST_CASE("Color mode", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig.cds")); ProjectConfig pc(new QWidget); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); REQUIRE_NOTHROW(pc.load(inConfig)); REQUIRE_NOTHROW(pc.setColorMode(true)); REQUIRE_NOTHROW(pc.setColorMode(false)); } TEST_CASE("Close event", "[projectconfig]") { QCloseEvent e; ProjectConfig pc(new QWidget); QSignalSpy closeSpy(&pc, &ProjectConfig::closeProject); pc.closeEvent(&e); CHECK(closeSpy.count() == 1); } TEST_CASE("Validation schema parse error", "[projectconfig]") { CHECK(ProjectConfigValidator::loadConfigSchema("Makefile") == false); } TEST_CASE("Validation JSON format error", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig_wrong.cds")); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.read(40); CHECK(ProjectConfigValidator::validateConfiguration(inConfig) == false); } TEST_CASE("Validation schema validation failed", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig_wrong.cds")); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); CHECK(ProjectConfigValidator::validateConfiguration(inConfig) == false); } TEST_CASE("Validation succeeded", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig.cds")); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); CHECK(ProjectConfigValidator::validateConfiguration(inConfig)); } TEST_CASE("Validator validate", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig.cds")); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); ProjectConfigValidator pcv; CHECK(pcv.loadConfigSchema()); CHECK(pcv.validateConfiguration(inConfig)); } TEST_CASE("callbacks test", "[projectconfig]") { using namespace fakeit; PCInterface::node_t nodeCreated; PCInterface::node_t nodeDeleted; PCInterface::node_t nodeClicked; PCInterface::menu_t nodeMenu; QtNodes::FlowScene* fs; Mock<PCInterface> pcMock; When(Method(pcMock, setNodeCreatedCallback)).Do([&](auto flow, auto&& fn) { fs = flow; nodeCreated = fn; }); When(Method(pcMock, setNodeDeletedCallback)).Do([&](auto, auto&& fn) { nodeDeleted = fn; }); When(Method(pcMock, setNodeDoubleClickedCallback)).Do([&](auto, auto&& fn) { nodeClicked = fn; }); When(Method(pcMock, setNodeContextMenuCallback)).Do([&](auto, auto&& fn) { nodeMenu = fn; }); Fake(Method(pcMock, showContextMenu)); Fake(Method(pcMock, openProperties)); ProjectConfig pc(nullptr, ProjectConfigCtx(&pcMock.get())); pc.simulationStarted(); auto& node = fs->createNode(std::make_unique<CanDeviceModel>()); node.restore({}); nodeCreated(node); nodeClicked(node); nodeMenu(node, QPointF()); QSignalSpy showingSpy(&pc, &ProjectConfig::handleWidgetShowing); auto& node2 = fs->createNode(std::make_unique<CanRawViewModel>()); nodeClicked(node2); nodeMenu(node2, QPointF()); CHECK(showingSpy.count() == 1); pc.simulationStopped(); nodeClicked(node); nodeMenu(node, QPointF()); nodeClicked(node2); nodeMenu(node2, QPointF()); fs->removeNode(node); fs->removeNode(node2); } TEST_CASE("Plugin loading - sections not initialized", "[common]") { QtNodes::FlowScene graphScene; Plugins plugins(graphScene.registry()); REQUIRE_NOTHROW(plugins.addWidgets({ 0x11223344 })); } int main(int argc, char* argv[]) { Q_INIT_RESOURCE(CANdevResources); bool haveDebug = std::getenv("CDS_DEBUG") != nullptr; kDefaultLogger = spdlog::stdout_color_mt("cds"); if (haveDebug) { kDefaultLogger->set_level(spdlog::level::debug); } cds_debug("Staring unit tests"); QApplication a(argc, argv); return Catch::Session().run(argc, argv); } <commit_msg>Fix typo<commit_after>#define CATCH_CONFIG_RUNNER #include <QApplication> #include <QCloseEvent> #include <QDir> #include <QMenu> #include <QSignalSpy> #include <QWindow> #include <candevicemodel.h> #include <canrawviewmodel.h> #include <catch.hpp> #include <fakeit.hpp> #include <log.h> #include <nodes/FlowScene> #include <pcinterface.h> #include <projectconfig.h> #include <projectconfigvalidator.h> #include "ui_projectconfig.h" #include <QPushButton> #include <iconlabel.h> #include <plugins.hpp> std::shared_ptr<spdlog::logger> kDefaultLogger; TEST_CASE("Loading and saving", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig.cds")); ProjectConfig pc(new QWidget); QByteArray outConfig; CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); REQUIRE_NOTHROW(pc.load(inConfig)); REQUIRE_NOTHROW(outConfig = pc.save()); REQUIRE_NOTHROW(pc.clearGraphView()); REQUIRE_NOTHROW(pc.load(outConfig)); } TEST_CASE("Color mode", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig.cds")); ProjectConfig pc(new QWidget); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); REQUIRE_NOTHROW(pc.load(inConfig)); REQUIRE_NOTHROW(pc.setColorMode(true)); REQUIRE_NOTHROW(pc.setColorMode(false)); } TEST_CASE("Close event", "[projectconfig]") { QCloseEvent e; ProjectConfig pc(new QWidget); QSignalSpy closeSpy(&pc, &ProjectConfig::closeProject); pc.closeEvent(&e); CHECK(closeSpy.count() == 1); } TEST_CASE("Validation schema parse error", "[projectconfig]") { CHECK(ProjectConfigValidator::loadConfigSchema("Makefile") == false); } TEST_CASE("Validation JSON format error", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig_wrong.cds")); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.read(40); CHECK(ProjectConfigValidator::validateConfiguration(inConfig) == false); } TEST_CASE("Validation schema validation failed", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig_wrong.cds")); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); CHECK(ProjectConfigValidator::validateConfiguration(inConfig) == false); } TEST_CASE("Validation succeeded", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig.cds")); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); CHECK(ProjectConfigValidator::validateConfiguration(inConfig)); } TEST_CASE("Validator validate", "[projectconfig]") { QDir dir("configfiles"); QFile file(dir.absoluteFilePath("projectconfig.cds")); CHECK(file.open(QIODevice::ReadOnly) == true); auto inConfig = file.readAll(); ProjectConfigValidator pcv; CHECK(pcv.loadConfigSchema()); CHECK(pcv.validateConfiguration(inConfig)); } TEST_CASE("callbacks test", "[projectconfig]") { using namespace fakeit; PCInterface::node_t nodeCreated; PCInterface::node_t nodeDeleted; PCInterface::node_t nodeClicked; PCInterface::menu_t nodeMenu; QtNodes::FlowScene* fs; Mock<PCInterface> pcMock; When(Method(pcMock, setNodeCreatedCallback)).Do([&](auto flow, auto&& fn) { fs = flow; nodeCreated = fn; }); When(Method(pcMock, setNodeDeletedCallback)).Do([&](auto, auto&& fn) { nodeDeleted = fn; }); When(Method(pcMock, setNodeDoubleClickedCallback)).Do([&](auto, auto&& fn) { nodeClicked = fn; }); When(Method(pcMock, setNodeContextMenuCallback)).Do([&](auto, auto&& fn) { nodeMenu = fn; }); Fake(Method(pcMock, showContextMenu)); Fake(Method(pcMock, openProperties)); ProjectConfig pc(nullptr, ProjectConfigCtx(&pcMock.get())); pc.simulationStarted(); auto& node = fs->createNode(std::make_unique<CanDeviceModel>()); node.restore({}); nodeCreated(node); nodeClicked(node); nodeMenu(node, QPointF()); QSignalSpy showingSpy(&pc, &ProjectConfig::handleWidgetShowing); auto& node2 = fs->createNode(std::make_unique<CanRawViewModel>()); nodeClicked(node2); nodeMenu(node2, QPointF()); CHECK(showingSpy.count() == 1); pc.simulationStopped(); nodeClicked(node); nodeMenu(node, QPointF()); nodeClicked(node2); nodeMenu(node2, QPointF()); fs->removeNode(node); fs->removeNode(node2); } TEST_CASE("Plugin loading - sections not initialized", "[common]") { QtNodes::FlowScene graphScene; Plugins plugins(graphScene.registry()); REQUIRE_NOTHROW(plugins.addWidgets({ 0x11223344 })); } int main(int argc, char* argv[]) { Q_INIT_RESOURCE(CANdevResources); bool haveDebug = std::getenv("CDS_DEBUG") != nullptr; kDefaultLogger = spdlog::stdout_color_mt("cds"); if (haveDebug) { kDefaultLogger->set_level(spdlog::level::debug); } cds_debug("Starting unit tests"); QApplication a(argc, argv); return Catch::Session().run(argc, argv); } <|endoftext|>
<commit_before>/* * Copyright (c) 2006, Mathieu Champlon * 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 copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS 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 xeumeuleu_attribute_hpp #define xeumeuleu_attribute_hpp #include <string> namespace xml { // ============================================================================= /** @class attribute_manipulator @brief Attribute manipulator */ // Created: MAT 2006-01-05 // ============================================================================= template< typename T > class attribute_manipulator { public: //! @name Constructors/Destructor //@{ attribute_manipulator( const std::string& name, T& value, bool skip = false ) : name_ ( name ) , value_( value ) , skip_( skip ) {} //@} private: //! @name Copy/Assignment //@{ attribute_manipulator& operator=( const attribute_manipulator& ); //!< Assignment operator //@} public: //! @name Member data //@{ std::string name_; T& value_; bool skip_; //@} }; // ----------------------------------------------------------------------------- // Name: attribute // Created: MAT 2006-01-06 // ----------------------------------------------------------------------------- template< typename T > attribute_manipulator< const T > attribute( const std::string& name, const T& value ) { return attribute_manipulator< const T >( name, value ); } // ----------------------------------------------------------------------------- // Name: attribute // Created: MAT 2017-03-21 // ----------------------------------------------------------------------------- template< typename T, typename F > attribute_manipulator< const T > attribute( const std::string& name, const T& value, const F& fallback ) { return attribute_manipulator< const T >( name, value, value == fallback ); } // ----------------------------------------------------------------------------- // Name: attribute // Created: MAT 2017-03-21 // ----------------------------------------------------------------------------- template< typename T > attribute_manipulator< const T* > attribute( const std::string& name, const T* value, std::nullptr_t ) { return attribute_manipulator< const T* >( name, value, !value ); } // ----------------------------------------------------------------------------- // Name: attribute // Created: MAT 2006-01-06 // ----------------------------------------------------------------------------- template< typename T > attribute_manipulator< T > attribute( const std::string& name, T& value ) { return attribute_manipulator< T >( name, value ); } } #endif // xeumeuleu_attribute_hpp <commit_msg>Fixed reference on local pointer<commit_after>/* * Copyright (c) 2006, Mathieu Champlon * 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 copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS 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 xeumeuleu_attribute_hpp #define xeumeuleu_attribute_hpp #include <string> namespace xml { // ============================================================================= /** @class attribute_manipulator @brief Attribute manipulator */ // Created: MAT 2006-01-05 // ============================================================================= template< typename T > class attribute_manipulator { public: //! @name Constructors/Destructor //@{ attribute_manipulator( const std::string& name, T& value, bool skip = false ) : name_ ( name ) , value_( value ) , skip_ ( skip ) {} //@} private: //! @name Copy/Assignment //@{ attribute_manipulator& operator=( const attribute_manipulator& ); //!< Assignment operator //@} public: //! @name Member data //@{ std::string name_; T& value_; bool skip_; //@} }; // ----------------------------------------------------------------------------- // Name: attribute // Created: MAT 2006-01-06 // ----------------------------------------------------------------------------- template< typename T > attribute_manipulator< const T > attribute( const std::string& name, const T& value ) { return attribute_manipulator< const T >( name, value ); } // ----------------------------------------------------------------------------- // Name: attribute // Created: MAT 2017-03-21 // ----------------------------------------------------------------------------- template< typename T, typename F > attribute_manipulator< const T > attribute( const std::string& name, const T& value, const F& fallback ) { return attribute_manipulator< const T >( name, value, value == fallback ); } // ----------------------------------------------------------------------------- // Name: attribute // Created: MAT 2017-03-21 // ----------------------------------------------------------------------------- template< typename T > attribute_manipulator< const T > attribute( const std::string& name, const T& value, std::nullptr_t ) { return attribute_manipulator< const T >( name, value, !value ); } // ----------------------------------------------------------------------------- // Name: attribute // Created: MAT 2006-01-06 // ----------------------------------------------------------------------------- template< typename T > attribute_manipulator< T > attribute( const std::string& name, T& value ) { return attribute_manipulator< T >( name, value ); } } #endif // xeumeuleu_attribute_hpp <|endoftext|>
<commit_before>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 1999-2008 Vaclav Slavik * * 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$ * * Application class * */ #include <wx/wxprec.h> #include <wx/wx.h> #include <wx/config.h> #include <wx/fs_zip.h> #include <wx/image.h> #include <wx/cmdline.h> #include <wx/log.h> #include <wx/xrc/xmlres.h> #include <wx/xrc/xh_all.h> #include <wx/stdpaths.h> #include <wx/filename.h> #include <wx/sysopt.h> #ifdef USE_SPARKLE #include <Sparkle/SUCarbonAPI.h> #endif // USE_SPARKLE #if !wxUSE_UNICODE #error "Unicode build of wxWidgets is required by Poedit" #endif #include "edapp.h" #include "edframe.h" #include "manager.h" #include "prefsdlg.h" #include "parser.h" #include "chooselang.h" #include "icons.h" IMPLEMENT_APP(PoeditApp); wxString PoeditApp::GetAppPath() const { #if defined(__UNIX__) wxString home; if (!wxGetEnv(_T("POEDIT_PREFIX"), &home)) home = wxString::FromAscii(POEDIT_PREFIX); return home; #elif defined(__WXMSW__) wxString exedir; wxFileName::SplitPath(wxStandardPaths::Get().GetExecutablePath(), &exedir, NULL, NULL); wxFileName fn = wxFileName::DirName(exedir); fn.RemoveLastDir(); return fn.GetFullPath(); #else #error "Unsupported platform!" #endif } wxString PoeditApp::GetAppVersion() const { wxString version(_T("1.4.0")); return version; } #ifndef __WXMAC__ static wxArrayString gs_filesToOpen; #endif extern void InitXmlResource(); bool PoeditApp::OnInit() { if (!wxApp::OnInit()) return false; #if defined(__WXMAC__) && wxCHECK_VERSION(2,8,5) wxSystemOptions::SetOption(wxMAC_TEXTCONTROL_USE_SPELL_CHECKER, 1); #endif #ifdef __WXMAC__ SetExitOnFrameDelete(false); #endif #if defined(__UNIX__) && !defined(__WXMAC__) wxString home = wxGetHomeDir() + _T("/"); // create Poedit cfg dir, move ~/.poedit to ~/.poedit/config // (upgrade from older versions of Poedit which used ~/.poedit file) if (!wxDirExists(home + _T(".poedit"))) { if (wxFileExists(home + _T(".poedit"))) wxRenameFile(home + _T(".poedit"), home + _T(".poedit2")); wxMkdir(home + _T(".poedit")); if (wxFileExists(home + _T(".poedit2"))) wxRenameFile(home + _T(".poedit2"), home + _T(".poedit/config")); } #endif SetVendorName(_T("Vaclav Slavik")); SetAppName(_T("Poedit")); #if defined(__WXMAC__) #define CFG_FILE (wxStandardPaths::Get().GetUserConfigDir() + _T("/net.poedit.Poedit.cfg")) #elif defined(__UNIX__) #define CFG_FILE (home + _T(".poedit/config")) #else #define CFG_FILE wxEmptyString #endif #ifdef __WXMAC__ // upgrade from the old location of config file: wxString oldcfgfile = wxStandardPaths::Get().GetUserConfigDir() + _T("/poedit.cfg"); if (wxFileExists(oldcfgfile) && !wxFileExists(CFG_FILE)) { wxRenameFile(oldcfgfile, CFG_FILE); } #endif wxConfigBase::Set( new wxConfig(wxEmptyString, wxEmptyString, CFG_FILE, wxEmptyString, wxCONFIG_USE_GLOBAL_FILE | wxCONFIG_USE_LOCAL_FILE)); wxConfigBase::Get()->SetExpandEnvVars(false); wxImage::AddHandler(new wxGIFHandler); wxImage::AddHandler(new wxPNGHandler); wxXmlResource::Get()->InitAllHandlers(); InitXmlResource(); SetDefaultCfg(wxConfig::Get()); #ifdef HAS_INSERT_PROVIDER wxArtProvider::Insert(new PoeditArtProvider); #else wxArtProvider::PushProvider(new PoeditArtProvider); #endif #ifdef __WXMAC__ wxLocale::AddCatalogLookupPathPrefix( wxStandardPaths::Get().GetResourcesDir() + _T("/locale")); #else wxLocale::AddCatalogLookupPathPrefix(GetAppPath() + _T("/share/locale")); #endif m_locale.Init(GetUILanguage()); m_locale.AddCatalog(_T("poedit")); if (wxConfig::Get()->Read(_T("translator_name"), _T("nothing")) == _T("nothing")) { wxMessageBox(_("This is first time you run Poedit.\nPlease fill in your name and email address.\n(This information is used only in catalogs headers)"), _("Setup"), wxOK | wxICON_INFORMATION); PreferencesDialog dlg; dlg.TransferTo(wxConfig::Get()); if (dlg.ShowModal() == wxID_OK) dlg.TransferFrom(wxConfig::Get()); } // opening files or creating empty window is handled differently on Macs, // using MacOpenFile() and MacNewFile(), so don't do it here: #ifndef __WXMAC__ if (gs_filesToOpen.GetCount() == 0) { OpenNewFile(); } else { for (size_t i = 0; i < gs_filesToOpen.GetCount(); i++) OpenFile(gs_filesToOpen[i]); gs_filesToOpen.clear(); } #endif // !__WXMAC__ #ifdef USE_SPARKLE SUSparkleInitializeForCarbon(); #endif // USE_SPARKLE return true; } void PoeditApp::OpenNewFile() { if (wxConfig::Get()->Read(_T("manager_startup"), (long)false)) ManagerFrame::Create()->Show(true); else PoeditFrame::Create(wxEmptyString); } void PoeditApp::OpenFile(const wxString& name) { PoeditFrame::Create(name); } void PoeditApp::SetDefaultParsers(wxConfigBase *cfg) { ParsersDB pdb; bool changed = false; wxString defaultsVersion = cfg->Read(_T("Parsers/DefaultsVersion"), _T("1.2.x")); pdb.Read(cfg); // Add parsers for languages supported by gettext itself (but only if the // user didn't already add language with this name himself): static struct { const wxChar *name; const wxChar *exts; } s_gettextLangs[] = { { _T("C/C++"), _T("*.c;*.cpp;*.h;*.hpp;*.cc;*.C;*.cxx;*.hxx") }, #ifndef __WINDOWS__ // FIXME: not supported by 0.13.1 shipped with poedit on win32 { _T("C#"), _T("*.cs") }, #endif { _T("Java"), _T("*.java") }, { _T("Perl"), _T("*.pl") }, { _T("PHP"), _T("*.php") }, { _T("Python"), _T("*.py") }, { _T("TCL"), _T("*.tcl") }, { NULL, NULL } }; for (size_t i = 0; s_gettextLangs[i].name != NULL; i++) { // if this lang is already registered, don't overwrite it: if (pdb.FindParser(s_gettextLangs[i].name) != -1) continue; // otherwise add new parser: Parser p; p.Name = s_gettextLangs[i].name; p.Extensions = s_gettextLangs[i].exts; p.Command = _T("xgettext --force-po --omit-header -o %o %C %K %F"); p.KeywordItem = _T("-k%k"); p.FileItem = _T("%f"); p.CharsetItem = _T("--from-code=%c"); pdb.Add(p); changed = true; } // If upgrading Poedit to 1.2.4, add dxgettext parser for Delphi: #ifdef __WINDOWS__ if (defaultsVersion == _T("1.2.x")) { Parser p; p.Name = _T("Delphi (dxgettext)"); p.Extensions = _T("*.pas;*.dpr;*.xfm;*.dfm"); p.Command = _T("dxgettext --so %o %F"); p.KeywordItem = wxEmptyString; p.FileItem = _T("%f"); pdb.Add(p); changed = true; } #endif // If upgrading Poedit to 1.2.5, update C++ parser to handle --from-code: if (defaultsVersion == _T("1.2.x") || defaultsVersion == _T("1.2.4")) { int cpp = pdb.FindParser(_T("C/C++")); if (cpp != -1) { if (pdb[cpp].Command == _T("xgettext --force-po -o %o %K %F")) { pdb[cpp].Command = _T("xgettext --force-po --omit-header -o %o %C %K %F"); pdb[cpp].CharsetItem = _T("--from-code=%c"); changed = true; } } } // 1.4.0 adds --omit-header to parsers lines: for ( size_t i = 0; i < pdb.size(); ++i ) { if ( pdb[i].Command == _T("xgettext --force-po -o %o %C %K %F") ) { pdb[i].Command = _T("xgettext --force-po --omit-header -o %o %C %K %F"); changed = true; } } if (changed) { pdb.Write(cfg); cfg->Write(_T("Parsers/DefaultsVersion"), GetAppVersion()); } } void PoeditApp::SetDefaultCfg(wxConfigBase *cfg) { SetDefaultParsers(cfg); if (cfg->Read(_T("version"), wxEmptyString) == GetAppVersion()) return; if (cfg->Read(_T("TM/database_path"), wxEmptyString).empty()) { wxString dbpath; #if defined(__WXMAC__) dbpath = wxStandardPaths::Get().GetUserDataDir() + _T("/tm"); #elif defined(__UNIX__) dbpath = wxGetHomeDir() + _T("/.poedit/tm"); #elif defined(__WXMSW__) dbpath = wxGetHomeDir() + _T("\\poedit_tm"); #endif cfg->Write(_T("TM/database_path"), dbpath); } if (cfg->Read(_T("TM/search_paths"), wxEmptyString).empty()) { wxString paths; #if defined(__UNIX__) paths = wxGetHomeDir() + _T(":/usr/share/locale:/usr/local/share/locale"); #elif defined(__WXMSW__) paths = _T("C:"); #endif cfg->Write(_T("TM/search_paths"), paths); } cfg->Write(_T("version"), GetAppVersion()); } void PoeditApp::OnInitCmdLine(wxCmdLineParser& parser) { wxApp::OnInitCmdLine(parser); parser.AddParam(_T("catalog.po"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE); } bool PoeditApp::OnCmdLineParsed(wxCmdLineParser& parser) { if (!wxApp::OnCmdLineParsed(parser)) return false; #ifndef __WXMAC__ for (size_t i = 0; i < parser.GetParamCount(); i++) gs_filesToOpen.Add(parser.GetParam(i)); #endif return true; } <commit_msg>fixed duplicate Help menu on OS X when using non-English translation<commit_after>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 1999-2008 Vaclav Slavik * * 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$ * * Application class * */ #include <wx/wxprec.h> #include <wx/wx.h> #include <wx/config.h> #include <wx/fs_zip.h> #include <wx/image.h> #include <wx/cmdline.h> #include <wx/log.h> #include <wx/xrc/xmlres.h> #include <wx/xrc/xh_all.h> #include <wx/stdpaths.h> #include <wx/filename.h> #include <wx/sysopt.h> #ifdef USE_SPARKLE #include <Sparkle/SUCarbonAPI.h> #endif // USE_SPARKLE #if !wxUSE_UNICODE #error "Unicode build of wxWidgets is required by Poedit" #endif #include "edapp.h" #include "edframe.h" #include "manager.h" #include "prefsdlg.h" #include "parser.h" #include "chooselang.h" #include "icons.h" IMPLEMENT_APP(PoeditApp); wxString PoeditApp::GetAppPath() const { #if defined(__UNIX__) wxString home; if (!wxGetEnv(_T("POEDIT_PREFIX"), &home)) home = wxString::FromAscii(POEDIT_PREFIX); return home; #elif defined(__WXMSW__) wxString exedir; wxFileName::SplitPath(wxStandardPaths::Get().GetExecutablePath(), &exedir, NULL, NULL); wxFileName fn = wxFileName::DirName(exedir); fn.RemoveLastDir(); return fn.GetFullPath(); #else #error "Unsupported platform!" #endif } wxString PoeditApp::GetAppVersion() const { wxString version(_T("1.4.0")); return version; } #ifndef __WXMAC__ static wxArrayString gs_filesToOpen; #endif extern void InitXmlResource(); bool PoeditApp::OnInit() { if (!wxApp::OnInit()) return false; #if defined(__WXMAC__) && wxCHECK_VERSION(2,8,5) wxSystemOptions::SetOption(wxMAC_TEXTCONTROL_USE_SPELL_CHECKER, 1); #endif #ifdef __WXMAC__ // so that help menu is correctly merged with system-provided menu // (see http://sourceforge.net/tracker/index.php?func=detail&aid=1600747&group_id=9863&atid=309863) s_macHelpMenuTitleName = _("&Help"); SetExitOnFrameDelete(false); #endif #if defined(__UNIX__) && !defined(__WXMAC__) wxString home = wxGetHomeDir() + _T("/"); // create Poedit cfg dir, move ~/.poedit to ~/.poedit/config // (upgrade from older versions of Poedit which used ~/.poedit file) if (!wxDirExists(home + _T(".poedit"))) { if (wxFileExists(home + _T(".poedit"))) wxRenameFile(home + _T(".poedit"), home + _T(".poedit2")); wxMkdir(home + _T(".poedit")); if (wxFileExists(home + _T(".poedit2"))) wxRenameFile(home + _T(".poedit2"), home + _T(".poedit/config")); } #endif SetVendorName(_T("Vaclav Slavik")); SetAppName(_T("Poedit")); #if defined(__WXMAC__) #define CFG_FILE (wxStandardPaths::Get().GetUserConfigDir() + _T("/net.poedit.Poedit.cfg")) #elif defined(__UNIX__) #define CFG_FILE (home + _T(".poedit/config")) #else #define CFG_FILE wxEmptyString #endif #ifdef __WXMAC__ // upgrade from the old location of config file: wxString oldcfgfile = wxStandardPaths::Get().GetUserConfigDir() + _T("/poedit.cfg"); if (wxFileExists(oldcfgfile) && !wxFileExists(CFG_FILE)) { wxRenameFile(oldcfgfile, CFG_FILE); } #endif wxConfigBase::Set( new wxConfig(wxEmptyString, wxEmptyString, CFG_FILE, wxEmptyString, wxCONFIG_USE_GLOBAL_FILE | wxCONFIG_USE_LOCAL_FILE)); wxConfigBase::Get()->SetExpandEnvVars(false); wxImage::AddHandler(new wxGIFHandler); wxImage::AddHandler(new wxPNGHandler); wxXmlResource::Get()->InitAllHandlers(); InitXmlResource(); SetDefaultCfg(wxConfig::Get()); #ifdef HAS_INSERT_PROVIDER wxArtProvider::Insert(new PoeditArtProvider); #else wxArtProvider::PushProvider(new PoeditArtProvider); #endif #ifdef __WXMAC__ wxLocale::AddCatalogLookupPathPrefix( wxStandardPaths::Get().GetResourcesDir() + _T("/locale")); #else wxLocale::AddCatalogLookupPathPrefix(GetAppPath() + _T("/share/locale")); #endif m_locale.Init(GetUILanguage()); m_locale.AddCatalog(_T("poedit")); if (wxConfig::Get()->Read(_T("translator_name"), _T("nothing")) == _T("nothing")) { wxMessageBox(_("This is first time you run Poedit.\nPlease fill in your name and email address.\n(This information is used only in catalogs headers)"), _("Setup"), wxOK | wxICON_INFORMATION); PreferencesDialog dlg; dlg.TransferTo(wxConfig::Get()); if (dlg.ShowModal() == wxID_OK) dlg.TransferFrom(wxConfig::Get()); } // opening files or creating empty window is handled differently on Macs, // using MacOpenFile() and MacNewFile(), so don't do it here: #ifndef __WXMAC__ if (gs_filesToOpen.GetCount() == 0) { OpenNewFile(); } else { for (size_t i = 0; i < gs_filesToOpen.GetCount(); i++) OpenFile(gs_filesToOpen[i]); gs_filesToOpen.clear(); } #endif // !__WXMAC__ #ifdef USE_SPARKLE SUSparkleInitializeForCarbon(); #endif // USE_SPARKLE return true; } void PoeditApp::OpenNewFile() { if (wxConfig::Get()->Read(_T("manager_startup"), (long)false)) ManagerFrame::Create()->Show(true); else PoeditFrame::Create(wxEmptyString); } void PoeditApp::OpenFile(const wxString& name) { PoeditFrame::Create(name); } void PoeditApp::SetDefaultParsers(wxConfigBase *cfg) { ParsersDB pdb; bool changed = false; wxString defaultsVersion = cfg->Read(_T("Parsers/DefaultsVersion"), _T("1.2.x")); pdb.Read(cfg); // Add parsers for languages supported by gettext itself (but only if the // user didn't already add language with this name himself): static struct { const wxChar *name; const wxChar *exts; } s_gettextLangs[] = { { _T("C/C++"), _T("*.c;*.cpp;*.h;*.hpp;*.cc;*.C;*.cxx;*.hxx") }, #ifndef __WINDOWS__ // FIXME: not supported by 0.13.1 shipped with poedit on win32 { _T("C#"), _T("*.cs") }, #endif { _T("Java"), _T("*.java") }, { _T("Perl"), _T("*.pl") }, { _T("PHP"), _T("*.php") }, { _T("Python"), _T("*.py") }, { _T("TCL"), _T("*.tcl") }, { NULL, NULL } }; for (size_t i = 0; s_gettextLangs[i].name != NULL; i++) { // if this lang is already registered, don't overwrite it: if (pdb.FindParser(s_gettextLangs[i].name) != -1) continue; // otherwise add new parser: Parser p; p.Name = s_gettextLangs[i].name; p.Extensions = s_gettextLangs[i].exts; p.Command = _T("xgettext --force-po --omit-header -o %o %C %K %F"); p.KeywordItem = _T("-k%k"); p.FileItem = _T("%f"); p.CharsetItem = _T("--from-code=%c"); pdb.Add(p); changed = true; } // If upgrading Poedit to 1.2.4, add dxgettext parser for Delphi: #ifdef __WINDOWS__ if (defaultsVersion == _T("1.2.x")) { Parser p; p.Name = _T("Delphi (dxgettext)"); p.Extensions = _T("*.pas;*.dpr;*.xfm;*.dfm"); p.Command = _T("dxgettext --so %o %F"); p.KeywordItem = wxEmptyString; p.FileItem = _T("%f"); pdb.Add(p); changed = true; } #endif // If upgrading Poedit to 1.2.5, update C++ parser to handle --from-code: if (defaultsVersion == _T("1.2.x") || defaultsVersion == _T("1.2.4")) { int cpp = pdb.FindParser(_T("C/C++")); if (cpp != -1) { if (pdb[cpp].Command == _T("xgettext --force-po -o %o %K %F")) { pdb[cpp].Command = _T("xgettext --force-po --omit-header -o %o %C %K %F"); pdb[cpp].CharsetItem = _T("--from-code=%c"); changed = true; } } } // 1.4.0 adds --omit-header to parsers lines: for ( size_t i = 0; i < pdb.size(); ++i ) { if ( pdb[i].Command == _T("xgettext --force-po -o %o %C %K %F") ) { pdb[i].Command = _T("xgettext --force-po --omit-header -o %o %C %K %F"); changed = true; } } if (changed) { pdb.Write(cfg); cfg->Write(_T("Parsers/DefaultsVersion"), GetAppVersion()); } } void PoeditApp::SetDefaultCfg(wxConfigBase *cfg) { SetDefaultParsers(cfg); if (cfg->Read(_T("version"), wxEmptyString) == GetAppVersion()) return; if (cfg->Read(_T("TM/database_path"), wxEmptyString).empty()) { wxString dbpath; #if defined(__WXMAC__) dbpath = wxStandardPaths::Get().GetUserDataDir() + _T("/tm"); #elif defined(__UNIX__) dbpath = wxGetHomeDir() + _T("/.poedit/tm"); #elif defined(__WXMSW__) dbpath = wxGetHomeDir() + _T("\\poedit_tm"); #endif cfg->Write(_T("TM/database_path"), dbpath); } if (cfg->Read(_T("TM/search_paths"), wxEmptyString).empty()) { wxString paths; #if defined(__UNIX__) paths = wxGetHomeDir() + _T(":/usr/share/locale:/usr/local/share/locale"); #elif defined(__WXMSW__) paths = _T("C:"); #endif cfg->Write(_T("TM/search_paths"), paths); } cfg->Write(_T("version"), GetAppVersion()); } void PoeditApp::OnInitCmdLine(wxCmdLineParser& parser) { wxApp::OnInitCmdLine(parser); parser.AddParam(_T("catalog.po"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE); } bool PoeditApp::OnCmdLineParsed(wxCmdLineParser& parser) { if (!wxApp::OnCmdLineParsed(parser)) return false; #ifndef __WXMAC__ for (size_t i = 0; i < parser.GetParamCount(); i++) gs_filesToOpen.Add(parser.GetParam(i)); #endif return true; } <|endoftext|>
<commit_before>// Lesson 13.cpp : Defines the entry point for the console application. #include <render_framework\render_framework.h> #include <chrono> #pragma comment (lib , "Render Framework" ) using namespace std; using namespace glm; using namespace render_framework; using namespace chrono; #define OBJECTS 1 // Global scope box shared_ptr<mesh> object[1]; shared_ptr<arc_ball_camera> cam; shared_ptr<mesh> plane; float dissolveFactor = 1.0f; /* * userTranslation * * Moves the object around inside the window using the keyboard arrow keys. */ void userTranslation(float deltaTime) { // Move the quad when arrow keys are pressed if (glfwGetKey(renderer::get_instance().get_window(), 'J')) { object[0]->trans.translate(vec3(-10.0, 0.0, 0.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'L')) { object[0]->trans.translate(vec3(10.0, 0.0, 0.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'I')) { object[0]->trans.translate(vec3(0.0, 0.0, -10.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'K')) { object[0]->trans.translate(vec3(0.0, 0.0, 10.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'U')) { object[0]->trans.translate(vec3(0.0, 10.0, 0.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'O')) { object[0]->trans.translate(vec3(0.0, -10.0, 0.0) * deltaTime); } } // userTranslation() /* * cameraTranslation * * Moves the object around inside the window using the keyboard arrow keys. */ void cameraTranslation(float deltaTime) { // Move the quad when arrow keys are pressed if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) { cam->rotate(0.0, half_pi<float>() * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) { cam->rotate(0.0, -half_pi<float>() * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) { cam->move(-5.0f * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) { cam->move(5.0f * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'W')) { cam->rotate(half_pi<float>() * deltaTime, 0.0); } if (glfwGetKey(renderer::get_instance().get_window(), 'S')) { cam->rotate(-half_pi<float>() * deltaTime, 0.0); } } // cameraTranslation() /* * Update routine * * Updates the application state */ void update(float deltaTime) { cameraTranslation(deltaTime); userTranslation(deltaTime); cam->set_target(object[0]->trans.position); cam->update(deltaTime); } // update() bool load_content() { int i = 0; for (i=0;i<OBJECTS;i++) { // Create plane plane = make_shared<mesh>(); plane->geom = geometry_builder::create_plane(); plane->trans.translate(vec3(0.0f, -1.0f, 0.0f)); // Load in effect. Start with shaders auto eff = make_shared<effect>(); eff->add_shader("shader.vert", GL_VERTEX_SHADER); eff->add_shader("shader.frag", GL_FRAGMENT_SHADER); if (!effect_loader::build_effect(eff)) { return false; } // Attach effect to the plane mesh plane->mat = make_shared<material>(); plane->mat->effect = eff; // Set the texture for shader plane->mat->set_texture("tex", texture_loader::load("Checkered.png")); // Create box object[i] = make_shared<mesh>(); object[i]->geom = geometry_builder::create_torus(); // Load in effect. Start with shaders auto eff2 = make_shared<effect>(); eff2->add_shader("cell.vert", GL_VERTEX_SHADER); eff2->add_shader("cell.frag", GL_FRAGMENT_SHADER); if (!effect_loader::build_effect(eff2)) { return false; } // Attach effect to the object object[i]->mat = make_shared<material>(); object[i]->mat->effect = eff2; // Set textures for shader vector<vec4> colour; colour.push_back(vec4(0.12f, 0.0f, 0.0f, 1.0f)); colour.push_back(vec4(0.25f, 0.0f, 0.0f, 1.0)); colour.push_back(vec4(0.5f, 0.0f, 0.0f, 1.0)); colour.push_back(vec4(1.0f, 0.0f, 0.0f, 1.0)); auto tex = texture_generator::generate(colour, 4, 1, false, false); // Attach texture to the box effect object[i]->mat->set_texture("tex", tex); } return true; } // load_content() bool load_camera() { // Initialize the camera cam = make_shared<arc_ball_camera>(); /* Set the projection matrix */ // First get the aspect ratio (width/height) float aspect = (float)renderer::get_instance().get_screen_width() / (float)renderer::get_instance().get_screen_width(); // Use this to set the camera projection matrix cam->set_projection( quarter_pi<float>(), // FOV aspect, // Aspect ratio 2.414f, // Near plane 10000.0f); // Far plane // Set the camera properties cam->set_position(vec3(0.0, 0.0, 0.0)); cam->set_distance(20.0f); // Attach camera to renderer renderer::get_instance().set_camera(cam); // Set the view matrix auto view = lookAt( vec3(20.0f, 20.0f, 20.0f), // Camera position vec3(0.0f, 0.0f, 0.0f), // Target vec3(0.0f, 1.0f, 0.0f)); // Up vector renderer::get_instance().set_view(view); return true; } // load_camera int main() { // Initialize the renderer if (!renderer::get_instance().initialise()) return -1; // Set the clear colour to cyan glClearColor(0.0f, 1.0f, 1.0f, 1.0f); if (!load_content()) { return -1; } if (!load_camera()) { return -1; } // Monitor the elapsed time per frame auto currentTimeStamp = system_clock::now(); auto prevTimeStamp = system_clock::now(); // Main render loop while (renderer::get_instance().is_running()) { // Get current time currentTimeStamp = system_clock::now(); // Calculate elapsed time auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp); // Convert to fractions of a second auto seconds = float(elapsed.count()) / 1000.0; // Update Scene update(seconds); // Check if running if (renderer::get_instance().begin_render()) { // Render Cube int i = 0; for (i = 0; i <OBJECTS; i++) { renderer::get_instance().render(object[i]); } // Render plane renderer::get_instance().render(plane); // End the render renderer::get_instance().end_render(); } prevTimeStamp = currentTimeStamp; } // Main render loop }<commit_msg>Implemented mipmaps and anisstropic filtering<commit_after>// Lesson 13.cpp : Defines the entry point for the console application. #include <render_framework\render_framework.h> #include <chrono> #pragma comment (lib , "Render Framework" ) using namespace std; using namespace glm; using namespace render_framework; using namespace chrono; #define OBJECTS 2 // Global scope box shared_ptr<mesh> object[OBJECTS]; shared_ptr<target_camera> cam; shared_ptr<mesh> plane; /* * userTranslation * * Moves the object around inside the window using the keyboard arrow keys. */ void userTranslation(float deltaTime) { // Move the quad when arrow keys are pressed if (glfwGetKey(renderer::get_instance().get_window(), 'J')) { object[0]->trans.translate(vec3(-10.0, 0.0, 0.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'L')) { object[0]->trans.translate(vec3(10.0, 0.0, 0.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'I')) { object[0]->trans.translate(vec3(0.0, 0.0, -10.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'K')) { object[0]->trans.translate(vec3(0.0, 0.0, 10.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'U')) { object[0]->trans.translate(vec3(0.0, 10.0, 0.0) * deltaTime); } if (glfwGetKey(renderer::get_instance().get_window(), 'O')) { object[0]->trans.translate(vec3(0.0, -10.0, 0.0) * deltaTime); } } // userTranslation() /* * cameraTranslation * * Moves the object around inside the window using the keyboard arrow keys. */ void cameraTranslation(float deltaTime) { if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) { cam->set_position(cam->get_position() - 1.0f); } if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) { cam->set_position(cam->get_position() + 1.0f); } } // cameraTranslation() /* * Update routine * * Updates the application state */ void update(float deltaTime) { cameraTranslation(deltaTime); userTranslation(deltaTime); cam->set_target(object[0]->trans.position); cam->update(deltaTime); } // update() bool load_content() { // Create plane plane = make_shared<mesh>(); plane->geom = geometry_builder::create_plane(); plane->trans.translate(vec3(0.0f, -1.0f, 0.0f)); // Load in effect. Start with shaders auto eff = make_shared<effect>(); eff->add_shader("shader.vert", GL_VERTEX_SHADER); eff->add_shader("shader.frag", GL_FRAGMENT_SHADER); if (!effect_loader::build_effect(eff)) { return false; } // Attach effect to the plane mesh plane->mat = make_shared<material>(); plane->mat->effect = eff; // Set the texture for shader plane->mat->set_texture("tex", texture_loader::load("Checkered.png", true, true)); // Create box object[0] = make_shared<mesh>(); object[0]->geom = geometry_builder::create_box(); // Attach effect to the object object[0]->mat = make_shared<material>(); object[0]->mat->effect = eff; // Set the texture for shader object[0]->mat->set_texture("tex", texture_loader::load("Checkered.png", false, false)); // Scale and move object object[0]->trans.scale = vec3(10.0, 20.0, 0.5); object[0]->trans.translate(vec3(0.0, 9.5, 0.0)); // Create box object[1] = make_shared<mesh>(); object[1]->geom = geometry_builder::create_box(); // Attach effect to the object object[1]->mat = make_shared<material>(); object[1]->mat->effect = eff; // Set the texture for shader object[1]->mat->set_texture("tex", texture_loader::load("Checkered.png", true, false)); object[1]->trans.scale = vec3(10.0, 20.0, 0.5); object[1]->trans.translate(vec3(10.0, 9.5, 0.0)); return true; } // load_content() bool load_camera() { // Initialize the camera cam = make_shared<target_camera>(); /* Set the projection matrix */ // First get the aspect ratio (width/height) float aspect = (float)renderer::get_instance().get_screen_width() / (float)renderer::get_instance().get_screen_width(); // Use this to set the camera projection matrix cam->set_projection( quarter_pi<float>(), // FOV aspect, // Aspect ratio 2.414f, // Near plane 10000.0f); // Far plane // Set the camera properties cam->set_position(vec3(0.0, 5.0, 20.0)); cam->set_target(vec3(0.0, 0.0, 0.0)); cam->set_up(vec3(0.0, 1.0, 0.0)); // Attach camera to renderer renderer::get_instance().set_camera(cam); // Set the view matrix auto view = lookAt( vec3(20.0f, 20.0f, 20.0f), // Camera position vec3(0.0f, 0.0f, 0.0f), // Target vec3(0.0f, 1.0f, 0.0f)); // Up vector renderer::get_instance().set_view(view); return true; } // load_camera int main() { // Initialize the renderer if (!renderer::get_instance().initialise()) return -1; // Set the clear colour to cyan glClearColor(0.0f, 1.0f, 1.0f, 1.0f); if (!load_content()) { return -1; } if (!load_camera()) { return -1; } // Monitor the elapsed time per frame auto currentTimeStamp = system_clock::now(); auto prevTimeStamp = system_clock::now(); // Main render loop while (renderer::get_instance().is_running()) { // Get current time currentTimeStamp = system_clock::now(); // Calculate elapsed time auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp); // Convert to fractions of a second auto seconds = float(elapsed.count()) / 1000.0; // Update Scene update(seconds); // Check if running if (renderer::get_instance().begin_render()) { // Render Cube int i = 0; for (i = 0; i <OBJECTS; i++) { renderer::get_instance().render(object[i]); } // Render plane renderer::get_instance().render(plane); // End the render renderer::get_instance().end_render(); } prevTimeStamp = currentTimeStamp; } // Main render loop }<|endoftext|>
<commit_before>#include <iostream> #include <stdexcept> #include <string> #include "environment.h" #include "filescriptsource.h" #include "lexer.h" #include "log.h" #include "nullostream.h" #include "parser.h" #include "peachyparser.h" #include "runtime.h" #include "script.h" #include "scriptsource.h" #include "tokenfactory.h" #include "tokensource.h" using namespace peachy; int main(int argc, char ** argv) { (void) argc; (void) argv; NullOStream * nullOStream = new NullOStream; Log * nullLogger = new Log(nullOStream); Log * debugLogger = new Log(&std::cout); debugLogger->info("Peachy test harness"); ScriptSource * scriptSource; try { scriptSource = new FileScriptSource(nullLogger, "test.peachy"); } catch(std::runtime_error e) { debugLogger->info("Unable to acquire script source"); goto shortexit; } Environment * environment = new Environment(nullLogger); Runtime * runtime = new Runtime(nullLogger); TokenFactory * tokenFactory = new TokenFactory(nullLogger, nullLogger); TokenSource * tokenSource = new Lexer(nullLogger, tokenFactory, scriptSource); Parser * parser = new PeachyParser(debugLogger, tokenSource); Script * script = new Script(nullLogger, environment, runtime, parser); script->run(); delete script; delete parser; delete tokenSource; delete tokenFactory; delete runtime; delete environment; delete scriptSource; shortexit: delete nullLogger; delete nullOStream; debugLogger->info("Test harness complete"); delete debugLogger; return 0; } <commit_msg>removed unused args<commit_after>#include <iostream> #include <stdexcept> #include <string> #include "environment.h" #include "filescriptsource.h" #include "lexer.h" #include "log.h" #include "nullostream.h" #include "parser.h" #include "peachyparser.h" #include "runtime.h" #include "script.h" #include "scriptsource.h" #include "tokenfactory.h" #include "tokensource.h" using namespace peachy; int main() { NullOStream * nullOStream = new NullOStream; Log * nullLogger = new Log(nullOStream); Log * debugLogger = new Log(&std::cout); debugLogger->info("Peachy test harness"); ScriptSource * scriptSource; try { scriptSource = new FileScriptSource(nullLogger, "test.peachy"); } catch(std::runtime_error e) { debugLogger->info("Unable to acquire script source"); goto shortexit; } Environment * environment = new Environment(nullLogger); Runtime * runtime = new Runtime(nullLogger); TokenFactory * tokenFactory = new TokenFactory(nullLogger, nullLogger); TokenSource * tokenSource = new Lexer(nullLogger, tokenFactory, scriptSource); Parser * parser = new PeachyParser(debugLogger, tokenSource); Script * script = new Script(nullLogger, environment, runtime, parser); script->run(); delete script; delete parser; delete tokenSource; delete tokenFactory; delete runtime; delete environment; delete scriptSource; shortexit: delete nullLogger; delete nullOStream; debugLogger->info("Test harness complete"); delete debugLogger; return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <ctime> #include <new> #include <algorithm> #include <climits> #include <unistd.h> #include <cstring> #include "Swimd.h" using namespace std; void fillRandomly(unsigned char* seq, int seqLength, int alphabetLength); int * createSimpleScoreMatrix(int alphabetLength, int match, int mismatch); int calculateSW(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[], int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, SwimdSearchResult results[]); int calculateGlobal(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[], int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, SwimdSearchResult results[], const int); void printInts(int a[], int aLength); int maximumScore(SwimdSearchResult results[], int resultsLength); int main(int argc, char * const argv[]) { char mode[32] = "SW"; // "SW", "NW", "HW" or "OV" if (argc > 1) { strcpy(mode, argv[1]); } clock_t start, finish; srand(42); int alphabetLength = 4; int gapOpen = 11; int gapExt = 1; // Create random query int queryLength = 1000; unsigned char query[queryLength]; fillRandomly(query, queryLength, alphabetLength); // Create random database int dbLength = 200; unsigned char * db[dbLength]; int dbSeqsLengths[dbLength]; for (int i = 0; i < dbLength; i++) { dbSeqsLengths[i] = 800 + rand() % 4000; db[i] = new unsigned char[dbSeqsLengths[i]]; fillRandomly(db[i], dbSeqsLengths[i], alphabetLength); } /* printf("Query:\n"); for (int i = 0; i < queryLength; i++) printf("%d ", query[i]); printf("\n"); printf("Database:\n"); for (int i = 0; i < dbLength; i++) { printf("%d. ", i); for (int j = 0; j < dbSeqsLengths[i]; j++) printf("%d ", db[i][j]); printf("\n"); } */ // Create score matrix int * scoreMatrix = createSimpleScoreMatrix(alphabetLength, 3, -1); // Run Swimd printf("Starting Swimd!\n"); #ifdef __AVX2__ printf("Using AVX2!\n"); #elif __SSE4_1__ printf("Using SSE4.1!\n"); #endif start = clock(); SwimdSearchResult results[dbLength]; int resultCode; int modeCode; if (!strcmp(mode, "NW")) modeCode = SWIMD_MODE_NW; else if (!strcmp(mode, "HW")) modeCode = SWIMD_MODE_HW; else if (!strcmp(mode, "OV")) modeCode = SWIMD_MODE_OV; else if (!strcmp(mode, "SW")) modeCode = SWIMD_MODE_SW; else { printf("Invalid mode!\n"); return 1; } resultCode = swimdSearchDatabase(query, queryLength, db, dbLength, dbSeqsLengths, gapOpen, gapExt, scoreMatrix, alphabetLength, results, modeCode, SWIMD_OVERFLOW_SIMPLE); finish = clock(); double time1 = ((double)(finish-start)) / CLOCKS_PER_SEC; printf("Time: %lf\n", time1); if (resultCode != 0) { printf("Overflow happened!"); exit(0); } printf("Maximum: %d\n", maximumScore(results, dbLength)); printf("\n"); // Run normal SW printf("Starting normal!\n"); start = clock(); SwimdSearchResult results2[dbLength]; if (!strcmp(mode, "SW")) { resultCode = calculateSW(query, queryLength, db, dbLength, dbSeqsLengths, gapOpen, gapExt, scoreMatrix, alphabetLength, results2); } else { resultCode = calculateGlobal(query, queryLength, db, dbLength, dbSeqsLengths, gapOpen, gapExt, scoreMatrix, alphabetLength, results2, modeCode); } finish = clock(); double time2 = ((double)(finish-start))/CLOCKS_PER_SEC; printf("Time: %lf\n", time2); printf("Maximum: %d\n", maximumScore(results2, dbLength)); printf("\n"); // Print differences in scores (hopefully there are none!) for (int i = 0; i < dbLength; i++) { if (results[i].score != results2[i].score) { printf("#%d: score is %d but should be %d\n", i, results[i].score, results2[i].score); } if (results[i].endLocationTarget != results2[i].endLocationTarget) { printf("#%d: end location in target is %d but should be %d\n", i, results[i].endLocationTarget, results2[i].endLocationTarget); } if (results[i].endLocationQuery != results2[i].endLocationQuery) { printf("#%d: end location in query is %d but should be %d\n", i, results[i].endLocationQuery, results2[i].endLocationQuery); } //printf("#%d: score -> %d, end location -> (q: %d, t: %d)\n", // i, results[i].score, results[i].endLocationQuery, results[i].endLocationTarget); } printf("Times faster: %lf\n", time2/time1); // Free allocated memory for (int i = 0; i < dbLength; i++) { delete[] db[i]; } delete[] scoreMatrix; } void fillRandomly(unsigned char* seq, int seqLength, int alphabetLength) { for (int i = 0; i < seqLength; i++) seq[i] = rand() % alphabetLength; } int* createSimpleScoreMatrix(int alphabetLength, int match, int mismatch) { int * scoreMatrix = new int[alphabetLength*alphabetLength]; for (int i = 0; i < alphabetLength; i++) { for (int j = 0; j < alphabetLength; j++) scoreMatrix[i * alphabetLength + j] = (i==j ? match : mismatch); } return scoreMatrix; } int calculateSW(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[], int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, SwimdSearchResult results[]) { int prevHs[queryLength]; int prevEs[queryLength]; for (int seqIdx = 0; seqIdx < dbLength; seqIdx++) { int maxH = 0; int endLocationTarget = 0; int endLocationQuery = 0; // Initialize all values to 0 for (int i = 0; i < queryLength; i++) { prevHs[i] = prevEs[i] = 0; } for (int c = 0; c < dbSeqLengths[seqIdx]; c++) { int uF, uH, ulH; uF = uH = ulH = 0; for (int r = 0; r < queryLength; r++) { int E = max(prevHs[r] - gapOpen, prevEs[r] - gapExt); int F = max(uH - gapOpen, uF - gapExt); int score = scoreMatrix[query[r] * alphabetLength + db[seqIdx][c]]; int H = max(0, max(E, max(F, ulH+score))); if (H > maxH) { endLocationTarget = c; endLocationQuery = r; maxH = H; } uF = F; uH = H; ulH = prevHs[r]; prevHs[r] = H; prevEs[r] = E; } } results[seqIdx].score = maxH; results[seqIdx].endLocationTarget = endLocationTarget; results[seqIdx].endLocationQuery = endLocationQuery; } return 0; } int calculateGlobal(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[], int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, SwimdSearchResult results[], const int mode) { int prevHs[queryLength]; int prevEs[queryLength]; const int LOWER_SCORE_BOUND = INT_MIN + gapExt; for (int seqIdx = 0; seqIdx < dbLength; seqIdx++) { // Initialize all values to 0 for (int r = 0; r < queryLength; r++) { // Query has fixed start and end if not OV prevHs[r] = mode == SWIMD_MODE_OV ? 0 : -1 * gapOpen - r * gapExt; prevEs[r] = LOWER_SCORE_BOUND; } int maxH = INT_MIN; int endLocationTarget = 0; int endLocationQuery = 0; int H = INT_MIN; int targetLength = dbSeqLengths[seqIdx]; for (int c = 0; c < targetLength; c++) { int uF, uH, ulH; uF = LOWER_SCORE_BOUND; if (mode == SWIMD_MODE_NW) { // Database sequence has fixed start and end only in NW uH = -1 * gapOpen - c * gapExt; ulH = uH + gapExt; } else { uH = ulH = 0; } if (c == 0) ulH = 0; for (int r = 0; r < queryLength; r++) { int E = max(prevHs[r] - gapOpen, prevEs[r] - gapExt); int F = max(uH - gapOpen, uF - gapExt); int score = scoreMatrix[query[r] * alphabetLength + db[seqIdx][c]]; H = max(E, max(F, ulH+score)); if (mode == SWIMD_MODE_OV && c == targetLength - 1) { if (H > maxH) { maxH = H; endLocationQuery = r; endLocationTarget = c; } } uF = F; uH = H; ulH = prevHs[r]; prevHs[r] = H; prevEs[r] = E; } if (H > maxH) { maxH = H; endLocationTarget = c; endLocationQuery = queryLength - 1; } } if (mode == SWIMD_MODE_NW) { results[seqIdx].score = H; results[seqIdx].endLocationTarget = targetLength - 1; results[seqIdx].endLocationQuery = queryLength - 1; } else if (mode == SWIMD_MODE_OV || mode == SWIMD_MODE_HW) { results[seqIdx].score = maxH; results[seqIdx].endLocationTarget = endLocationTarget; results[seqIdx].endLocationQuery = endLocationQuery; } else return 1; } return 0; } void printInts(int a[], int aLength) { for (int i = 0; i < aLength; i++) printf("%d ", a[i]); printf("\n"); } int maximumScore(SwimdSearchResult results[], int resultsLength) { int maximum = 0; for (int i = 0; i < resultsLength; i++) if (results[i].score > maximum) maximum = results[i].score; return maximum; } <commit_msg>Nicer error reporing in test.<commit_after>#include <cstdio> #include <cstdlib> #include <ctime> #include <new> #include <algorithm> #include <climits> #include <unistd.h> #include <cstring> #include "Swimd.h" using namespace std; void fillRandomly(unsigned char* seq, int seqLength, int alphabetLength); int * createSimpleScoreMatrix(int alphabetLength, int match, int mismatch); int calculateSW(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[], int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, SwimdSearchResult results[]); int calculateGlobal(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[], int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, SwimdSearchResult results[], const int); void printInts(int a[], int aLength); int maximumScore(SwimdSearchResult results[], int resultsLength); int main(int argc, char * const argv[]) { char mode[32] = "SW"; // "SW", "NW", "HW" or "OV" if (argc > 1) { strcpy(mode, argv[1]); } clock_t start, finish; srand(42); int alphabetLength = 4; int gapOpen = 11; int gapExt = 1; // Create random query int queryLength = 1000; unsigned char query[queryLength]; fillRandomly(query, queryLength, alphabetLength); // Create random database int dbLength = 200; unsigned char * db[dbLength]; int dbSeqsLengths[dbLength]; for (int i = 0; i < dbLength; i++) { dbSeqsLengths[i] = 800 + rand() % 4000; db[i] = new unsigned char[dbSeqsLengths[i]]; fillRandomly(db[i], dbSeqsLengths[i], alphabetLength); } /* printf("Query:\n"); for (int i = 0; i < queryLength; i++) printf("%d ", query[i]); printf("\n"); printf("Database:\n"); for (int i = 0; i < dbLength; i++) { printf("%d. ", i); for (int j = 0; j < dbSeqsLengths[i]; j++) printf("%d ", db[i][j]); printf("\n"); } */ // Create score matrix int * scoreMatrix = createSimpleScoreMatrix(alphabetLength, 3, -1); // Run Swimd printf("Starting Swimd!\n"); #ifdef __AVX2__ printf("Using AVX2!\n"); #elif __SSE4_1__ printf("Using SSE4.1!\n"); #endif start = clock(); SwimdSearchResult results[dbLength]; int resultCode; int modeCode; if (!strcmp(mode, "NW")) modeCode = SWIMD_MODE_NW; else if (!strcmp(mode, "HW")) modeCode = SWIMD_MODE_HW; else if (!strcmp(mode, "OV")) modeCode = SWIMD_MODE_OV; else if (!strcmp(mode, "SW")) modeCode = SWIMD_MODE_SW; else { printf("Invalid mode!\n"); return 1; } resultCode = swimdSearchDatabase(query, queryLength, db, dbLength, dbSeqsLengths, gapOpen, gapExt, scoreMatrix, alphabetLength, results, modeCode, SWIMD_OVERFLOW_SIMPLE); finish = clock(); double time1 = ((double)(finish-start)) / CLOCKS_PER_SEC; if (resultCode == SWIMD_ERR_OVERFLOW) { printf("Error: overflow happened!\n"); exit(0); } if (resultCode == SWIMD_ERR_NO_SIMD_SUPPORT) { printf("Error: no SIMD support!\n"); exit(0); } printf("Time: %lf\n", time1); printf("Maximum: %d\n", maximumScore(results, dbLength)); printf("\n"); // Run normal SW printf("Starting normal!\n"); start = clock(); SwimdSearchResult results2[dbLength]; if (!strcmp(mode, "SW")) { resultCode = calculateSW(query, queryLength, db, dbLength, dbSeqsLengths, gapOpen, gapExt, scoreMatrix, alphabetLength, results2); } else { resultCode = calculateGlobal(query, queryLength, db, dbLength, dbSeqsLengths, gapOpen, gapExt, scoreMatrix, alphabetLength, results2, modeCode); } finish = clock(); double time2 = ((double)(finish-start))/CLOCKS_PER_SEC; printf("Time: %lf\n", time2); printf("Maximum: %d\n", maximumScore(results2, dbLength)); printf("\n"); // Print differences in scores (hopefully there are none!) for (int i = 0; i < dbLength; i++) { if (results[i].score != results2[i].score) { printf("#%d: score is %d but should be %d\n", i, results[i].score, results2[i].score); } if (results[i].endLocationTarget != results2[i].endLocationTarget) { printf("#%d: end location in target is %d but should be %d\n", i, results[i].endLocationTarget, results2[i].endLocationTarget); } if (results[i].endLocationQuery != results2[i].endLocationQuery) { printf("#%d: end location in query is %d but should be %d\n", i, results[i].endLocationQuery, results2[i].endLocationQuery); } //printf("#%d: score -> %d, end location -> (q: %d, t: %d)\n", // i, results[i].score, results[i].endLocationQuery, results[i].endLocationTarget); } printf("Times faster: %lf\n", time2/time1); // Free allocated memory for (int i = 0; i < dbLength; i++) { delete[] db[i]; } delete[] scoreMatrix; } void fillRandomly(unsigned char* seq, int seqLength, int alphabetLength) { for (int i = 0; i < seqLength; i++) seq[i] = rand() % alphabetLength; } int* createSimpleScoreMatrix(int alphabetLength, int match, int mismatch) { int * scoreMatrix = new int[alphabetLength*alphabetLength]; for (int i = 0; i < alphabetLength; i++) { for (int j = 0; j < alphabetLength; j++) scoreMatrix[i * alphabetLength + j] = (i==j ? match : mismatch); } return scoreMatrix; } int calculateSW(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[], int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, SwimdSearchResult results[]) { int prevHs[queryLength]; int prevEs[queryLength]; for (int seqIdx = 0; seqIdx < dbLength; seqIdx++) { int maxH = 0; int endLocationTarget = 0; int endLocationQuery = 0; // Initialize all values to 0 for (int i = 0; i < queryLength; i++) { prevHs[i] = prevEs[i] = 0; } for (int c = 0; c < dbSeqLengths[seqIdx]; c++) { int uF, uH, ulH; uF = uH = ulH = 0; for (int r = 0; r < queryLength; r++) { int E = max(prevHs[r] - gapOpen, prevEs[r] - gapExt); int F = max(uH - gapOpen, uF - gapExt); int score = scoreMatrix[query[r] * alphabetLength + db[seqIdx][c]]; int H = max(0, max(E, max(F, ulH+score))); if (H > maxH) { endLocationTarget = c; endLocationQuery = r; maxH = H; } uF = F; uH = H; ulH = prevHs[r]; prevHs[r] = H; prevEs[r] = E; } } results[seqIdx].score = maxH; results[seqIdx].endLocationTarget = endLocationTarget; results[seqIdx].endLocationQuery = endLocationQuery; } return 0; } int calculateGlobal(unsigned char query[], int queryLength, unsigned char ** db, int dbLength, int dbSeqLengths[], int gapOpen, int gapExt, int * scoreMatrix, int alphabetLength, SwimdSearchResult results[], const int mode) { int prevHs[queryLength]; int prevEs[queryLength]; const int LOWER_SCORE_BOUND = INT_MIN + gapExt; for (int seqIdx = 0; seqIdx < dbLength; seqIdx++) { // Initialize all values to 0 for (int r = 0; r < queryLength; r++) { // Query has fixed start and end if not OV prevHs[r] = mode == SWIMD_MODE_OV ? 0 : -1 * gapOpen - r * gapExt; prevEs[r] = LOWER_SCORE_BOUND; } int maxH = INT_MIN; int endLocationTarget = 0; int endLocationQuery = 0; int H = INT_MIN; int targetLength = dbSeqLengths[seqIdx]; for (int c = 0; c < targetLength; c++) { int uF, uH, ulH; uF = LOWER_SCORE_BOUND; if (mode == SWIMD_MODE_NW) { // Database sequence has fixed start and end only in NW uH = -1 * gapOpen - c * gapExt; ulH = uH + gapExt; } else { uH = ulH = 0; } if (c == 0) ulH = 0; for (int r = 0; r < queryLength; r++) { int E = max(prevHs[r] - gapOpen, prevEs[r] - gapExt); int F = max(uH - gapOpen, uF - gapExt); int score = scoreMatrix[query[r] * alphabetLength + db[seqIdx][c]]; H = max(E, max(F, ulH+score)); if (mode == SWIMD_MODE_OV && c == targetLength - 1) { if (H > maxH) { maxH = H; endLocationQuery = r; endLocationTarget = c; } } uF = F; uH = H; ulH = prevHs[r]; prevHs[r] = H; prevEs[r] = E; } if (H > maxH) { maxH = H; endLocationTarget = c; endLocationQuery = queryLength - 1; } } if (mode == SWIMD_MODE_NW) { results[seqIdx].score = H; results[seqIdx].endLocationTarget = targetLength - 1; results[seqIdx].endLocationQuery = queryLength - 1; } else if (mode == SWIMD_MODE_OV || mode == SWIMD_MODE_HW) { results[seqIdx].score = maxH; results[seqIdx].endLocationTarget = endLocationTarget; results[seqIdx].endLocationQuery = endLocationQuery; } else return 1; } return 0; } void printInts(int a[], int aLength) { for (int i = 0; i < aLength; i++) printf("%d ", a[i]); printf("\n"); } int maximumScore(SwimdSearchResult results[], int resultsLength) { int maximum = 0; for (int i = 0; i < resultsLength; i++) if (results[i].score > maximum) maximum = results[i].score; return maximum; } <|endoftext|>
<commit_before>/******************************************************************************* Copyright (c) 2019, Jan Koester [email protected] 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 <organization> 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 <COPYRIGHT HOLDER> 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 <systempp/sysinfo.h> #include <systempp/sysconsole.h> #include <config.h> #include "connections.h" #include "eventapi.h" #include "threadpool.h" #include "exception.h" #include "event.h" bool libhttppp::Event::_Run=true; bool libhttppp::Event::_Restart=false; libhttppp::Event::Event(libsystempp::ServerSocket* serversocket) : EVENT(serversocket){ // libhttppp::CtrlHandler::initCtrlHandler(); } libhttppp::Event::~Event(){ } libhttppp::EventApi::~EventApi(){ } void libhttppp::Event::runEventloop(){ libsystempp::CpuInfo cpuinfo; size_t thrs = cpuinfo.getCores(); initEventHandler(); MAINWORKERLOOP: ThreadPool thpool; for (size_t i = 0; i < thrs; i++) { libsystempp::Thread *cthread=thpool.addThread(); try{ cthread->Create(WorkerThread, (void*)this); }catch(HTTPException &e){ throw e; } for (libsystempp::Thread *curth = thpool.getfirstThread(); curth; curth = curth->nextThread) { curth->Join(); } } if(libhttppp::Event::_Restart){ libhttppp::Event::_Restart=false; goto MAINWORKERLOOP; } } void * libhttppp::Event::WorkerThread(void* wrkevent){ Event *eventptr=((Event*)wrkevent); HTTPException excep; while (libhttppp::Event::_Run) { try { for (int i = 0; i < eventptr->waitEventHandler(); ++i) { int state=eventptr->StatusEventHandler(i); if(state==EventHandlerStatus::EVNOTREADY) eventptr->ConnectEventHandler(i); if(eventptr->LockConnection(i)==LockState::LOCKED){ try{ switch(state){ case EventHandlerStatus::EVIN: eventptr->ReadEventHandler(i); break; case EventHandlerStatus::EVOUT: eventptr->WriteEventHandler(i); break; default: throw excep[HTTPException::Error] << "no action try to close"; break; } eventptr->UnlockConnection(i); }catch(HTTPException &e){ eventptr->CloseEventHandler(i); if(e.getErrorType()==HTTPException::Critical){ eventptr->UnlockConnection(i); throw e; } libsystempp::Console[SYSOUT] << e.what() << libsystempp::Console[SYSOUT].endl; eventptr->UnlockConnection(i); } } } }catch(HTTPException &e){ switch(e.getErrorType()){ case HTTPException::Critical: throw e; break; default: libsystempp::Console[SYSOUT] << e.what() << libsystempp::Console[SYSOUT].endl; } } } return NULL; } <commit_msg>removed not more needed os folder<commit_after>/******************************************************************************* Copyright (c) 2019, Jan Koester [email protected] 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 <organization> 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 <COPYRIGHT HOLDER> 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 <systempp/sysinfo.h> #include <systempp/sysconsole.h> #include "config.h" #include "connections.h" #include "eventapi.h" #include "threadpool.h" #include "exception.h" #include "event.h" bool libhttppp::Event::_Run=true; bool libhttppp::Event::_Restart=false; libhttppp::Event::Event(libsystempp::ServerSocket* serversocket) : EVENT(serversocket){ // libhttppp::CtrlHandler::initCtrlHandler(); } libhttppp::Event::~Event(){ } libhttppp::EventApi::~EventApi(){ } void libhttppp::Event::runEventloop(){ libsystempp::CpuInfo cpuinfo; size_t thrs = cpuinfo.getCores(); initEventHandler(); MAINWORKERLOOP: ThreadPool thpool; for (size_t i = 0; i < thrs; i++) { libsystempp::Thread *cthread=thpool.addThread(); try{ cthread->Create(WorkerThread, (void*)this); }catch(HTTPException &e){ throw e; } for (libsystempp::Thread *curth = thpool.getfirstThread(); curth; curth = curth->nextThread) { curth->Join(); } } if(libhttppp::Event::_Restart){ libhttppp::Event::_Restart=false; goto MAINWORKERLOOP; } } void * libhttppp::Event::WorkerThread(void* wrkevent){ Event *eventptr=((Event*)wrkevent); HTTPException excep; while (libhttppp::Event::_Run) { try { for (int i = 0; i < eventptr->waitEventHandler(); ++i) { int state=eventptr->StatusEventHandler(i); if(state==EventHandlerStatus::EVNOTREADY) eventptr->ConnectEventHandler(i); if(eventptr->LockConnection(i)==LockState::LOCKED){ try{ switch(state){ case EventHandlerStatus::EVIN: eventptr->ReadEventHandler(i); break; case EventHandlerStatus::EVOUT: eventptr->WriteEventHandler(i); break; default: throw excep[HTTPException::Error] << "no action try to close"; break; } eventptr->UnlockConnection(i); }catch(HTTPException &e){ eventptr->CloseEventHandler(i); if(e.getErrorType()==HTTPException::Critical){ eventptr->UnlockConnection(i); throw e; } libsystempp::Console[SYSOUT] << e.what() << libsystempp::Console[SYSOUT].endl; eventptr->UnlockConnection(i); } } } }catch(HTTPException &e){ switch(e.getErrorType()){ case HTTPException::Critical: throw e; break; default: libsystempp::Console[SYSOUT] << e.what() << libsystempp::Console[SYSOUT].endl; } } } return NULL; } <|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_TYPES_INHERIT_LINEARLY_HPP #define BOOST_BRIGAND_TYPES_INHERIT_LINEARLY_HPP #include <brigand/algorithms/fold.hpp> #include <brigand/types/empty_base.hpp> namespace brigand { namespace lazy { template< typename Types , typename Node , typename Root = brigand::empty_base > struct inherit_linearly; template< typename Types , template<typename...> class Node, typename...Ts , typename Root > struct inherit_linearly<Types,Node<Ts...>,Root> { // TODO: change after lazy-fication using type = brigand::fold<Types,Root,bind<Node,Ts...>>; }; } template< typename Types , typename Node , typename Root = brigand::empty_base > using inherit_linearly = typename lazy::inherit_linearly<Types,Node,Root>::type; } #endif <commit_msg>Delete inherit_linearly.hpp<commit_after><|endoftext|>
<commit_before>#include "graph.hpp" void align_sequence (DnaString & my_sequence, boost::dynamic_bitset<> & qual, TGraph const & graph, std::vector<VertexLabels> & vertex_vector, String<TVertexDescriptor> & order, std::vector<ExactBacktracker> & backtracker, std::vector<ExactBacktracker> & reverse_backtracker, boost::unordered_set<TVertexDescriptor> const & free_nodes, std::vector<TVertexDescriptor> & matching_vertices, std::vector<TVertexDescriptor> & reverse_matching_vertices ) { initializeExactScoreMatrixAndBacktracker(length(my_sequence), length(order), backtracker); reverse_backtracker = backtracker; alignToGraphExact (my_sequence, order, graph, matching_vertices, vertex_vector, backtracker, free_nodes, qual ); reverseComplement(my_sequence); boost::dynamic_bitset<> qual_reversed(qual.size()); std::size_t qual_size = qual.size(); for (unsigned pos = 0 ; pos < qual_size ; ++pos) { if (qual.test(pos)) { qual_reversed[qual_size-pos-1] = 1; } } alignToGraphExact (my_sequence, order, graph, reverse_matching_vertices, vertex_vector, reverse_backtracker, free_nodes, qual ); reverseComplement(my_sequence); } boost::dynamic_bitset<> align_sequence_kmer (String<Dna> & my_sequence, String<char> & qual, unsigned const & id_numbers, TKmerMap & kmer_map, std::vector<VertexLabels> & vertex_vector, int const & kmer_size, int const & min_kmers ) { unsigned best_kmer_index = find_best_kmer(qual, kmer_size); boost::dynamic_bitset<> matched_ids = align_kmer_to_graph (my_sequence, id_numbers, kmer_map, vertex_vector, best_kmer_index, kmer_size, min_kmers ); if (matched_ids.find_first() != matched_ids.npos) { return matched_ids; } reverseComplement(my_sequence); matched_ids = align_kmer_to_graph (my_sequence, id_numbers, kmer_map, vertex_vector, best_kmer_index, kmer_size, min_kmers ); reverseComplement(my_sequence); return matched_ids; } CharString myExtractTagValue(String<char> &tags) { BamTagsDict tagsDict(tags); unsigned tagIdx = 0; if (!findTagKey(tagIdx, tagsDict, "RG")) { return ""; } CharString read_group; if (!extractTagValue(read_group, tagsDict, tagIdx)) { std::cerr << "Not a valid string at pos " << tagIdx << std::endl; return ""; } return read_group; } void createGenericGraph(callOptions & CO, TGraph & graph, std::vector<VertexLabels> & vertex_vector, std::vector<std::string> & ids, boost::unordered_map< std::pair<TVertexDescriptor, TVertexDescriptor>, boost::dynamic_bitset<> > & edge_ids, boost::unordered_set<TVertexDescriptor> & free_nodes, String<TVertexDescriptor> & order ) { int number_of_exons = CO.number_of_exons; std::stringstream base_path; base_path << gyper_SOURCE_DIRECTORY << "/data/haplotypes/hla/references/" << CO.gene << "/"; TVertexDescriptor begin_vertex; { std::string p3_string = base_path.str(); p3_string.append("p3.fa"); if (CO.verbose) { std::cout << "Adding utr " << p3_string << std::endl; } const char* alignment_file_p3 = p3_string.c_str(); graph = createGraph(alignment_file_p3, vertex_vector, ids, begin_vertex); } TVertexDescriptor new_begin_vertex; std::string tmp_string; std::string extension = ".fa"; // First exon { tmp_string = base_path.str(); std::string exon = "e"; std::string feature_number = std::to_string(number_of_exons); exon.append(feature_number); exon.append(extension); tmp_string.append(exon); if (CO.verbose) { std::cout << "Adding exon " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, edge_ids, new_begin_vertex, begin_vertex); --number_of_exons; } while (number_of_exons >= 1) { // Intron { tmp_string = base_path.str(); std::string intron = "i"; std::string feature_number = std::to_string(number_of_exons); intron.append(feature_number); intron.append(extension); tmp_string.append(intron); if (CO.verbose) { std::cout << "Adding intron " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } // Exon { tmp_string = base_path.str(); std::string exon = "e"; std::string feature_number = std::to_string(number_of_exons); exon.append(feature_number); exon.append(extension); tmp_string.append(exon); if (CO.verbose) { std::cout << "Adding exon " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, edge_ids, new_begin_vertex, begin_vertex); } --number_of_exons; } { // Final UTR tmp_string = base_path.str(); std::string utr = "5p"; utr.append(extension); tmp_string.append(utr); if (CO.verbose) { std::cout << "Adding utr " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } topologicalSort(order, graph); } void create_exon_2_and_3_graph(callOptions & CO, TGraph & graph, std::vector<VertexLabels> & vertex_vector, std::vector<std::string> & ids, boost::unordered_map< std::pair<TVertexDescriptor, TVertexDescriptor>, boost::dynamic_bitset<> > & edge_ids, boost::unordered_set<TVertexDescriptor> & free_nodes, String<TVertexDescriptor> & order ) { int number_of_exons = CO.number_of_exons; std::stringstream base_path; base_path << gyper_SOURCE_DIRECTORY << "/data/haplotypes/hla/references/" << CO.gene << "/"; TVertexDescriptor begin_vertex; { std::string p3_string = base_path.str(); p3_string.append("p3.fa"); if (CO.verbose) { std::cout << "Adding utr " << p3_string << std::endl; } const char* alignment_file_p3 = p3_string.c_str(); graph = createGraph(alignment_file_p3, vertex_vector, ids, begin_vertex); } TVertexDescriptor new_begin_vertex; std::string tmp_string; std::string extension = ".fa"; // First exon { tmp_string = base_path.str(); std::string exon = "e"; std::string feature_number = std::to_string(number_of_exons); exon.append(feature_number); exon.append(extension); tmp_string.append(exon); if (CO.verbose) { std::cout << "Adding exon " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); if (number_of_exons == 2 || number_of_exons == 3) { extendGraph(graph, alignment_file, vertex_vector, edge_ids, new_begin_vertex, begin_vertex); } else { extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } --number_of_exons; } while (number_of_exons >= 1) { // Intron { tmp_string = base_path.str(); std::string intron = "i"; std::string feature_number = std::to_string(number_of_exons); intron.append(feature_number); intron.append(extension); tmp_string.append(intron); if (CO.verbose) { std::cout << "Adding intron " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } // Exon { tmp_string = base_path.str(); std::string exon = "e"; std::string feature_number = std::to_string(number_of_exons); exon.append(feature_number); exon.append(extension); tmp_string.append(exon); if (CO.verbose) { std::cout << "Adding exon " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, edge_ids, new_begin_vertex, begin_vertex); } --number_of_exons; } { // Final UTR tmp_string = base_path.str(); std::string utr = "5p"; utr.append(extension); tmp_string.append(utr); if (CO.verbose) { std::cout << "Adding utr " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } topologicalSort(order, graph); } <commit_msg>some additional prints added in verbose mode<commit_after>#include "graph.hpp" void align_sequence (DnaString & my_sequence, boost::dynamic_bitset<> & qual, TGraph const & graph, std::vector<VertexLabels> & vertex_vector, String<TVertexDescriptor> & order, std::vector<ExactBacktracker> & backtracker, std::vector<ExactBacktracker> & reverse_backtracker, boost::unordered_set<TVertexDescriptor> const & free_nodes, std::vector<TVertexDescriptor> & matching_vertices, std::vector<TVertexDescriptor> & reverse_matching_vertices ) { initializeExactScoreMatrixAndBacktracker(length(my_sequence), length(order), backtracker); reverse_backtracker = backtracker; alignToGraphExact (my_sequence, order, graph, matching_vertices, vertex_vector, backtracker, free_nodes, qual ); reverseComplement(my_sequence); boost::dynamic_bitset<> qual_reversed(qual.size()); std::size_t qual_size = qual.size(); for (unsigned pos = 0 ; pos < qual_size ; ++pos) { if (qual.test(pos)) { qual_reversed[qual_size-pos-1] = 1; } } alignToGraphExact (my_sequence, order, graph, reverse_matching_vertices, vertex_vector, reverse_backtracker, free_nodes, qual ); reverseComplement(my_sequence); } boost::dynamic_bitset<> align_sequence_kmer (String<Dna> & my_sequence, String<char> & qual, unsigned const & id_numbers, TKmerMap & kmer_map, std::vector<VertexLabels> & vertex_vector, int const & kmer_size, int const & min_kmers ) { unsigned best_kmer_index = find_best_kmer(qual, kmer_size); boost::dynamic_bitset<> matched_ids = align_kmer_to_graph (my_sequence, id_numbers, kmer_map, vertex_vector, best_kmer_index, kmer_size, min_kmers ); if (matched_ids.find_first() != matched_ids.npos) { return matched_ids; } reverseComplement(my_sequence); matched_ids = align_kmer_to_graph (my_sequence, id_numbers, kmer_map, vertex_vector, best_kmer_index, kmer_size, min_kmers ); reverseComplement(my_sequence); return matched_ids; } CharString myExtractTagValue(String<char> &tags) { BamTagsDict tagsDict(tags); unsigned tagIdx = 0; if (!findTagKey(tagIdx, tagsDict, "RG")) { return ""; } CharString read_group; if (!extractTagValue(read_group, tagsDict, tagIdx)) { std::cerr << "Not a valid string at pos " << tagIdx << std::endl; return ""; } return read_group; } void createGenericGraph(callOptions & CO, TGraph & graph, std::vector<VertexLabels> & vertex_vector, std::vector<std::string> & ids, boost::unordered_map< std::pair<TVertexDescriptor, TVertexDescriptor>, boost::dynamic_bitset<> > & edge_ids, boost::unordered_set<TVertexDescriptor> & free_nodes, String<TVertexDescriptor> & order ) { int number_of_exons = CO.number_of_exons; std::stringstream base_path; base_path << gyper_SOURCE_DIRECTORY << "/data/haplotypes/hla/references/" << CO.gene << "/"; TVertexDescriptor begin_vertex; { std::string p3_string = base_path.str(); p3_string.append("p3.fa"); if (CO.verbose) { std::cout << "Adding utr " << p3_string << std::endl; } const char* alignment_file_p3 = p3_string.c_str(); graph = createGraph(alignment_file_p3, vertex_vector, ids, begin_vertex); } TVertexDescriptor new_begin_vertex; std::string tmp_string; std::string extension = ".fa"; // First exon { tmp_string = base_path.str(); std::string exon = "e"; std::string feature_number = std::to_string(number_of_exons); exon.append(feature_number); exon.append(extension); tmp_string.append(exon); if (CO.verbose) { std::cout << "Adding exon " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, edge_ids, new_begin_vertex, begin_vertex); --number_of_exons; } while (number_of_exons >= 1) { // Intron { tmp_string = base_path.str(); std::string intron = "i"; std::string feature_number = std::to_string(number_of_exons); intron.append(feature_number); intron.append(extension); tmp_string.append(intron); if (CO.verbose) { std::cout << "Adding intron " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } // Exon { tmp_string = base_path.str(); std::string exon = "e"; std::string feature_number = std::to_string(number_of_exons); exon.append(feature_number); exon.append(extension); tmp_string.append(exon); if (CO.verbose) { std::cout << "Adding exon " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, edge_ids, new_begin_vertex, begin_vertex); } --number_of_exons; } { // Final UTR tmp_string = base_path.str(); std::string utr = "5p"; utr.append(extension); tmp_string.append(utr); if (CO.verbose) { std::cout << "Adding utr " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } topologicalSort(order, graph); } void create_exon_2_and_3_graph(callOptions & CO, TGraph & graph, std::vector<VertexLabels> & vertex_vector, std::vector<std::string> & ids, boost::unordered_map< std::pair<TVertexDescriptor, TVertexDescriptor>, boost::dynamic_bitset<> > & edge_ids, boost::unordered_set<TVertexDescriptor> & free_nodes, String<TVertexDescriptor> & order ) { int number_of_exons = CO.number_of_exons; std::stringstream base_path; base_path << gyper_SOURCE_DIRECTORY << "/data/haplotypes/hla/references/" << CO.gene << "/"; TVertexDescriptor begin_vertex; { std::string p3_string = base_path.str(); p3_string.append("p3.fa"); if (CO.verbose) { std::cout << "Adding utr " << p3_string << std::endl; } const char* alignment_file_p3 = p3_string.c_str(); graph = createGraph(alignment_file_p3, vertex_vector, ids, begin_vertex); } TVertexDescriptor new_begin_vertex; std::string tmp_string; std::string extension = ".fa"; // First exon { tmp_string = base_path.str(); std::string exon = "e"; std::string feature_number = std::to_string(number_of_exons); exon.append(feature_number); exon.append(extension); tmp_string.append(exon); // if (CO.verbose) // { // std::cout << "Adding exon " << tmp_string << std::endl; // } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); if (number_of_exons == 2 || number_of_exons == 3) { if (CO.verbose) { std::cout << "Adding exon " << tmp_string << std::endl; } extendGraph(graph, alignment_file, vertex_vector, edge_ids, new_begin_vertex, begin_vertex); } else { if (CO.verbose) { std::cout << "Adding exon " << tmp_string << " as intron" << std::endl; } extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } --number_of_exons; } while (number_of_exons >= 1) { // Intron { tmp_string = base_path.str(); std::string intron = "i"; std::string feature_number = std::to_string(number_of_exons); intron.append(feature_number); intron.append(extension); tmp_string.append(intron); if (CO.verbose) { std::cout << "Adding intron " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } // Exon { tmp_string = base_path.str(); std::string exon = "e"; std::string feature_number = std::to_string(number_of_exons); exon.append(feature_number); exon.append(extension); tmp_string.append(exon); // if (CO.verbose) // { // std::cout << "Adding exon " << tmp_string << std::endl; // } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); if (number_of_exons == 2 || number_of_exons == 3) { if (CO.verbose) { std::cout << "Adding exon " << tmp_string << std::endl; } extendGraph(graph, alignment_file, vertex_vector, edge_ids, new_begin_vertex, begin_vertex); } else { if (CO.verbose) { std::cout << "Adding exon " << tmp_string << " as intron" << std::endl; } extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } } --number_of_exons; } { // Final UTR tmp_string = base_path.str(); std::string utr = "5p"; utr.append(extension); tmp_string.append(utr); if (CO.verbose) { std::cout << "Adding utr " << tmp_string << std::endl; } const char* alignment_file = tmp_string.c_str(); free_nodes.insert(begin_vertex); extendGraph(graph, alignment_file, vertex_vector, new_begin_vertex, begin_vertex); } topologicalSort(order, graph); } <|endoftext|>
<commit_before>// if s1 starts with s2 returns true, else false // len is the length of s1 // s2 should be null-terminated static bool starts_with(const char *s1, int len, const char *s2) { int n = 0; while (*s2 && n < len) { if (*s1++ != *s2++) return false; n++; } return *s2 == 0; } // convert escape sequence to event, and return consumed bytes on success (failure == 0) static int parse_escape_seq(struct tb_event *event, const char *buf, int len) { if (len >= 6 && starts_with(buf, len, "\033[M")) { switch (buf[3] & 3) { case 0: if (buf[3] == 0x60) event->key = TB_KEY_MOUSE_WHEEL_UP; else event->key = TB_KEY_MOUSE_LEFT; break; case 1: if (buf[3] == 0x61) event->key = TB_KEY_MOUSE_WHEEL_DOWN; else event->key = TB_KEY_MOUSE_MIDDLE; break; case 2: event->key = TB_KEY_MOUSE_RIGHT; break; case 3: event->key = TB_KEY_MOUSE_RELEASE; break; default: return -6; } event->type = TB_EVENT_MOUSE; // TB_EVENT_KEY by default // the coord is 1,1 for upper left event->x = buf[4] - 1 - 32; event->y = buf[5] - 1 - 32; return 6; } // it's pretty simple here, find 'starts_with' match and return // success, else return failure int i; for (i = 0; keys[i]; i++) { if (starts_with(buf, len, keys[i])) { event->ch = 0; event->key = 0xFFFF-i; return strlen(keys[i]); } } return 0; } static bool extract_event(struct tb_event *event, struct bytebuffer *inbuf, int inputmode) { const char *buf = inbuf->buf; const int len = inbuf->len; if (len == 0) return false; if (buf[0] == '\033') { int n = parse_escape_seq(event, buf, len); if (n != 0) { bool success = true; if (n < 0) { success = false; n = -n; } bytebuffer_truncate(inbuf, n); return success; } else { // it's not escape sequence, then it's ALT or ESC, // check inputmode if (inputmode&TB_INPUT_ESC) { // if we're in escape mode, fill ESC event, pop // buffer, return success event->ch = 0; event->key = TB_KEY_ESC; event->mod = 0; bytebuffer_truncate(inbuf, 1); return true; } else if (inputmode&TB_INPUT_ALT) { // if we're in alt mode, set ALT modifier to // event and redo parsing event->mod = TB_MOD_ALT; bytebuffer_truncate(inbuf, 1); return extract_event(event, inbuf, inputmode); } assert(!"never got here"); } } // if we're here, this is not an escape sequence and not an alt sequence // so, it's a FUNCTIONAL KEY or a UNICODE character // first of all check if it's a functional key if ((unsigned char)buf[0] <= TB_KEY_SPACE || (unsigned char)buf[0] == TB_KEY_BACKSPACE2) { // fill event, pop buffer, return success */ event->ch = 0; event->key = (uint16_t)buf[0]; bytebuffer_truncate(inbuf, 1); return true; } // feh... we got utf8 here // check if there is all bytes if (len >= tb_utf8_char_length(buf[0])) { /* everything ok, fill event, pop buffer, return success */ tb_utf8_char_to_unicode(&event->ch, buf); event->key = 0; bytebuffer_truncate(inbuf, tb_utf8_char_length(buf[0])); return true; } // event isn't recognized, perhaps there is not enough bytes in utf8 // sequence return false; } <commit_msg>Use uint8_t as mouse coordinate type in input parsing.<commit_after>// if s1 starts with s2 returns true, else false // len is the length of s1 // s2 should be null-terminated static bool starts_with(const char *s1, int len, const char *s2) { int n = 0; while (*s2 && n < len) { if (*s1++ != *s2++) return false; n++; } return *s2 == 0; } // convert escape sequence to event, and return consumed bytes on success (failure == 0) static int parse_escape_seq(struct tb_event *event, const char *buf, int len) { if (len >= 6 && starts_with(buf, len, "\033[M")) { switch (buf[3] & 3) { case 0: if (buf[3] == 0x60) event->key = TB_KEY_MOUSE_WHEEL_UP; else event->key = TB_KEY_MOUSE_LEFT; break; case 1: if (buf[3] == 0x61) event->key = TB_KEY_MOUSE_WHEEL_DOWN; else event->key = TB_KEY_MOUSE_MIDDLE; break; case 2: event->key = TB_KEY_MOUSE_RIGHT; break; case 3: event->key = TB_KEY_MOUSE_RELEASE; break; default: return -6; } event->type = TB_EVENT_MOUSE; // TB_EVENT_KEY by default // the coord is 1,1 for upper left event->x = (uint8_t)buf[4] - 1 - 32; event->y = (uint8_t)buf[5] - 1 - 32; return 6; } // it's pretty simple here, find 'starts_with' match and return // success, else return failure int i; for (i = 0; keys[i]; i++) { if (starts_with(buf, len, keys[i])) { event->ch = 0; event->key = 0xFFFF-i; return strlen(keys[i]); } } return 0; } static bool extract_event(struct tb_event *event, struct bytebuffer *inbuf, int inputmode) { const char *buf = inbuf->buf; const int len = inbuf->len; if (len == 0) return false; if (buf[0] == '\033') { int n = parse_escape_seq(event, buf, len); if (n != 0) { bool success = true; if (n < 0) { success = false; n = -n; } bytebuffer_truncate(inbuf, n); return success; } else { // it's not escape sequence, then it's ALT or ESC, // check inputmode if (inputmode&TB_INPUT_ESC) { // if we're in escape mode, fill ESC event, pop // buffer, return success event->ch = 0; event->key = TB_KEY_ESC; event->mod = 0; bytebuffer_truncate(inbuf, 1); return true; } else if (inputmode&TB_INPUT_ALT) { // if we're in alt mode, set ALT modifier to // event and redo parsing event->mod = TB_MOD_ALT; bytebuffer_truncate(inbuf, 1); return extract_event(event, inbuf, inputmode); } assert(!"never got here"); } } // if we're here, this is not an escape sequence and not an alt sequence // so, it's a FUNCTIONAL KEY or a UNICODE character // first of all check if it's a functional key if ((unsigned char)buf[0] <= TB_KEY_SPACE || (unsigned char)buf[0] == TB_KEY_BACKSPACE2) { // fill event, pop buffer, return success */ event->ch = 0; event->key = (uint16_t)buf[0]; bytebuffer_truncate(inbuf, 1); return true; } // feh... we got utf8 here // check if there is all bytes if (len >= tb_utf8_char_length(buf[0])) { /* everything ok, fill event, pop buffer, return success */ tb_utf8_char_to_unicode(&event->ch, buf); event->key = 0; bytebuffer_truncate(inbuf, tb_utf8_char_length(buf[0])); return true; } // event isn't recognized, perhaps there is not enough bytes in utf8 // sequence return false; } <|endoftext|>
<commit_before>/** * Copyright (C) 2012 by INdT * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This 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 Lesser 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. * * @author Rodrigo Goncalves de Oliveira <[email protected]> * @author Roger Felipe Zanoni da Silva <[email protected]> */ #include <QDebug> #include <QPainter> #include <QQmlProperty> #include "layer.h" //! Class constructor Layer::Layer(QuasiDeclarativeItem *parent) : QuasiPaintedItem(parent) , m_drawType(Quasi::TiledDrawType) , m_factor(1.0) , m_type(Quasi::InfiniteType) , m_direction((Quasi::LayerDirection)-1) // Backward , m_areaToDraw(2.0) , m_columnOffset(0) , m_drawingMirrored(false) , m_shouldMirror(false) , m_tileWidth(32) , m_tileHeight(32) , m_latestPoint(0) { #if QT_VERSION >= 0x050000 setZ(Quasi::InteractionLayerOrdering_01); #else setZValue(Quasi::InteractionLayerOrdering_01); #endif // this activates the item layered mode QQmlProperty(this, "layer.enabled").write(true); } //! Class destructor Layer::~Layer() { m_pixmaps.clear(); m_mirroredTiles.clear(); } //! Stores the source path for the image /*! * \param source the image path */ void Layer::setSource(const QString &source) { if (m_source != source) m_source = source; } //! Gets the image source path /*! * \return the source path for the image */ QString Layer::source() const { return m_source; } //! Stores the layer type /*! * \param drawType can be Tiled (default) or Plane */ void Layer::setDrawType(Quasi::DrawType drawType) { if (m_drawType != drawType) m_drawType = drawType; } //! Gets the layer type /*! * \return Tiled or Plane according the layer draw type */ Quasi::DrawType Layer::drawType() const { return m_drawType; } void Layer::setDirection(const Quasi::LayerDirection &direction) { if (direction != m_direction){ if (direction == Quasi::BackwardDirection) m_direction = (Quasi::LayerDirection)-1; // insane black magic else m_direction = direction; emit directionChanged(); } } //! Stores the layer update factor /*! * \param factor the factor value */ void Layer::setFactor(qreal factor) { if (m_factor != factor) m_factor = factor; } //! Gets the layer update factor /*! * \return layer update factor */ qreal Layer::factor() const { return m_factor; } //! Stores the layer z order /*! * \param order the layer z order */ void Layer::setOrder(Quasi::Ordering order) { #if QT_VERSION >= 0x050000 if (z() != order) setZ(order); #else if (zValue() != order) setZValue(order); #endif } //! Gets the layer z order /*! * \return layer z order */ Quasi::Ordering Layer::order() const { #if QT_VERSION >= 0x050000 return (Quasi::Ordering)z(); #else return (Quasi::Ordering)zValue(); #endif } void Layer::setLayerType(const Quasi::LayerType &type) { if (type != m_type){ m_type = type; emit layerTypeChanged(); } } void Layer::setTileHeight(const int &value) { if (m_drawType == Quasi::PlaneDrawType) return; if (value != m_tileHeight){ m_tileHeight = value; if (m_tileWidth != 0 && m_tileHeight != 0) emit tilesChanged(); } } void Layer::setTileWidth(const int &value) { if (m_drawType == Quasi::PlaneDrawType) return; if (value != m_tileWidth){ m_tileWidth = value; if (m_tileWidth != 0 && m_tileHeight != 0) emit tilesChanged(); } } //! Adds a tile on the list /*! * \param pix the pixmap to append on the list * \return the list actual size or -1 if the layer can not accept tiled pixmaps */ int Layer::addTile(const QPixmap &pix) { m_pixmaps.append(pix); return m_pixmaps.size(); } //! Gets a tile from the list /*! * \param pos the tile position on the list * \return the tile pixmap of position pos on the list or null, if none */ QPixmap Layer::getTile(int pos) const { return m_pixmaps.at(pos); } void Layer::setDrawGrid(bool draw) { if (draw != m_drawGrid) m_drawGrid = draw; } void Layer::setGridColor(const QColor &color) { if (color != m_gridColor) m_gridColor = color; } //! Gets the tiles pixmap list size /*! * \return the tiles pixmap list size */ int Layer::count() const { return m_pixmaps.size(); } void Layer::generateOffsets() { bool completed = false; int start = 0; int step = m_numColumns; int max = m_totalColumns; int count = 0; int maxCount = step * (int)m_areaToDraw; bool first = true; Offsets::OffsetsList firstPoint; while (!completed) { Offsets::OffsetsList offsetsList; int tamanho; int fim = 0; bool finish = false; while (count < maxCount) { fim = (start + step) % max; if (fim - start > 0) { tamanho = step; count += tamanho; // TODO check this comparison. Is it really needed? if (finish || count != maxCount) { offsetsList.append(Offsets(start, tamanho)); if (!finish) start = fim; finish = false; } else { offsetsList.append(Offsets(start, tamanho)); } } else { int oldStart = start; tamanho = max - start; count += tamanho; offsetsList.append(Offsets(start, tamanho)); tamanho = step - tamanho; start = 0; count += tamanho; if (tamanho != 0) { offsetsList.append(Offsets(0, tamanho)); } if (count <= maxCount / 2) { start = tamanho; finish = true; } else start = oldStart; } } count = 0; if (offsetsList == firstPoint) completed = true; else m_offsets.append(offsetsList); if (first) { firstPoint = offsetsList; first = false; } } } void Layer::updateTiles() { if ((boundingRect().width() == 0) || (boundingRect().height() == 0)) return; // TODO create enums to define image aspect, auto tile, etc... QPixmap pix(source()); // TODO if (m_drawType == Quasi::PlaneDrawType) { m_tileWidth = width(); m_tileHeight = height(); if (pix.width() % (int)width() != 0) { // XXX create some log system? qCritical() << QString("Quasi>>Image \'%1\' doesn't contains a proper size... CROPPING!").arg(source()); int newWidth = pix.width() - (pix.width() % (int)width()); pix = pix.copy(0, 0, newWidth, height()); } } if (pix.width() < boundingRect().width()) { QPixmap temp(boundingRect().width(), boundingRect().height()); QPainter p(&temp); p.drawTiledPixmap(boundingRect(), pix, QPoint(0,0)); p.end(); pix = temp; } QPixmap mirrored; if (m_type == Quasi::MirroredType){ QImage image = pix.toImage(); mirrored = QPixmap::fromImage(image.mirrored(true, false)); } // visible tiles m_numColumns = boundingRect().width() / m_tileWidth; m_numRows = boundingRect().height() / m_tileHeight; // total of columns and rows m_totalColumns = pix.width() / m_tileWidth; m_totalRows = pix.height() / m_tileHeight; int i, j; for (i = 0; i < m_totalRows; i++) { for (j = 0; j < m_totalColumns; j++){ QPixmap temp(m_tileWidth, m_tileHeight); QPainter p(&temp); p.setCompositionMode(QPainter::CompositionMode_Source); p.drawPixmap(0, 0, m_tileWidth, m_tileHeight, pix, j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight); p.end(); addTile(temp); if (m_type == Quasi::MirroredType) { QPainter p(&temp); p.drawPixmap(0, 0, m_tileWidth, m_tileHeight, mirrored, j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight); p.end(); m_mirroredTiles.append(temp); } } } generateOffsets(); drawPixmap(); } QPixmap Layer::generatePartialPixmap(int startPoint, int size) { QPixmap temp(m_tileWidth * size, boundingRect().height()); QPainter p(&temp); int i, j; int index = 0; for (i = 0; i < m_numRows; i++) { for (j = 0; j < size; j++) { index = ((i * m_totalColumns) + (j + startPoint)); // TODO improve comparison if (m_direction == Quasi::ForwardDirection) { if (m_drawingMirrored) p.drawPixmap(j * m_tileWidth, i * m_tileHeight, getTile(index)); else p.drawPixmap(j * m_tileWidth, i * m_tileHeight, m_mirroredTiles.at(index)); } else { if (m_drawingMirrored) p.drawPixmap(j * m_tileWidth, i * m_tileHeight, m_mirroredTiles.at(index)); else p.drawPixmap(j * m_tileWidth, i * m_tileHeight, getTile(index)); } // just draw a grid // XXX chech the possibility of drawn it only on a debug mode if (m_drawGrid) { p.setPen(m_gridColor); p.drawRect(j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight); } } } p.end(); return temp; } void Layer::drawPixmap() { if ((boundingRect().width() == 0) || (boundingRect().height() == 0)) return; // TODO Forward if (m_currentImage) delete m_currentImage; m_currentImage = new QImage(boundingRect().width() * m_areaToDraw, boundingRect().height(), QImage::Format_ARGB32_Premultiplied); QPainter p(m_currentImage); int xPoint = 0; for (int i = 0; i < m_offsets[m_columnOffset].size(); i++) { Offsets offset = m_offsets[m_columnOffset].at(i); if (((m_type == Quasi::MirroredType) && (i != 0) && (offset.point() - m_latestPoint < 0)) || m_shouldMirror) { m_drawingMirrored = !m_drawingMirrored; m_shouldMirror = false; } QPixmap pix = generatePartialPixmap(offset.point(), offset.size()); p.drawPixmap(xPoint, 0, pix); xPoint += pix.width(); m_latestPoint = offset.point(); if ((m_type == Quasi::MirroredType) && (i == m_offsets[m_columnOffset].size() - 1) && (offset.size() < m_numColumns)) m_shouldMirror = true; } if (m_direction == Quasi::ForwardDirection) m_columnOffset = (m_columnOffset - 1 < 0) ? m_offsets.size() - 1 : m_columnOffset - 1; else m_columnOffset = (m_columnOffset + 1) % m_offsets.size(); p.end(); } <commit_msg>Fixed initialization order in Layer class<commit_after>/** * Copyright (C) 2012 by INdT * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This 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 Lesser 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. * * @author Rodrigo Goncalves de Oliveira <[email protected]> * @author Roger Felipe Zanoni da Silva <[email protected]> */ #include <QDebug> #include <QPainter> #include <QQmlProperty> #include "layer.h" //! Class constructor Layer::Layer(QQuickItem *parent) : QuasiPaintedItem(parent) , m_direction((Quasi::LayerDirection)-1) // Backward , m_tileWidth(32) , m_tileHeight(32) , m_factor(1.0) , m_drawType(Quasi::TiledDrawType) , m_type(Quasi::InfiniteType) , m_areaToDraw(2.0) , m_columnOffset(0) , m_drawingMirrored(false) , m_shouldMirror(false) , m_latestPoint(0) { #if QT_VERSION >= 0x050000 setZ(Quasi::InteractionLayerOrdering_01); #else setZValue(Quasi::InteractionLayerOrdering_01); #endif // this activates the item layered mode QQmlProperty(this, "layer.enabled").write(true); } //! Class destructor Layer::~Layer() { m_pixmaps.clear(); m_mirroredTiles.clear(); } //! Stores the source path for the image /*! * \param source the image path */ void Layer::setSource(const QString &source) { if (m_source != source) m_source = source; } //! Gets the image source path /*! * \return the source path for the image */ QString Layer::source() const { return m_source; } //! Stores the layer type /*! * \param drawType can be Tiled (default) or Plane */ void Layer::setDrawType(Quasi::DrawType drawType) { if (m_drawType != drawType) m_drawType = drawType; } //! Gets the layer type /*! * \return Tiled or Plane according the layer draw type */ Quasi::DrawType Layer::drawType() const { return m_drawType; } void Layer::setDirection(const Quasi::LayerDirection &direction) { if (direction != m_direction){ if (direction == Quasi::BackwardDirection) m_direction = (Quasi::LayerDirection)-1; // insane black magic else m_direction = direction; emit directionChanged(); } } //! Stores the layer update factor /*! * \param factor the factor value */ void Layer::setFactor(qreal factor) { if (m_factor != factor) m_factor = factor; } //! Gets the layer update factor /*! * \return layer update factor */ qreal Layer::factor() const { return m_factor; } //! Stores the layer z order /*! * \param order the layer z order */ void Layer::setOrder(Quasi::Ordering order) { #if QT_VERSION >= 0x050000 if (z() != order) setZ(order); #else if (zValue() != order) setZValue(order); #endif } //! Gets the layer z order /*! * \return layer z order */ Quasi::Ordering Layer::order() const { #if QT_VERSION >= 0x050000 return (Quasi::Ordering)z(); #else return (Quasi::Ordering)zValue(); #endif } void Layer::setLayerType(const Quasi::LayerType &type) { if (type != m_type){ m_type = type; emit layerTypeChanged(); } } void Layer::setTileHeight(const int &value) { if (m_drawType == Quasi::PlaneDrawType) return; if (value != m_tileHeight){ m_tileHeight = value; if (m_tileWidth != 0 && m_tileHeight != 0) emit tilesChanged(); } } void Layer::setTileWidth(const int &value) { if (m_drawType == Quasi::PlaneDrawType) return; if (value != m_tileWidth){ m_tileWidth = value; if (m_tileWidth != 0 && m_tileHeight != 0) emit tilesChanged(); } } //! Adds a tile on the list /*! * \param pix the pixmap to append on the list * \return the list actual size or -1 if the layer can not accept tiled pixmaps */ int Layer::addTile(const QPixmap &pix) { m_pixmaps.append(pix); return m_pixmaps.size(); } //! Gets a tile from the list /*! * \param pos the tile position on the list * \return the tile pixmap of position pos on the list or null, if none */ QPixmap Layer::getTile(int pos) const { return m_pixmaps.at(pos); } void Layer::setDrawGrid(bool draw) { if (draw != m_drawGrid) m_drawGrid = draw; } void Layer::setGridColor(const QColor &color) { if (color != m_gridColor) m_gridColor = color; } //! Gets the tiles pixmap list size /*! * \return the tiles pixmap list size */ int Layer::count() const { return m_pixmaps.size(); } void Layer::generateOffsets() { bool completed = false; int start = 0; int step = m_numColumns; int max = m_totalColumns; int count = 0; int maxCount = step * (int)m_areaToDraw; bool first = true; Offsets::OffsetsList firstPoint; while (!completed) { Offsets::OffsetsList offsetsList; int tamanho; int fim = 0; bool finish = false; while (count < maxCount) { fim = (start + step) % max; if (fim - start > 0) { tamanho = step; count += tamanho; // TODO check this comparison. Is it really needed? if (finish || count != maxCount) { offsetsList.append(Offsets(start, tamanho)); if (!finish) start = fim; finish = false; } else { offsetsList.append(Offsets(start, tamanho)); } } else { int oldStart = start; tamanho = max - start; count += tamanho; offsetsList.append(Offsets(start, tamanho)); tamanho = step - tamanho; start = 0; count += tamanho; if (tamanho != 0) { offsetsList.append(Offsets(0, tamanho)); } if (count <= maxCount / 2) { start = tamanho; finish = true; } else start = oldStart; } } count = 0; if (offsetsList == firstPoint) completed = true; else m_offsets.append(offsetsList); if (first) { firstPoint = offsetsList; first = false; } } } void Layer::updateTiles() { if ((boundingRect().width() == 0) || (boundingRect().height() == 0)) return; // TODO create enums to define image aspect, auto tile, etc... QPixmap pix(source()); // TODO if (m_drawType == Quasi::PlaneDrawType) { m_tileWidth = width(); m_tileHeight = height(); if (pix.width() % (int)width() != 0) { // XXX create some log system? qCritical() << QString("Quasi>>Image \'%1\' doesn't contains a proper size... CROPPING!").arg(source()); int newWidth = pix.width() - (pix.width() % (int)width()); pix = pix.copy(0, 0, newWidth, height()); } } if (pix.width() < boundingRect().width()) { QPixmap temp(boundingRect().width(), boundingRect().height()); QPainter p(&temp); p.drawTiledPixmap(boundingRect(), pix, QPoint(0,0)); p.end(); pix = temp; } QPixmap mirrored; if (m_type == Quasi::MirroredType){ QImage image = pix.toImage(); mirrored = QPixmap::fromImage(image.mirrored(true, false)); } // visible tiles m_numColumns = boundingRect().width() / m_tileWidth; m_numRows = boundingRect().height() / m_tileHeight; // total of columns and rows m_totalColumns = pix.width() / m_tileWidth; m_totalRows = pix.height() / m_tileHeight; int i, j; for (i = 0; i < m_totalRows; i++) { for (j = 0; j < m_totalColumns; j++){ QPixmap temp(m_tileWidth, m_tileHeight); QPainter p(&temp); p.setCompositionMode(QPainter::CompositionMode_Source); p.drawPixmap(0, 0, m_tileWidth, m_tileHeight, pix, j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight); p.end(); addTile(temp); if (m_type == Quasi::MirroredType) { QPainter p(&temp); p.drawPixmap(0, 0, m_tileWidth, m_tileHeight, mirrored, j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight); p.end(); m_mirroredTiles.append(temp); } } } generateOffsets(); drawPixmap(); } QPixmap Layer::generatePartialPixmap(int startPoint, int size) { QPixmap temp(m_tileWidth * size, boundingRect().height()); QPainter p(&temp); int i, j; int index = 0; for (i = 0; i < m_numRows; i++) { for (j = 0; j < size; j++) { index = ((i * m_totalColumns) + (j + startPoint)); // TODO improve comparison if (m_direction == Quasi::ForwardDirection) { if (m_drawingMirrored) p.drawPixmap(j * m_tileWidth, i * m_tileHeight, getTile(index)); else p.drawPixmap(j * m_tileWidth, i * m_tileHeight, m_mirroredTiles.at(index)); } else { if (m_drawingMirrored) p.drawPixmap(j * m_tileWidth, i * m_tileHeight, m_mirroredTiles.at(index)); else p.drawPixmap(j * m_tileWidth, i * m_tileHeight, getTile(index)); } // just draw a grid // XXX chech the possibility of drawn it only on a debug mode if (m_drawGrid) { p.setPen(m_gridColor); p.drawRect(j * m_tileWidth, i * m_tileHeight, m_tileWidth, m_tileHeight); } } } p.end(); return temp; } void Layer::drawPixmap() { if ((boundingRect().width() == 0) || (boundingRect().height() == 0)) return; // TODO Forward if (m_currentImage) delete m_currentImage; m_currentImage = new QImage(boundingRect().width() * m_areaToDraw, boundingRect().height(), QImage::Format_ARGB32_Premultiplied); QPainter p(m_currentImage); int xPoint = 0; for (int i = 0; i < m_offsets[m_columnOffset].size(); i++) { Offsets offset = m_offsets[m_columnOffset].at(i); if (((m_type == Quasi::MirroredType) && (i != 0) && (offset.point() - m_latestPoint < 0)) || m_shouldMirror) { m_drawingMirrored = !m_drawingMirrored; m_shouldMirror = false; } QPixmap pix = generatePartialPixmap(offset.point(), offset.size()); p.drawPixmap(xPoint, 0, pix); xPoint += pix.width(); m_latestPoint = offset.point(); if ((m_type == Quasi::MirroredType) && (i == m_offsets[m_columnOffset].size() - 1) && (offset.size() < m_numColumns)) m_shouldMirror = true; } if (m_direction == Quasi::ForwardDirection) m_columnOffset = (m_columnOffset - 1 < 0) ? m_offsets.size() - 1 : m_columnOffset - 1; else m_columnOffset = (m_columnOffset + 1) % m_offsets.size(); p.end(); } <|endoftext|>
<commit_before>#ifdef COMPONENT_LEXER_H // do not include this file directly. // use lexer.h instead. /********************************* * Implementation: Class Token ** *********************************/ // constructors Token::Token(String val, tokenType t, tokenType st, bufferIndex ln, bufferIndex in) { this->_value = val; this->_type = t; this->_subtype = st; this->_line = ln; this->_indent = in; } Token::Token(const Token& t) { this->_value = t._value; this->_type = t._type; this->_subtype = t._subtype; this->_line = t._line; this->_indent = t._indent; } Token Token::operator= (const Token& t) { this->_value = t._value; this->_type = t._type; this->_subtype = t._subtype; this->_line = t._line; this->_indent = t._indent; return *this; } // properties tokenType Token::type() const { return this->_type; } tokenType Token::subtype() const { return this->_subtype; } bufferIndex Token::lineNumber() const { return this->_line; } bufferIndex Token::indent() const { return this->_indent; } String Token::value() const { return this->_value; } // mutators bool Token::setType(tokenType t) { this->_type = t; } bool Token::setSubtype(tokenType st) { this->_subtype = st; } bool Token::setLineNumber(bufferIndex ln) { this->_line = ln; } bool Token::setIndent(bufferIndex in) { this->_indent = in; } bool Token::setValue(String s) { this->_value = s; } // end implementation: class Token /**************************************** * Implementation: Class Lexer ** ****************************************/ // constructors, and dynamic data managers. Lexer::Lexer (String data) { this->source.open(data.c_str()); this->line = 1; this->indent = 0; } Lexer::~Lexer() { if (this->source) this->source.close(); errors.clear(); innerBuffer.clear(); } /*** static members ***/ bool Lexer::isValidIdentifier(String val) { if (val.length() > MAX_ID_LENGTH) return false; if (!isalpha(val[0]) && val[0] != '_') return false; for (__SIZETYPE i = 0; i < val.length(); i++) if (!isalnum(val[i]) && val[i] != '_') return false; return true; } // maps a keyword to a corresponding operator. // possible only if the keyword can be replaced by the operator in the code, // without altering the flow of logic. String Lexer::entityMap(String val) { if (val == "and") return "&&"; if (val == "or") return "||"; if (val == "not") return "!"; if (val == "equals") return "=="; return val; } // Converts a string into a token, // assumes string to be somewhat valid. Token Lexer::toToken(String val) { if (!val) return nullToken; if (val[0] == -1) return nullToken; val = entityMap(val); // string literal: if (val[0] == '\"' || val[0] == '\'') { return Token(val, LITERAL, STRING); } // numeric literal if (val[0] >= '0' && val[0] <= '9') { return Token(val, LITERAL, NUMBER); } // punctuator if (Punctuators.indexOf(val) >= 0) { return Token(val, PUNCTUATOR); } // keywords if (Keywords.indexOf(val) >= 0) { if (Constants.indexOf(val) >= 0) { if (val == "true" || val == "false") return Token(val, LITERAL, BOOLEAN); return Token(val, KEYWORD, CONSTANT); } return Token(val, KEYWORD); } // inbuilt functions if (InbuiltFunctions.indexOf(val) >= 0) return Token(val, IDENTIFIER, FUNCTION); // operators. assumes that the operator has been extracted properly. if (binaryOperators.indexOf(val) >= 0) { return Token(val, OPERATOR, BINARYOP); } if (unaryOperators.indexOf(val) >= 0) { return Token(val, OPERATOR, UNARYOP); } // identifier if (isValidIdentifier(val)) { return Token(val, IDENTIFIER); } return Token(val); } /*** Member functions: actual lexing procedures. ***/ // removes all leading spaces, and discard comments. int Lexer::trim() { if (this->source.eof()) return -1; int sp = 0; while (this->source.peek() == ' ') { this->source.get(); sp++; } if (this->source.peek() == '#') { while (this->source.get() != '\n' && !this->source.eof()) // ignore the rest of the line. this->endLine(); return this->trim(); } if (this->source.eof()) return -1; return sp; } // Increases the line number, and sets up the next line // extracts the tabs from next line, sets the indent, and returns the number. // assumes that the \n is already read from the buffer. int Lexer::endLine() { this->innerBuffer.pushback(newlineToken); if (this->source.eof()) return -1; this->line++; // extract the indentation. int num = 0; while (this->source.peek() == '\t') { this->source.get(); num++; } this->indent = num; return (num); } // extracts a string: as '...' or "..." String Lexer::readString() { char st = this->source.get(), tmp = 0; String ret = st; while (tmp != st) { tmp = this->source.get(); if (tmp == '\n') { // error. string not terminated properly. this->errors.pushback(Error("l1", "", this->line)); this->endLine(); // return a null string. return ""; } ret += tmp; if (tmp == '\\') { // escape: get the next character. tmp = this->source.get(); if (tmp != '\n') ret += tmp; else this->endLine(); } } return ret; } // reads a numeric value: can contain utmost one decimal point. String Lexer::readNumber() { String num; bool isDeci = false; char ch = this->source.get(); while ((ch >= '0' && ch <= '9') || ch == '.') { if (ch == '.') { if (!isDeci) { isDeci = true; } else { // error- too many decimal points this->errors.pushback(Error("l2", "", this->line)); return ""; } } num += ch; ch = this->source.get(); } if (ch == '\n') { this->endLine(); } else { if (!this->source.eof()) this->source.putback(ch); } return num; } // reads an identifier/keyword, // assuming the starting character in the buffer is a alpha or underscore. // does `not` check whether it is valid. String Lexer::readIdentifier() { String ret; int len = 0; char ch = this->source.get(); while (isalnum(ch) || ch == '_') { ret += ch; len++; ch = this->source.get(); } if (!this->source.eof()) this->source.putback(ch); return ret; } // reads an operator, without touching any adjacent characters. // this does not do a full check for all operators. // note: some operators are 'decided' by the parser, because they depend on situation. String Lexer::readOperator() { char ch = this->source.peek(); if (Opstarts.indexOf(ch) == -1) return ""; this->source.get(); String ret = ch; // check whether can be followed by = static const idList eq(strsplit("+-*/%=!<>")); if (eq.indexOf(ch) >= 0 && this->source.peek() == '=') { ret += (this->source.get()); // a second = if ((ch == '=' || ch == '!') && (this->source.peek() == '=')) { ret += this->source.get(); } } else if (ch == '+' || ch == '-' || ch == '&' || ch == '|') { // operators ++ -- && || if (this->source.peek() == ch) ret += (this->source.get()); } return ret; } Token Lexer::getToken() { // check for a previously buffered token. if (!this->innerBuffer.empty()) { Token tmp; this->innerBuffer.popfront(tmp); return tmp; } this->trim(); char ch = this->source.peek(); if (this->source.eof()) return eofToken; String val; bufferIndex tline = this->line, tindent = this->indent; if (ch == '\n') { this->source.get(); this->endLine(); return this->getToken(); } if (ch == '\'' || ch == '\"') { val = this->readString(); // string literal } else if (isalpha(ch) || ch == '_') { val = this->readIdentifier(); // identifier/keyword } else if (isdigit(ch)) { val = this->readNumber(); // numeric constant } else if (Punctuators.indexOf(ch) >= 0) { val = ch; // punctuator. keep it as it is."; this->source.get(); } else if (Opstarts.indexOf(ch) >= 0) { val = this->readOperator(); } else { // just ignore the character, as of now. This should flag an unknown character error. val = ch; this->source.get(); } Token tok = toToken(val); tok.setLineNumber(tline); tok.setIndent(tindent); this->innerBuffer.pushback(tok); this->innerBuffer.popfront(tok); return tok; } bool Lexer::putbackToken(Token a) { this->innerBuffer.pushfront(a); return true; } // extracts a single statement, from the current state of the lexer. // Considers `newline` as the delimiter, unless found in paranthesis. // returns a balanced expression. Infix Lexer::getTokensTill(String delim) { Infix ret; Token tmp; while (!this->ended()) { tmp = this->getToken(); if (tmp.type() == DIRECTIVE && tmp.value() == "@eof") return ret; if (tmp.value() == delim) return ret; } } Vector<Error> Lexer::getErrors() const { return this->errors; } bool Lexer::ended() { return (this->source && this->source.eof() && this->innerBuffer.empty()); } bool importLexerData() { Keywords = strsplit("var let typeof String Number Boolean Array and or not equals delete", ' '); InbuiltFunctions = strsplit("print input readNumber readString readLine get", ' '); Constants = strsplit("null infinity true false", ' '); Keywords.append(Constants); Punctuators = strsplit("()[]{},:;"); // operators. binaryOperators = strsplit("+ += - -= * *= / /= % %= = == === != !== > >= < <= && || ? . []", ' '); unaryOperators = strsplit("! ++ --", ' '); Opstarts = strsplit("+-*/%=?&|<>!."); return true; } #endif <commit_msg>add unable to open file to lexer error list<commit_after>#ifdef COMPONENT_LEXER_H // do not include this file directly. // use lexer.h instead. /********************************* * Implementation: Class Token ** *********************************/ // constructors Token::Token(String val, tokenType t, tokenType st, bufferIndex ln, bufferIndex in) { this->_value = val; this->_type = t; this->_subtype = st; this->_line = ln; this->_indent = in; } Token::Token(const Token& t) { this->_value = t._value; this->_type = t._type; this->_subtype = t._subtype; this->_line = t._line; this->_indent = t._indent; } Token Token::operator= (const Token& t) { this->_value = t._value; this->_type = t._type; this->_subtype = t._subtype; this->_line = t._line; this->_indent = t._indent; return *this; } // properties tokenType Token::type() const { return this->_type; } tokenType Token::subtype() const { return this->_subtype; } bufferIndex Token::lineNumber() const { return this->_line; } bufferIndex Token::indent() const { return this->_indent; } String Token::value() const { return this->_value; } // mutators bool Token::setType(tokenType t) { this->_type = t; } bool Token::setSubtype(tokenType st) { this->_subtype = st; } bool Token::setLineNumber(bufferIndex ln) { this->_line = ln; } bool Token::setIndent(bufferIndex in) { this->_indent = in; } bool Token::setValue(String s) { this->_value = s; } // end implementation: class Token /**************************************** * Implementation: Class Lexer ** ****************************************/ // constructors, and dynamic data managers. Lexer::Lexer (String data) { this->source.open(data.c_str()); if (!this->source) this->errors.pushback(Error("l0", data)); this->line = 1; this->indent = 0; } Lexer::~Lexer() { if (this->source) this->source.close(); errors.clear(); innerBuffer.clear(); } /*** static members ***/ bool Lexer::isValidIdentifier(String val) { if (val.length() > MAX_ID_LENGTH) return false; if (!isalpha(val[0]) && val[0] != '_') return false; for (__SIZETYPE i = 0; i < val.length(); i++) if (!isalnum(val[i]) && val[i] != '_') return false; return true; } // maps a keyword to a corresponding operator. // possible only if the keyword can be replaced by the operator in the code, // without altering the flow of logic. String Lexer::entityMap(String val) { if (val == "and") return "&&"; if (val == "or") return "||"; if (val == "not") return "!"; if (val == "equals") return "=="; return val; } // Converts a string into a token, // assumes string to be somewhat valid. Token Lexer::toToken(String val) { if (!val) return nullToken; if (val[0] == -1) return nullToken; val = entityMap(val); // string literal: if (val[0] == '\"' || val[0] == '\'') { return Token(val, LITERAL, STRING); } // numeric literal if (val[0] >= '0' && val[0] <= '9') { return Token(val, LITERAL, NUMBER); } // punctuator if (Punctuators.indexOf(val) >= 0) { return Token(val, PUNCTUATOR); } // keywords if (Keywords.indexOf(val) >= 0) { if (Constants.indexOf(val) >= 0) { if (val == "true" || val == "false") return Token(val, LITERAL, BOOLEAN); return Token(val, KEYWORD, CONSTANT); } return Token(val, KEYWORD); } // inbuilt functions if (InbuiltFunctions.indexOf(val) >= 0) return Token(val, IDENTIFIER, FUNCTION); // operators. assumes that the operator has been extracted properly. if (binaryOperators.indexOf(val) >= 0) { return Token(val, OPERATOR, BINARYOP); } if (unaryOperators.indexOf(val) >= 0) { return Token(val, OPERATOR, UNARYOP); } // identifier if (isValidIdentifier(val)) { return Token(val, IDENTIFIER); } return Token(val); } /*** Member functions: actual lexing procedures. ***/ // removes all leading spaces, and discard comments. int Lexer::trim() { if (this->source.eof()) return -1; int sp = 0; while (this->source.peek() == ' ') { this->source.get(); sp++; } if (this->source.peek() == '#') { while (this->source.get() != '\n' && !this->source.eof()) // ignore the rest of the line. this->endLine(); return this->trim(); } if (this->source.eof()) return -1; return sp; } // Increases the line number, and sets up the next line // extracts the tabs from next line, sets the indent, and returns the number. // assumes that the \n is already read from the buffer. int Lexer::endLine() { this->innerBuffer.pushback(newlineToken); if (this->source.eof()) return -1; this->line++; // extract the indentation. int num = 0; while (this->source.peek() == '\t') { this->source.get(); num++; } this->indent = num; return (num); } // extracts a string: as '...' or "..." String Lexer::readString() { char st = this->source.get(), tmp = 0; String ret = st; while (tmp != st) { tmp = this->source.get(); if (tmp == '\n') { // error. string not terminated properly. this->errors.pushback(Error("l1", "", this->line)); this->endLine(); // return a null string. return ""; } ret += tmp; if (tmp == '\\') { // escape: get the next character. tmp = this->source.get(); if (tmp != '\n') ret += tmp; else this->endLine(); } } return ret; } // reads a numeric value: can contain utmost one decimal point. String Lexer::readNumber() { String num; bool isDeci = false; char ch = this->source.get(); while ((ch >= '0' && ch <= '9') || ch == '.') { if (ch == '.') { if (!isDeci) { isDeci = true; } else { // error- too many decimal points this->errors.pushback(Error("l2", "", this->line)); return ""; } } num += ch; ch = this->source.get(); } if (ch == '\n') { this->endLine(); } else { if (!this->source.eof()) this->source.putback(ch); } return num; } // reads an identifier/keyword, // assuming the starting character in the buffer is a alpha or underscore. // does `not` check whether it is valid. String Lexer::readIdentifier() { String ret; int len = 0; char ch = this->source.get(); while (isalnum(ch) || ch == '_') { ret += ch; len++; ch = this->source.get(); } if (!this->source.eof()) this->source.putback(ch); return ret; } // reads an operator, without touching any adjacent characters. // this does not do a full check for all operators. // note: some operators are 'decided' by the parser, because they depend on situation. String Lexer::readOperator() { char ch = this->source.peek(); if (Opstarts.indexOf(ch) == -1) return ""; this->source.get(); String ret = ch; // check whether can be followed by = static const idList eq(strsplit("+-*/%=!<>")); if (eq.indexOf(ch) >= 0 && this->source.peek() == '=') { ret += (this->source.get()); // a second = if ((ch == '=' || ch == '!') && (this->source.peek() == '=')) { ret += this->source.get(); } } else if (ch == '+' || ch == '-' || ch == '&' || ch == '|') { // operators ++ -- && || if (this->source.peek() == ch) ret += (this->source.get()); } return ret; } Token Lexer::getToken() { // check for a previously buffered token. if (!this->innerBuffer.empty()) { Token tmp; this->innerBuffer.popfront(tmp); return tmp; } this->trim(); char ch = this->source.peek(); if (this->source.eof()) return eofToken; String val; bufferIndex tline = this->line, tindent = this->indent; if (ch == '\n') { this->source.get(); this->endLine(); return this->getToken(); } if (ch == '\'' || ch == '\"') { val = this->readString(); // string literal } else if (isalpha(ch) || ch == '_') { val = this->readIdentifier(); // identifier/keyword } else if (isdigit(ch)) { val = this->readNumber(); // numeric constant } else if (Punctuators.indexOf(ch) >= 0) { val = ch; // punctuator. keep it as it is."; this->source.get(); } else if (Opstarts.indexOf(ch) >= 0) { val = this->readOperator(); } else { // just ignore the character, as of now. This should flag an unknown character error. val = ch; this->source.get(); } Token tok = toToken(val); tok.setLineNumber(tline); tok.setIndent(tindent); this->innerBuffer.pushback(tok); this->innerBuffer.popfront(tok); return tok; } bool Lexer::putbackToken(Token a) { this->innerBuffer.pushfront(a); return true; } // extracts a single statement, from the current state of the lexer. // Considers `newline` as the delimiter, unless found in paranthesis. // returns a balanced expression. Infix Lexer::getTokensTill(String delim) { Infix ret; Token tmp; while (!this->ended()) { tmp = this->getToken(); if (tmp.type() == DIRECTIVE && tmp.value() == "@eof") return ret; if (tmp.value() == delim) return ret; } } Vector<Error> Lexer::getErrors() const { return this->errors; } bool Lexer::ended() { return (this->source && this->source.eof() && this->innerBuffer.empty()); } bool importLexerData() { Keywords = strsplit("var let typeof String Number Boolean Array and or not equals delete", ' '); InbuiltFunctions = strsplit("print input readNumber readString readLine get", ' '); Constants = strsplit("null infinity true false", ' '); Keywords.append(Constants); Punctuators = strsplit("()[]{},:;"); // operators. binaryOperators = strsplit("+ += - -= * *= / /= % %= = == === != !== > >= < <= && || ? . []", ' '); unaryOperators = strsplit("! ++ --", ' '); Opstarts = strsplit("+-*/%=?&|<>!."); return true; } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2009-2014 Mark D. Hill and David A. Wood * 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 copyright holders 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 __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__ #define __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__ #include <exception> #include <iostream> #include <string> #include "base/callback.hh" #include "mem/protocol/AccessPermission.hh" #include "mem/ruby/common/Address.hh" #include "mem/ruby/common/Consumer.hh" #include "mem/ruby/common/DataBlock.hh" #include "mem/ruby/common/Histogram.hh" #include "mem/ruby/common/MachineID.hh" #include "mem/ruby/network/MessageBuffer.hh" #include "mem/ruby/network/Network.hh" #include "mem/ruby/system/CacheRecorder.hh" #include "mem/packet.hh" #include "mem/qport.hh" #include "params/RubyController.hh" #include "mem/mem_object.hh" class Network; // used to communicate that an in_port peeked the wrong message type class RejectException: public std::exception { virtual const char* what() const throw() { return "Port rejected message based on type"; } }; class AbstractController : public MemObject, public Consumer { public: typedef RubyControllerParams Params; AbstractController(const Params *p); void init(); const Params *params() const { return (const Params *)_params; } const NodeID getVersion() const { return m_machineID.getNum(); } const MachineType getType() const { return m_machineID.getType(); } void initNetworkPtr(Network* net_ptr) { m_net_ptr = net_ptr; } // return instance name void blockOnQueue(Addr, MessageBuffer*); void unblock(Addr); virtual MessageBuffer* getMandatoryQueue() const = 0; virtual MessageBuffer* getMemoryQueue() const = 0; virtual AccessPermission getAccessPermission(const Addr &addr) = 0; virtual void print(std::ostream & out) const = 0; virtual void wakeup() = 0; virtual void resetStats() = 0; virtual void regStats(); virtual void recordCacheTrace(int cntrl, CacheRecorder* tr) = 0; virtual Sequencer* getSequencer() const = 0; //! These functions are used by ruby system to read/write the data blocks //! that exist with in the controller. virtual void functionalRead(const Addr &addr, PacketPtr) = 0; void functionalMemoryRead(PacketPtr); //! The return value indicates the number of messages written with the //! data from the packet. virtual int functionalWriteBuffers(PacketPtr&) = 0; virtual int functionalWrite(const Addr &addr, PacketPtr) = 0; int functionalMemoryWrite(PacketPtr); //! Function for enqueuing a prefetch request virtual void enqueuePrefetch(const Addr &, const RubyRequestType&) { fatal("Prefetches not implemented!");} //! Function for collating statistics from all the controllers of this //! particular type. This function should only be called from the //! version 0 of this controller type. virtual void collateStats() {fatal("collateStats() should be overridden!");} //! Initialize the message buffers. virtual void initNetQueues() = 0; /** A function used to return the port associated with this bus object. */ BaseMasterPort& getMasterPort(const std::string& if_name, PortID idx = InvalidPortID); void queueMemoryRead(const MachineID &id, Addr addr, Cycles latency); void queueMemoryWrite(const MachineID &id, Addr addr, Cycles latency, const DataBlock &block); void queueMemoryWritePartial(const MachineID &id, Addr addr, Cycles latency, const DataBlock &block, int size); void recvTimingResp(PacketPtr pkt); public: MachineID getMachineID() const { return m_machineID; } Stats::Histogram& getDelayHist() { return m_delayHistogram; } Stats::Histogram& getDelayVCHist(uint32_t index) { return *(m_delayVCHistogram[index]); } protected: //! Profiles original cache requests including PUTs void profileRequest(const std::string &request); //! Profiles the delay associated with messages. void profileMsgDelay(uint32_t virtualNetwork, Cycles delay); void stallBuffer(MessageBuffer* buf, Addr addr); void wakeUpBuffers(Addr addr); void wakeUpAllBuffers(Addr addr); void wakeUpAllBuffers(); protected: NodeID m_version; MachineID m_machineID; NodeID m_clusterID; // MasterID used by some components of gem5. MasterID m_masterId; Network* m_net_ptr; bool m_is_blocking; std::map<Addr, MessageBuffer*> m_block_map; typedef std::vector<MessageBuffer*> MsgVecType; typedef std::set<MessageBuffer*> MsgBufType; typedef std::map<Addr, MsgVecType* > WaitingBufType; WaitingBufType m_waiting_buffers; unsigned int m_in_ports; unsigned int m_cur_in_port; int m_number_of_TBEs; int m_transitions_per_cycle; unsigned int m_buffer_size; Cycles m_recycle_latency; //! Counter for the number of cycles when the transitions carried out //! were equal to the maximum allowed Stats::Scalar m_fully_busy_cycles; //! Histogram for profiling delay for the messages this controller //! cares for Stats::Histogram m_delayHistogram; std::vector<Stats::Histogram *> m_delayVCHistogram; //! Callback class used for collating statistics from all the //! controller of this type. class StatsCallback : public Callback { private: AbstractController *ctr; public: virtual ~StatsCallback() {} StatsCallback(AbstractController *_ctr) : ctr(_ctr) {} void process() {ctr->collateStats();} }; /** * Port that forwards requests and receives responses from the * memory controller. It has a queue of packets not yet sent. */ class MemoryPort : public QueuedMasterPort { private: // Packet queues used to store outgoing requests and snoop responses. ReqPacketQueue reqQueue; SnoopRespPacketQueue snoopRespQueue; // Controller that operates this port. AbstractController *controller; public: MemoryPort(const std::string &_name, AbstractController *_controller, const std::string &_label); // Function for receiving a timing response from the peer port. // Currently the pkt is handed to the coherence controller // associated with this port. bool recvTimingResp(PacketPtr pkt); }; /* Master port to the memory controller. */ MemoryPort memoryPort; // State that is stored in packets sent to the memory controller. struct SenderState : public Packet::SenderState { // Id of the machine from which the request originated. MachineID id; SenderState(MachineID _id) : id(_id) {} }; }; #endif // __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__ <commit_msg>ruby: abstract controller: mark some variables as const<commit_after>/* * Copyright (c) 2009-2014 Mark D. Hill and David A. Wood * 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 copyright holders 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 __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__ #define __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__ #include <exception> #include <iostream> #include <string> #include "base/callback.hh" #include "mem/protocol/AccessPermission.hh" #include "mem/ruby/common/Address.hh" #include "mem/ruby/common/Consumer.hh" #include "mem/ruby/common/DataBlock.hh" #include "mem/ruby/common/Histogram.hh" #include "mem/ruby/common/MachineID.hh" #include "mem/ruby/network/MessageBuffer.hh" #include "mem/ruby/network/Network.hh" #include "mem/ruby/system/CacheRecorder.hh" #include "mem/packet.hh" #include "mem/qport.hh" #include "params/RubyController.hh" #include "mem/mem_object.hh" class Network; // used to communicate that an in_port peeked the wrong message type class RejectException: public std::exception { virtual const char* what() const throw() { return "Port rejected message based on type"; } }; class AbstractController : public MemObject, public Consumer { public: typedef RubyControllerParams Params; AbstractController(const Params *p); void init(); const Params *params() const { return (const Params *)_params; } const NodeID getVersion() const { return m_machineID.getNum(); } const MachineType getType() const { return m_machineID.getType(); } void initNetworkPtr(Network* net_ptr) { m_net_ptr = net_ptr; } // return instance name void blockOnQueue(Addr, MessageBuffer*); void unblock(Addr); virtual MessageBuffer* getMandatoryQueue() const = 0; virtual MessageBuffer* getMemoryQueue() const = 0; virtual AccessPermission getAccessPermission(const Addr &addr) = 0; virtual void print(std::ostream & out) const = 0; virtual void wakeup() = 0; virtual void resetStats() = 0; virtual void regStats(); virtual void recordCacheTrace(int cntrl, CacheRecorder* tr) = 0; virtual Sequencer* getSequencer() const = 0; //! These functions are used by ruby system to read/write the data blocks //! that exist with in the controller. virtual void functionalRead(const Addr &addr, PacketPtr) = 0; void functionalMemoryRead(PacketPtr); //! The return value indicates the number of messages written with the //! data from the packet. virtual int functionalWriteBuffers(PacketPtr&) = 0; virtual int functionalWrite(const Addr &addr, PacketPtr) = 0; int functionalMemoryWrite(PacketPtr); //! Function for enqueuing a prefetch request virtual void enqueuePrefetch(const Addr &, const RubyRequestType&) { fatal("Prefetches not implemented!");} //! Function for collating statistics from all the controllers of this //! particular type. This function should only be called from the //! version 0 of this controller type. virtual void collateStats() {fatal("collateStats() should be overridden!");} //! Initialize the message buffers. virtual void initNetQueues() = 0; /** A function used to return the port associated with this bus object. */ BaseMasterPort& getMasterPort(const std::string& if_name, PortID idx = InvalidPortID); void queueMemoryRead(const MachineID &id, Addr addr, Cycles latency); void queueMemoryWrite(const MachineID &id, Addr addr, Cycles latency, const DataBlock &block); void queueMemoryWritePartial(const MachineID &id, Addr addr, Cycles latency, const DataBlock &block, int size); void recvTimingResp(PacketPtr pkt); public: MachineID getMachineID() const { return m_machineID; } Stats::Histogram& getDelayHist() { return m_delayHistogram; } Stats::Histogram& getDelayVCHist(uint32_t index) { return *(m_delayVCHistogram[index]); } protected: //! Profiles original cache requests including PUTs void profileRequest(const std::string &request); //! Profiles the delay associated with messages. void profileMsgDelay(uint32_t virtualNetwork, Cycles delay); void stallBuffer(MessageBuffer* buf, Addr addr); void wakeUpBuffers(Addr addr); void wakeUpAllBuffers(Addr addr); void wakeUpAllBuffers(); protected: const NodeID m_version; MachineID m_machineID; const NodeID m_clusterID; // MasterID used by some components of gem5. const MasterID m_masterId; Network *m_net_ptr; bool m_is_blocking; std::map<Addr, MessageBuffer*> m_block_map; typedef std::vector<MessageBuffer*> MsgVecType; typedef std::set<MessageBuffer*> MsgBufType; typedef std::map<Addr, MsgVecType* > WaitingBufType; WaitingBufType m_waiting_buffers; unsigned int m_in_ports; unsigned int m_cur_in_port; const int m_number_of_TBEs; const int m_transitions_per_cycle; const unsigned int m_buffer_size; Cycles m_recycle_latency; //! Counter for the number of cycles when the transitions carried out //! were equal to the maximum allowed Stats::Scalar m_fully_busy_cycles; //! Histogram for profiling delay for the messages this controller //! cares for Stats::Histogram m_delayHistogram; std::vector<Stats::Histogram *> m_delayVCHistogram; //! Callback class used for collating statistics from all the //! controller of this type. class StatsCallback : public Callback { private: AbstractController *ctr; public: virtual ~StatsCallback() {} StatsCallback(AbstractController *_ctr) : ctr(_ctr) {} void process() {ctr->collateStats();} }; /** * Port that forwards requests and receives responses from the * memory controller. It has a queue of packets not yet sent. */ class MemoryPort : public QueuedMasterPort { private: // Packet queues used to store outgoing requests and snoop responses. ReqPacketQueue reqQueue; SnoopRespPacketQueue snoopRespQueue; // Controller that operates this port. AbstractController *controller; public: MemoryPort(const std::string &_name, AbstractController *_controller, const std::string &_label); // Function for receiving a timing response from the peer port. // Currently the pkt is handed to the coherence controller // associated with this port. bool recvTimingResp(PacketPtr pkt); }; /* Master port to the memory controller. */ MemoryPort memoryPort; // State that is stored in packets sent to the memory controller. struct SenderState : public Packet::SenderState { // Id of the machine from which the request originated. MachineID id; SenderState(MachineID _id) : id(_id) {} }; }; #endif // __MEM_RUBY_SLICC_INTERFACE_ABSTRACTCONTROLLER_HH__ <|endoftext|>
<commit_before>/** * @file * @brief Implements the particle generator * @remark Based on code from John Idarraga * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied * verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities * granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "GeneratorActionG4.hpp" #include <limits> #include <memory> #include <G4Event.hh> #include <G4GeneralParticleSource.hh> #include <G4ParticleDefinition.hh> #include <G4ParticleTable.hh> #include <array> #include "core/config/exceptions.h" #include "core/utils/log.h" #include "tools/geant4.h" using namespace allpix; GeneratorActionG4::GeneratorActionG4(const Configuration& config) : particle_source_(std::make_unique<G4GeneralParticleSource>()) { // Set verbosity of source to off particle_source_->SetVerbosity(0); // Get source specific parameters auto single_source = particle_source_->GetCurrentSource(); auto source_type = config.get<std::string>("beam_source_type", ""); // Find Geant4 particle auto pdg_table = G4ParticleTable::GetParticleTable(); auto particle_type = config.get<std::string>("particle_type", ""); std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower); auto particle_code = config.get<int>("particle_code", 0); G4ParticleDefinition* particle = nullptr; if(source_type.empty() && !particle_type.empty() && particle_code != 0) { // if(!particle_type.empty() && particle_code != 0) { if(pdg_table->FindParticle(particle_type) == pdg_table->FindParticle(particle_code)) { LOG(WARNING) << "particle_type and particle_code given. Continuing because t hey match."; particle = pdg_table->FindParticle(particle_code); if(particle == nullptr) { throw InvalidValueError(config, "particle_code", "particle code does not exist."); } } else { throw InvalidValueError( config, "particle_type", "Given particle_type does not match particle_code. Please remove one of them."); } } else if(source_type.empty() && particle_type.empty() && particle_code == 0) { throw InvalidValueError(config, "particle_code", "Please set particle_code or particle_type."); } else if(source_type.empty() && particle_code != 0) { particle = pdg_table->FindParticle(particle_code); if(particle == nullptr) { throw InvalidValueError(config, "particle_code", "particle code does not exist."); } } else if(source_type.empty() && !particle_type.empty()) { particle = pdg_table->FindParticle(particle_type); if(particle == nullptr) { throw InvalidValueError(config, "particle_type", "particle type does not exist."); } } else { if(source_type.empty()) { throw InvalidValueError(config, "source_type", "Please set source type."); } } LOG(DEBUG) << "Using particle " << particle->GetParticleName() << " (ID " << particle->GetPDGEncoding() << ")."; // Set global parameters of the source if(!particle_type.empty() || particle_code != 0) { single_source->SetNumberOfParticles(1); single_source->SetParticleDefinition(particle); // Set the primary track's start time in for the current event to zero: single_source->SetParticleTime(0.0); } // Set position parameters single_source->GetPosDist()->SetPosDisType("Beam"); single_source->GetPosDist()->SetBeamSigmaInR(config.get<double>("beam_size", 0)); single_source->GetPosDist()->SetCentreCoords(config.get<G4ThreeVector>("beam_position")); // Set angle distribution parameters single_source->GetAngDist()->SetAngDistType("beam2d"); single_source->GetAngDist()->DefineAngRefAxes("angref1", G4ThreeVector(-1., 0, 0)); G4TwoVector divergence = config.get<G4TwoVector>("beam_divergence", G4TwoVector(0., 0.)); single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x()); single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y()); G4ThreeVector direction = config.get<G4ThreeVector>("beam_direction"); if(fabs(direction.mag() - 1.0) > std::numeric_limits<double>::epsilon()) { LOG(WARNING) << "Momentum direction is not a unit vector: magnitude is ignored"; } if(!particle_type.empty() || particle_code != 0) { single_source->GetAngDist()->SetParticleMomentumDirection(direction); } // Set energy parameters auto energy_type = config.get<std::string>("beam_energy_type", ""); if(energy_type == "User") { single_source->GetEneDist()->SetEnergyDisType(energy_type); auto beam_hist_point = config.getArray<G4ThreeVector>("beam_hist_point"); for(auto& hist_point : beam_hist_point) { single_source->GetEneDist()->UserEnergyHisto(hist_point); } } else if(source_type == "Iron-55") { std::stringstream ss; ss << "gamma"; particle_type.assign(ss.str()); std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower); particle = pdg_table->FindParticle(particle_type); single_source->SetNumberOfParticles(1); single_source->SetParticleDefinition(particle); single_source->SetParticleTime(0.0); single_source->GetAngDist()->SetParticleMomentumDirection(direction); single_source->GetEneDist()->SetEnergyDisType("User"); G4ThreeVector hist_point1(0.0059, 28., 0.1), hist_point2(0.00649, 2.85, 0.1); std::array<G4ThreeVector, 2> beam_hist_point = {{hist_point1, hist_point2}}; for(auto& hist_point : beam_hist_point) { single_source->GetEneDist()->UserEnergyHisto(hist_point); } } else { single_source->GetEneDist()->SetEnergyDisType("Gauss"); single_source->GetEneDist()->SetMonoEnergy(config.get<double>("beam_energy")); } single_source->GetEneDist()->SetBeamSigmaInE(config.get<double>("beam_energy_spread", 0.)); } /** * Called automatically for every event */ void GeneratorActionG4::GeneratePrimaries(G4Event* event) { particle_source_->GeneratePrimaryVertex(event); } <commit_msg>Add a new way to generate particles: using energy spectra with energy spread<commit_after>/** * @file * @brief Implements the particle generator * @remark Based on code from John Idarraga * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied * verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities * granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "GeneratorActionG4.hpp" #include <limits> #include <memory> #include <G4Event.hh> #include <G4GeneralParticleSource.hh> #include <G4ParticleDefinition.hh> #include <G4ParticleTable.hh> #include <Randomize.hh> #include <array> #include "core/config/exceptions.h" #include "core/utils/log.h" #include "tools/geant4.h" using namespace allpix; GeneratorActionG4::GeneratorActionG4(const Configuration& config) : particle_source_(std::make_unique<G4GeneralParticleSource>()) { // Set verbosity of source to off particle_source_->SetVerbosity(0); // Get source specific parameters auto single_source = particle_source_->GetCurrentSource(); auto source_type = config.get<std::string>("beam_source_type", ""); // Find Geant4 particle auto pdg_table = G4ParticleTable::GetParticleTable(); auto particle_type = config.get<std::string>("particle_type", ""); std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower); auto particle_code = config.get<int>("particle_code", 0); G4ParticleDefinition* particle = nullptr; if(source_type.empty() && !particle_type.empty() && particle_code != 0) { // if(!particle_type.empty() && particle_code != 0) { if(pdg_table->FindParticle(particle_type) == pdg_table->FindParticle(particle_code)) { LOG(WARNING) << "particle_type and particle_code given. Continuing because t hey match."; particle = pdg_table->FindParticle(particle_code); if(particle == nullptr) { throw InvalidValueError(config, "particle_code", "particle code does not exist."); } } else { throw InvalidValueError( config, "particle_type", "Given particle_type does not match particle_code. Please remove one of them."); } } else if(source_type.empty() && particle_type.empty() && particle_code == 0) { throw InvalidValueError(config, "particle_code", "Please set particle_code or particle_type."); } else if(source_type.empty() && particle_code != 0) { particle = pdg_table->FindParticle(particle_code); if(particle == nullptr) { throw InvalidValueError(config, "particle_code", "particle code does not exist."); } } else if(source_type.empty() && !particle_type.empty()) { particle = pdg_table->FindParticle(particle_type); if(particle == nullptr) { throw InvalidValueError(config, "particle_type", "particle type does not exist."); } } else { if(source_type.empty()) { throw InvalidValueError(config, "source_type", "Please set source type."); } } LOG(DEBUG) << "Using particle " << particle->GetParticleName() << " (ID " << particle->GetPDGEncoding() << ")."; // Set global parameters of the source if(!particle_type.empty() || particle_code != 0) { single_source->SetNumberOfParticles(1); single_source->SetParticleDefinition(particle); // Set the primary track's start time in for the current event to zero: single_source->SetParticleTime(0.0); } // Set position parameters single_source->GetPosDist()->SetPosDisType("Beam"); single_source->GetPosDist()->SetBeamSigmaInR(config.get<double>("beam_size", 0)); single_source->GetPosDist()->SetCentreCoords(config.get<G4ThreeVector>("beam_position")); // Set angle distribution parameters single_source->GetAngDist()->SetAngDistType("beam2d"); single_source->GetAngDist()->DefineAngRefAxes("angref1", G4ThreeVector(-1., 0, 0)); G4TwoVector divergence = config.get<G4TwoVector>("beam_divergence", G4TwoVector(0., 0.)); single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x()); single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y()); G4ThreeVector direction = config.get<G4ThreeVector>("beam_direction"); if(fabs(direction.mag() - 1.0) > std::numeric_limits<double>::epsilon()) { LOG(WARNING) << "Momentum direction is not a unit vector: magnitude is ignored"; } if(!particle_type.empty() || particle_code != 0) { single_source->GetAngDist()->SetParticleMomentumDirection(direction); } // Set energy parameters auto energy_type = config.get<std::string>("beam_energy_type", ""); if(energy_type == "User") { single_source->GetEneDist()->SetEnergyDisType(energy_type); auto beam_hist_point = config.getArray<G4ThreeVector>("beam_hist_point"); for(auto& hist_point : beam_hist_point) { single_source->GetEneDist()->UserEnergyHisto(hist_point); } } else if(source_type == "Iron-55") { std::stringstream ss; ss << "gamma"; particle_type.assign(ss.str()); std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower); particle = pdg_table->FindParticle(particle_type); single_source->SetNumberOfParticles(1); single_source->SetParticleDefinition(particle); single_source->SetParticleTime(0.0); single_source->GetAngDist()->SetParticleMomentumDirection(direction); single_source->GetEneDist()->SetEnergyDisType("User"); G4double energy_hist_1[10]; G4double intensity_hist_1[10]; for(G4int i = 0; i < 10; i++) { energy_hist_1[i] = 0.0059 + 0.0001 * (1 - 2 * G4UniformRand()); intensity_hist_1[i] = 28. + 0.1 * (1 - 2 * G4UniformRand()); single_source->GetEneDist()->UserEnergyHisto(G4ThreeVector(energy_hist_1[i], intensity_hist_1[i], 0.)); } G4double energy_hist_2[10]; G4double intensity_hist_2[10]; for(G4int i = 0; i < 10; i++) { energy_hist_2[i] = 0.00649 + 0.0001 * (1 - 2 * G4UniformRand()); intensity_hist_2[i] = 2.85 + 0.01 * (1 - 2 * G4UniformRand()); single_source->GetEneDist()->UserEnergyHisto(G4ThreeVector(energy_hist_2[i], intensity_hist_2[i], 0.)); } } else { single_source->GetEneDist()->SetEnergyDisType("Gauss"); single_source->GetEneDist()->SetMonoEnergy(config.get<double>("beam_energy")); } single_source->GetEneDist()->SetBeamSigmaInE(config.get<double>("beam_energy_spread", 0.)); } /** * Called automatically for every event */ void GeneratorActionG4::GeneratePrimaries(G4Event* event) { particle_source_->GeneratePrimaryVertex(event); } <|endoftext|>
<commit_before>/** * @file * @brief Implements the particle generator * @remark Based on code from John Idarraga * @copyright MIT License */ #include "GeneratorActionG4.hpp" #include <limits> #include <memory> #include <G4Event.hh> #include <G4GeneralParticleSource.hh> #include <G4ParticleDefinition.hh> #include <G4ParticleTable.hh> #include "core/config/exceptions.h" #include "core/utils/log.h" #include "tools/geant4.h" using namespace allpix; GeneratorActionG4::GeneratorActionG4(const Configuration& config) : particle_source_(std::make_unique<G4GeneralParticleSource>()) { // Set verbosity of source to off particle_source_->SetVerbosity(0); // Get source specific parameters auto single_source = particle_source_->GetCurrentSource(); // Find Geant4 particle G4ParticleDefinition* particle = G4ParticleTable::GetParticleTable()->FindParticle(config.get<std::string>("particle_type")); if(particle == nullptr) { // FIXME more information about available particle throw InvalidValueError(config, "particle_type", "particle type does not exist"); } // Set global parameters of the source // FIXME keep number of particles always at one? single_source->SetNumberOfParticles(1); single_source->SetParticleDefinition(particle); // FIXME What is this time single_source->SetParticleTime(0.0); // Set position parameters single_source->GetPosDist()->SetPosDisType("Beam"); single_source->GetPosDist()->SetBeamSigmaInR(config.get<double>("particle_radius_sigma", 0)); single_source->GetPosDist()->SetCentreCoords(config.get<G4ThreeVector>("particle_position")); // Set angle distribution parameters single_source->GetAngDist()->SetAngDistType("beam2d"); single_source->GetAngDist()->DefineAngRefAxes("angref1", G4ThreeVector(-1., 0, 0)); G4TwoVector divergence = config.get<G4TwoVector>("particle_divergence_xy", G4TwoVector(0., 0.)); single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x()); single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y()); G4ThreeVector direction = config.get<G4ThreeVector>("particle_direction"); if(fabs(direction.mag() - 1.0) > std::numeric_limits<double>::epsilon()) { LOG(WARNING) << "Momentum direction is not a unit vector: magnitude is ignored"; } single_source->GetAngDist()->SetParticleMomentumDirection(direction); // Set energy parameters single_source->GetEneDist()->SetEnergyDisType("Mono"); single_source->GetEneDist()->SetMonoEnergy(config.get<double>("particle_energy")); } /** * Called automatically for every event */ void GeneratorActionG4::GeneratePrimaries(G4Event* event) { particle_source_->GeneratePrimaryVertex(event); } <commit_msg>Implement energy spread. Using parameter particle_energy_spread<commit_after>/** * @file * @brief Implements the particle generator * @remark Based on code from John Idarraga * @copyright MIT License */ #include "GeneratorActionG4.hpp" #include <limits> #include <memory> #include <G4Event.hh> #include <G4GeneralParticleSource.hh> #include <G4ParticleDefinition.hh> #include <G4ParticleTable.hh> #include "core/config/exceptions.h" #include "core/utils/log.h" #include "tools/geant4.h" using namespace allpix; GeneratorActionG4::GeneratorActionG4(const Configuration& config) : particle_source_(std::make_unique<G4GeneralParticleSource>()) { // Set verbosity of source to off particle_source_->SetVerbosity(0); // Get source specific parameters auto single_source = particle_source_->GetCurrentSource(); // Find Geant4 particle G4ParticleDefinition* particle = G4ParticleTable::GetParticleTable()->FindParticle(config.get<std::string>("particle_type")); if(particle == nullptr) { // FIXME more information about available particle throw InvalidValueError(config, "particle_type", "particle type does not exist"); } // Set global parameters of the source // FIXME keep number of particles always at one? single_source->SetNumberOfParticles(1); single_source->SetParticleDefinition(particle); // FIXME What is this time single_source->SetParticleTime(0.0); // Set position parameters single_source->GetPosDist()->SetPosDisType("Beam"); single_source->GetPosDist()->SetBeamSigmaInR(config.get<double>("particle_radius_sigma", 0)); single_source->GetPosDist()->SetCentreCoords(config.get<G4ThreeVector>("particle_position")); // Set angle distribution parameters single_source->GetAngDist()->SetAngDistType("beam2d"); single_source->GetAngDist()->DefineAngRefAxes("angref1", G4ThreeVector(-1., 0, 0)); G4TwoVector divergence = config.get<G4TwoVector>("particle_divergence_xy", G4TwoVector(0., 0.)); single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x()); single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y()); G4ThreeVector direction = config.get<G4ThreeVector>("particle_direction"); if(fabs(direction.mag() - 1.0) > std::numeric_limits<double>::epsilon()) { LOG(WARNING) << "Momentum direction is not a unit vector: magnitude is ignored"; } single_source->GetAngDist()->SetParticleMomentumDirection(direction); // Set energy parameters single_source->GetEneDist()->SetEnergyDisType("Gauss"); single_source->GetEneDist()->SetMonoEnergy(config.get<double>("particle_energy")); single_source->GetEneDist()->SetBeamSigmaInE(config.get<double>("particle_energy_spread", 0.)); } /** * Called automatically for every event */ void GeneratorActionG4::GeneratePrimaries(G4Event* event) { particle_source_->GeneratePrimaryVertex(event); } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins_config.h" #include "grins/boussinesq_buoyancy_adjoint_stab.h" // GRINS #include "grins/assembly_context.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/string_to_enum.h" #include "libmesh/fem_system.h" #include "libmesh/quadrature.h" namespace GRINS { BoussinesqBuoyancyAdjointStabilization::BoussinesqBuoyancyAdjointStabilization( const std::string& physics_name, const GetPot& input ) : BoussinesqBuoyancyBase(physics_name,input), /* \todo Do we want to have these come from a BoussinesqBuoyancyAdjointStabilization section instead? */ _rho( input("Physics/"+incompressible_navier_stokes+"/rho", 1.0) ), _mu( input("Physics/"+incompressible_navier_stokes+"/mu", 1.0) ), _stab_helper( input ), _p_var_name( input("Physics/VariableNames/pressure", p_var_name_default ) ), _P_FE_family( libMesh::Utility::string_to_enum<libMeshEnums::FEFamily>( input("Physics/"+incompressible_navier_stokes+"/FE_family", "LAGRANGE") ) ), _P_order( libMesh::Utility::string_to_enum<libMeshEnums::Order>( input("Physics/"+incompressible_navier_stokes+"/P_order", "FIRST") ) ) { return; } BoussinesqBuoyancyAdjointStabilization::~BoussinesqBuoyancyAdjointStabilization() { return; } void BoussinesqBuoyancyAdjointStabilization::init_context( AssemblyContext& context ) { context.get_element_fe(this->_p_var)->get_dphi(); context.get_element_fe(this->_u_var)->get_dphi(); context.get_element_fe(this->_u_var)->get_d2phi(); return; } void BoussinesqBuoyancyAdjointStabilization::init_variables( libMesh::FEMSystem* system ) { // First call base class BoussinesqBuoyancyBase::init_variables(system); _p_var = system->add_variable( _p_var_name, this->_P_order, _P_FE_family); return; } void BoussinesqBuoyancyAdjointStabilization::element_time_derivative( bool compute_jacobian, AssemblyContext& context, CachedValues& /*cache*/ ) { #ifdef GRINS_USE_GRVY_TIMERS this->_timer->BeginTimer("BoussinesqBuoyancyAdjointStabilization::element_time_derivative"); #endif // The number of local degrees of freedom in each variable. const unsigned int n_u_dofs = context.get_dof_indices(_u_var).size(); const unsigned int n_p_dofs = context.get_dof_indices(_p_var).size(); // Element Jacobian * quadrature weights for interior integration. const std::vector<libMesh::Real> &JxW = context.get_element_fe(_u_var)->get_JxW(); const std::vector<std::vector<libMesh::RealGradient> >& u_gradphi = context.get_element_fe(this->_u_var)->get_dphi(); const std::vector<std::vector<libMesh::RealTensor> >& u_hessphi = context.get_element_fe(this->_u_var)->get_d2phi(); const std::vector<std::vector<libMesh::RealGradient> >& p_dphi = context.get_element_fe(this->_p_var)->get_dphi(); // Get residuals libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(_u_var); // R_{u} libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(_v_var); // R_{v} libMesh::DenseSubVector<libMesh::Number> *Fw = NULL; if(this->_dim == 3) Fw = &context.get_elem_residual(this->_w_var); // R_{w} libMesh::DenseSubVector<libMesh::Number> &Fp = context.get_elem_residual(this->_p_var); // R_{p} // Now we will build the element Jacobian and residual. // Constructing the residual requires the solution and its // gradient from the previous timestep. This must be // calculated at each quadrature point by summing the // solution degree-of-freedom values by the appropriate // weight functions. unsigned int n_qpoints = context.get_element_qrule().n_points(); libMesh::FEBase* fe = context.get_element_fe(this->_u_var); for (unsigned int qp=0; qp != n_qpoints; qp++) { libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp ); libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp ); libMesh::RealGradient U( context.interior_value( this->_u_var, qp ), context.interior_value( this->_v_var, qp ) ); if( this->_dim == 3 ) { U(2) = context.interior_value( this->_w_var, qp ); } libMesh::Real tau_M = this->_stab_helper.compute_tau_momentum( context, qp, g, G, this->_rho, U, this->_mu, this->_is_steady ); // Compute the solution & its gradient at the old Newton iterate. libMesh::Number T; T = context.interior_value(_T_var, qp); libMesh::RealGradient residual = -_rho_ref*_beta_T*(T-_T_ref)*_g; // First, an i-loop over the velocity degrees of freedom. // We know that n_u_dofs == n_v_dofs so we can compute contributions // for both at the same time. for (unsigned int i=0; i != n_p_dofs; i++) { Fp(i) += tau_M*residual*p_dphi[i][qp]*JxW[qp]; } for (unsigned int i=0; i != n_u_dofs; i++) { Fu(i) += ( this->_rho*U*u_gradphi[i][qp] + this->_mu*( u_hessphi[i][qp](0,0) + u_hessphi[i][qp](1,1) + u_hessphi[i][qp](2,2) ) )*tau_M*residual(0)*JxW[qp]; Fv(i) += ( this->_rho*U*u_gradphi[i][qp] + this->_mu*( u_hessphi[i][qp](0,0) + u_hessphi[i][qp](1,1) + u_hessphi[i][qp](2,2) ) )*tau_M*residual(1)*JxW[qp]; if (_dim == 3) { (*Fw)(i) += ( this->_rho*U*u_gradphi[i][qp] + this->_mu*( u_hessphi[i][qp](0,0) + u_hessphi[i][qp](1,1) + u_hessphi[i][qp](2,2) ) )*tau_M*residual(2)*JxW[qp]; } if (compute_jacobian) { libmesh_not_implemented(); } // End compute_jacobian check } // End i dof loop } // End quadrature loop #ifdef GRINS_USE_GRVY_TIMERS this->_timer->EndTimer("BoussinesqBuoyancyAdjointStabilization::element_time_derivative"); #endif return; } } // namespace GRINS <commit_msg>untabify<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins_config.h" #include "grins/boussinesq_buoyancy_adjoint_stab.h" // GRINS #include "grins/assembly_context.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/string_to_enum.h" #include "libmesh/fem_system.h" #include "libmesh/quadrature.h" namespace GRINS { BoussinesqBuoyancyAdjointStabilization::BoussinesqBuoyancyAdjointStabilization( const std::string& physics_name, const GetPot& input ) : BoussinesqBuoyancyBase(physics_name,input), /* \todo Do we want to have these come from a BoussinesqBuoyancyAdjointStabilization section instead? */ _rho( input("Physics/"+incompressible_navier_stokes+"/rho", 1.0) ), _mu( input("Physics/"+incompressible_navier_stokes+"/mu", 1.0) ), _stab_helper( input ), _p_var_name( input("Physics/VariableNames/pressure", p_var_name_default ) ), _P_FE_family( libMesh::Utility::string_to_enum<libMeshEnums::FEFamily>( input("Physics/"+incompressible_navier_stokes+"/FE_family", "LAGRANGE") ) ), _P_order( libMesh::Utility::string_to_enum<libMeshEnums::Order>( input("Physics/"+incompressible_navier_stokes+"/P_order", "FIRST") ) ) { return; } BoussinesqBuoyancyAdjointStabilization::~BoussinesqBuoyancyAdjointStabilization() { return; } void BoussinesqBuoyancyAdjointStabilization::init_context( AssemblyContext& context ) { context.get_element_fe(this->_p_var)->get_dphi(); context.get_element_fe(this->_u_var)->get_dphi(); context.get_element_fe(this->_u_var)->get_d2phi(); return; } void BoussinesqBuoyancyAdjointStabilization::init_variables( libMesh::FEMSystem* system ) { // First call base class BoussinesqBuoyancyBase::init_variables(system); _p_var = system->add_variable( _p_var_name, this->_P_order, _P_FE_family); return; } void BoussinesqBuoyancyAdjointStabilization::element_time_derivative( bool compute_jacobian, AssemblyContext& context, CachedValues& /*cache*/ ) { #ifdef GRINS_USE_GRVY_TIMERS this->_timer->BeginTimer("BoussinesqBuoyancyAdjointStabilization::element_time_derivative"); #endif // The number of local degrees of freedom in each variable. const unsigned int n_u_dofs = context.get_dof_indices(_u_var).size(); const unsigned int n_p_dofs = context.get_dof_indices(_p_var).size(); // Element Jacobian * quadrature weights for interior integration. const std::vector<libMesh::Real> &JxW = context.get_element_fe(_u_var)->get_JxW(); const std::vector<std::vector<libMesh::RealGradient> >& u_gradphi = context.get_element_fe(this->_u_var)->get_dphi(); const std::vector<std::vector<libMesh::RealTensor> >& u_hessphi = context.get_element_fe(this->_u_var)->get_d2phi(); const std::vector<std::vector<libMesh::RealGradient> >& p_dphi = context.get_element_fe(this->_p_var)->get_dphi(); // Get residuals libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(_u_var); // R_{u} libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(_v_var); // R_{v} libMesh::DenseSubVector<libMesh::Number> *Fw = NULL; if(this->_dim == 3) Fw = &context.get_elem_residual(this->_w_var); // R_{w} libMesh::DenseSubVector<libMesh::Number> &Fp = context.get_elem_residual(this->_p_var); // R_{p} // Now we will build the element Jacobian and residual. // Constructing the residual requires the solution and its // gradient from the previous timestep. This must be // calculated at each quadrature point by summing the // solution degree-of-freedom values by the appropriate // weight functions. unsigned int n_qpoints = context.get_element_qrule().n_points(); libMesh::FEBase* fe = context.get_element_fe(this->_u_var); for (unsigned int qp=0; qp != n_qpoints; qp++) { libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp ); libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp ); libMesh::RealGradient U( context.interior_value( this->_u_var, qp ), context.interior_value( this->_v_var, qp ) ); if( this->_dim == 3 ) { U(2) = context.interior_value( this->_w_var, qp ); } libMesh::Real tau_M = this->_stab_helper.compute_tau_momentum( context, qp, g, G, this->_rho, U, this->_mu, this->_is_steady ); // Compute the solution & its gradient at the old Newton iterate. libMesh::Number T; T = context.interior_value(_T_var, qp); libMesh::RealGradient residual = -_rho_ref*_beta_T*(T-_T_ref)*_g; // First, an i-loop over the velocity degrees of freedom. // We know that n_u_dofs == n_v_dofs so we can compute contributions // for both at the same time. for (unsigned int i=0; i != n_p_dofs; i++) { Fp(i) += tau_M*residual*p_dphi[i][qp]*JxW[qp]; } for (unsigned int i=0; i != n_u_dofs; i++) { Fu(i) += ( this->_rho*U*u_gradphi[i][qp] + this->_mu*( u_hessphi[i][qp](0,0) + u_hessphi[i][qp](1,1) + u_hessphi[i][qp](2,2) ) )*tau_M*residual(0)*JxW[qp]; Fv(i) += ( this->_rho*U*u_gradphi[i][qp] + this->_mu*( u_hessphi[i][qp](0,0) + u_hessphi[i][qp](1,1) + u_hessphi[i][qp](2,2) ) )*tau_M*residual(1)*JxW[qp]; if (_dim == 3) { (*Fw)(i) += ( this->_rho*U*u_gradphi[i][qp] + this->_mu*( u_hessphi[i][qp](0,0) + u_hessphi[i][qp](1,1) + u_hessphi[i][qp](2,2) ) )*tau_M*residual(2)*JxW[qp]; } if (compute_jacobian) { libmesh_not_implemented(); } // End compute_jacobian check } // End i dof loop } // End quadrature loop #ifdef GRINS_USE_GRVY_TIMERS this->_timer->EndTimer("BoussinesqBuoyancyAdjointStabilization::element_time_derivative"); #endif return; } } // namespace GRINS <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include <QtGui/qevent.h> #include <QtGui/qmenu.h> #include <QtGui/qaction.h> #include <QInputDialog> #include <QDebug> #include <private/qdeclarativedebug_p.h> #include "objecttree.h" #include "inspectorcontext.h" namespace Qml { namespace Internal { ObjectTree::ObjectTree(QDeclarativeEngineDebug *client, QWidget *parent) : QTreeWidget(parent), m_client(client), m_query(0) { setFrameStyle(QFrame::NoFrame); setHeaderHidden(true); setMinimumWidth(250); setExpandsOnDoubleClick(false); connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), SLOT(currentItemChanged(QTreeWidgetItem *))); connect(this, SIGNAL(itemActivated(QTreeWidgetItem *, int)), SLOT(activated(QTreeWidgetItem *))); connect(this, SIGNAL(itemSelectionChanged()), SLOT(selectionChanged())); } void ObjectTree::setEngineDebug(QDeclarativeEngineDebug *client) { m_client = client; } void ObjectTree::selectionChanged() { if (selectedItems().isEmpty()) return; QTreeWidgetItem *item = selectedItems().first(); if (item) emit contextHelpIdChanged(InspectorContext::contextHelpIdForItem(item->text(0))); } void ObjectTree::reload(int objectDebugId) { if (!m_client) return; if (m_query) { delete m_query; m_query = 0; } m_query = m_client->queryObjectRecursive(QDeclarativeDebugObjectReference(objectDebugId), this); if (!m_query->isWaiting()) objectFetched(); else QObject::connect(m_query, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)), this, SLOT(objectFetched())); } void ObjectTree::setCurrentObject(int debugId) { QTreeWidgetItem *item = findItemByObjectId(debugId); if (item) { setCurrentItem(item); scrollToItem(item); item->setExpanded(true); } } void ObjectTree::objectFetched() { //dump(m_query->object(), 0); buildTree(m_query->object(), 0); setCurrentItem(topLevelItem(0)); delete m_query; m_query = 0; } void ObjectTree::currentItemChanged(QTreeWidgetItem *item) { if (!item) return; QDeclarativeDebugObjectReference obj = item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>(); if (obj.debugId() >= 0) emit currentObjectChanged(obj); } void ObjectTree::activated(QTreeWidgetItem *item) { if (!item) return; QDeclarativeDebugObjectReference obj = item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>(); if (obj.debugId() >= 0) emit activated(obj); } void ObjectTree::buildTree(const QDeclarativeDebugObjectReference &obj, QTreeWidgetItem *parent) { if (!parent) clear(); QTreeWidgetItem *item = parent ? new QTreeWidgetItem(parent) : new QTreeWidgetItem(this); if (obj.idString().isEmpty()) item->setText(0, obj.className()); else item->setText(0, obj.idString()); item->setData(0, Qt::UserRole, qVariantFromValue(obj)); if (parent && obj.contextDebugId() >= 0 && obj.contextDebugId() != parent->data(0, Qt::UserRole ).value<QDeclarativeDebugObjectReference>().contextDebugId()) { QDeclarativeDebugFileReference source = obj.source(); if (!source.url().isEmpty()) { QString toolTipString = QLatin1String("URL: ") + source.url().toString(); item->setToolTip(0, toolTipString); } item->setForeground(0, QColor("orange")); } else { item->setExpanded(true); } if (obj.contextDebugId() < 0) { item->setForeground(0, Qt::lightGray); } for (int ii = 0; ii < obj.children().count(); ++ii) buildTree(obj.children().at(ii), item); } void ObjectTree::dump(const QDeclarativeDebugContextReference &ctxt, int ind) { QByteArray indent(ind * 4, ' '); qWarning().nospace() << indent.constData() << ctxt.debugId() << " " << qPrintable(ctxt.name()); for (int ii = 0; ii < ctxt.contexts().count(); ++ii) dump(ctxt.contexts().at(ii), ind + 1); for (int ii = 0; ii < ctxt.objects().count(); ++ii) dump(ctxt.objects().at(ii), ind); } void ObjectTree::dump(const QDeclarativeDebugObjectReference &obj, int ind) { QByteArray indent(ind * 4, ' '); qWarning().nospace() << indent.constData() << qPrintable(obj.className()) << " " << qPrintable(obj.idString()) << " " << obj.debugId(); for (int ii = 0; ii < obj.children().count(); ++ii) dump(obj.children().at(ii), ind + 1); } QTreeWidgetItem *ObjectTree::findItemByObjectId(int debugId) const { for (int i=0; i<topLevelItemCount(); ++i) { QTreeWidgetItem *item = findItem(topLevelItem(i), debugId); if (item) return item; } return 0; } QTreeWidgetItem *ObjectTree::findItem(QTreeWidgetItem *item, int debugId) const { if (item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>().debugId() == debugId) return item; QTreeWidgetItem *child; for (int i=0; i<item->childCount(); ++i) { child = findItem(item->child(i), debugId); if (child) return child; } return 0; } void ObjectTree::mousePressEvent(QMouseEvent *me) { QTreeWidget::mousePressEvent(me); if (!currentItem()) return; if(me->button() == Qt::RightButton && me->type() == QEvent::MouseButtonPress) { QAction action(tr("Add watch..."), 0); QList<QAction *> actions; actions << &action; QDeclarativeDebugObjectReference obj = currentItem()->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>(); if (QMenu::exec(actions, me->globalPos())) { bool ok = false; QString watch = QInputDialog::getText(this, tr("Watch expression"), tr("Expression:"), QLineEdit::Normal, QString(), &ok); if (ok && !watch.isEmpty()) emit expressionWatchRequested(obj, watch); } } } } } <commit_msg>QmlInspector: Anonymous items' types displayed with special characters in object tree<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include <QtGui/qevent.h> #include <QtGui/qmenu.h> #include <QtGui/qaction.h> #include <QInputDialog> #include <QDebug> #include <private/qdeclarativedebug_p.h> #include "objecttree.h" #include "inspectorcontext.h" namespace Qml { namespace Internal { ObjectTree::ObjectTree(QDeclarativeEngineDebug *client, QWidget *parent) : QTreeWidget(parent), m_client(client), m_query(0) { setFrameStyle(QFrame::NoFrame); setHeaderHidden(true); setMinimumWidth(250); setExpandsOnDoubleClick(false); connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), SLOT(currentItemChanged(QTreeWidgetItem *))); connect(this, SIGNAL(itemActivated(QTreeWidgetItem *, int)), SLOT(activated(QTreeWidgetItem *))); connect(this, SIGNAL(itemSelectionChanged()), SLOT(selectionChanged())); } void ObjectTree::setEngineDebug(QDeclarativeEngineDebug *client) { m_client = client; } void ObjectTree::selectionChanged() { if (selectedItems().isEmpty()) return; QTreeWidgetItem *item = selectedItems().first(); if (item) emit contextHelpIdChanged(InspectorContext::contextHelpIdForItem(item->text(0))); } void ObjectTree::reload(int objectDebugId) { if (!m_client) return; if (m_query) { delete m_query; m_query = 0; } m_query = m_client->queryObjectRecursive(QDeclarativeDebugObjectReference(objectDebugId), this); if (!m_query->isWaiting()) objectFetched(); else QObject::connect(m_query, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)), this, SLOT(objectFetched())); } void ObjectTree::setCurrentObject(int debugId) { QTreeWidgetItem *item = findItemByObjectId(debugId); if (item) { setCurrentItem(item); scrollToItem(item); item->setExpanded(true); } } void ObjectTree::objectFetched() { //dump(m_query->object(), 0); buildTree(m_query->object(), 0); setCurrentItem(topLevelItem(0)); delete m_query; m_query = 0; } void ObjectTree::currentItemChanged(QTreeWidgetItem *item) { if (!item) return; QDeclarativeDebugObjectReference obj = item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>(); if (obj.debugId() >= 0) emit currentObjectChanged(obj); } void ObjectTree::activated(QTreeWidgetItem *item) { if (!item) return; QDeclarativeDebugObjectReference obj = item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>(); if (obj.debugId() >= 0) emit activated(obj); } void ObjectTree::buildTree(const QDeclarativeDebugObjectReference &obj, QTreeWidgetItem *parent) { if (!parent) clear(); QTreeWidgetItem *item = parent ? new QTreeWidgetItem(parent) : new QTreeWidgetItem(this); if (obj.idString().isEmpty()) item->setText(0, QLatin1String("<")+obj.className()+QLatin1String(">")); else item->setText(0, obj.idString()); item->setData(0, Qt::UserRole, qVariantFromValue(obj)); if (parent && obj.contextDebugId() >= 0 && obj.contextDebugId() != parent->data(0, Qt::UserRole ).value<QDeclarativeDebugObjectReference>().contextDebugId()) { QDeclarativeDebugFileReference source = obj.source(); if (!source.url().isEmpty()) { QString toolTipString = QLatin1String("URL: ") + source.url().toString(); item->setToolTip(0, toolTipString); } item->setForeground(0, QColor("orange")); } else { item->setExpanded(true); } if (obj.contextDebugId() < 0) { item->setForeground(0, Qt::lightGray); } for (int ii = 0; ii < obj.children().count(); ++ii) buildTree(obj.children().at(ii), item); } void ObjectTree::dump(const QDeclarativeDebugContextReference &ctxt, int ind) { QByteArray indent(ind * 4, ' '); qWarning().nospace() << indent.constData() << ctxt.debugId() << " " << qPrintable(ctxt.name()); for (int ii = 0; ii < ctxt.contexts().count(); ++ii) dump(ctxt.contexts().at(ii), ind + 1); for (int ii = 0; ii < ctxt.objects().count(); ++ii) dump(ctxt.objects().at(ii), ind); } void ObjectTree::dump(const QDeclarativeDebugObjectReference &obj, int ind) { QByteArray indent(ind * 4, ' '); qWarning().nospace() << indent.constData() << qPrintable(obj.className()) << " " << qPrintable(obj.idString()) << " " << obj.debugId(); for (int ii = 0; ii < obj.children().count(); ++ii) dump(obj.children().at(ii), ind + 1); } QTreeWidgetItem *ObjectTree::findItemByObjectId(int debugId) const { for (int i=0; i<topLevelItemCount(); ++i) { QTreeWidgetItem *item = findItem(topLevelItem(i), debugId); if (item) return item; } return 0; } QTreeWidgetItem *ObjectTree::findItem(QTreeWidgetItem *item, int debugId) const { if (item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>().debugId() == debugId) return item; QTreeWidgetItem *child; for (int i=0; i<item->childCount(); ++i) { child = findItem(item->child(i), debugId); if (child) return child; } return 0; } void ObjectTree::mousePressEvent(QMouseEvent *me) { QTreeWidget::mousePressEvent(me); if (!currentItem()) return; if(me->button() == Qt::RightButton && me->type() == QEvent::MouseButtonPress) { QAction action(tr("Add watch..."), 0); QList<QAction *> actions; actions << &action; QDeclarativeDebugObjectReference obj = currentItem()->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>(); if (QMenu::exec(actions, me->globalPos())) { bool ok = false; QString watch = QInputDialog::getText(this, tr("Watch expression"), tr("Expression:"), QLineEdit::Normal, QString(), &ok); if (ok && !watch.isEmpty()) emit expressionWatchRequested(obj, watch); } } } } } <|endoftext|>
<commit_before>/* * 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 3 of the License, or * (at your option) any later version. * * Written (W) 2013 Heiko Strathmann */ #include <shogun/statistics/MMDKernelSelectionMedian.h> #include <shogun/statistics/LinearTimeMMD.h> #include <shogun/features/streaming/StreamingFeatures.h> #include <shogun/statistics/QuadraticTimeMMD.h> #include <shogun/distance/EuclideanDistance.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/kernel/CombinedKernel.h> #include <shogun/mathematics/Statistics.h> using namespace shogun; CMMDKernelSelectionMedian::CMMDKernelSelectionMedian() : CMMDKernelSelection() { init(); } CMMDKernelSelectionMedian::CMMDKernelSelectionMedian( CKernelTwoSampleTestStatistic* mmd, index_t num_data_distance) : CMMDKernelSelection(mmd) { /* assert that a combined kernel is used */ CKernel* kernel=mmd->get_kernel(); CFeatures* lhs=kernel->get_lhs(); CFeatures* rhs=kernel->get_rhs(); REQUIRE(kernel, "%s::%s(): No kernel set!\n", get_name(), get_name()); REQUIRE(kernel->get_kernel_type()==K_COMBINED, "%s::%s(): Requires " "CombinedKernel as kernel. Yours is %s", get_name(), get_name(), kernel->get_name()); /* assert that all subkernels are Gaussian kernels */ CCombinedKernel* combined=(CCombinedKernel*)kernel; CKernel* subkernel=combined->get_first_kernel(); index_t i=0; while (subkernel) { REQUIRE(kernel, "%s::%s(): Subkernel (i) of current kernel is not" " of type GaussianKernel\n", get_name(), get_name(), i); SG_UNREF(subkernel); subkernel=combined->get_next_kernel(); i++; } /* assert 64 bit dense features since EuclideanDistance can only handle * those */ if (m_mmd->get_statistic_type()==S_QUADRATIC_TIME_MMD) { CFeatures* features=((CQuadraticTimeMMD*)m_mmd)->get_p_and_q(); REQUIRE(features->get_feature_class()==C_DENSE && features->get_feature_type()==F_DREAL, "%s::select_kernel(): " "Only 64 bit float dense features allowed, these are \"%s\"" " and of type %d\n", get_name(), features->get_name(), features->get_feature_type()); SG_UNREF(features); } else if (m_mmd->get_statistic_type()==S_LINEAR_TIME_MMD) { CStreamingFeatures* p=((CLinearTimeMMD*)m_mmd)->get_streaming_p(); CStreamingFeatures* q=((CLinearTimeMMD*)m_mmd)->get_streaming_q(); REQUIRE(p->get_feature_class()==C_STREAMING_DENSE && p->get_feature_type()==F_DREAL, "%s::select_kernel(): " "Only 64 bit float streaming dense features allowed, these (p) " "are \"%s\" and of type %d\n", get_name(), p->get_name(), p->get_feature_type()); REQUIRE(p->get_feature_class()==C_STREAMING_DENSE && p->get_feature_type()==F_DREAL, "%s::select_kernel(): " "Only 64 bit float streaming dense features allowed, these (q) " "are \"%s\" and of type %d\n", get_name(), q->get_name(), q->get_feature_type()); } SG_UNREF(kernel); SG_UNREF(lhs); SG_UNREF(rhs); init(); m_num_data_distance=num_data_distance; } CMMDKernelSelectionMedian::~CMMDKernelSelectionMedian() { } void CMMDKernelSelectionMedian::init() { SG_WARNING("register params!\n") /* this is a sensible value */ m_num_data_distance=1000; } SGVector<float64_t> CMMDKernelSelectionMedian::compute_measures() { SG_ERROR("%s::compute_measures(): Not implemented. Use select_kernel() " "method!\n", get_name()); return SGVector<float64_t>(); } CKernel* CMMDKernelSelectionMedian::select_kernel() { /* number of data for distace */ index_t num_data=CMath::min(m_num_data_distance, m_mmd->get_m()); SGMatrix<float64_t> dists; /* compute all pairwise distances, depends which mmd statistic is used */ if (m_mmd->get_statistic_type()==S_QUADRATIC_TIME_MMD) { /* fixed data, create merged copy of a random subset */ /* create vector with that correspond to the num_data first points of * each distribution, remember data is stored jointly */ SGVector<index_t> subset(num_data*2); index_t m=m_mmd->get_m(); for (index_t i=0; i<num_data; ++i) { /* num_data samples from each half of joint sample */ subset[i]=i; subset[i+num_data]=i+m; } /* add subset and compute pairwise distances */ CQuadraticTimeMMD* quad_mmd=(CQuadraticTimeMMD*)m_mmd; CFeatures* features=quad_mmd->get_p_and_q(); features->add_subset(subset); /* cast is safe, see constructor */ CDenseFeatures<float64_t>* dense_features= (CDenseFeatures<float64_t>*) features; dense_features->get_feature_matrix().display_matrix("dense"); CEuclideanDistance* distance=new CEuclideanDistance(dense_features, dense_features); dists=distance->get_distance_matrix(); features->remove_subset(); SG_UNREF(distance); SG_UNREF(features); } else if (m_mmd->get_statistic_type()==S_LINEAR_TIME_MMD) { /* just stream the desired number of points */ CLinearTimeMMD* linear_mmd=(CLinearTimeMMD*)m_mmd; CStreamingFeatures* p=linear_mmd->get_streaming_p(); CStreamingFeatures* q=linear_mmd->get_streaming_q(); /* cast is safe, see constructor */ CDenseFeatures<float64_t>* p_streamed=(CDenseFeatures<float64_t>*) p->get_streamed_features(num_data); CDenseFeatures<float64_t>* q_streamed=(CDenseFeatures<float64_t>*) q->get_streamed_features(num_data); /* for safety */ SG_REF(p_streamed); SG_REF(q_streamed); /* create merged feature object */ CDenseFeatures<float64_t>* merged=(CDenseFeatures<float64_t>*) p_streamed->create_merged_copy(q_streamed); /* compute pairwise distances */ CEuclideanDistance* distance=new CEuclideanDistance(merged, merged); dists=distance->get_distance_matrix(); /* clean up */ SG_UNREF(distance); SG_REF(p_streamed); SG_REF(q_streamed); SG_UNREF(p); SG_UNREF(q); } /* create a vector where the zeros have been removed, use upper triangle * only since distances are symmetric */ SGVector<float64_t> dist_vec(dists.num_rows*(dists.num_rows-1)/2); index_t write_idx=0; for (index_t i=0; i<dists.num_rows; ++i) { for (index_t j=i+1; j<dists.num_rows; ++j) dist_vec[write_idx++]=dists(i,j); } /* now we have distance matrix, compute median, allow to modify matrix */ float64_t median_distance=CStatistics::median(dist_vec, true); SG_DEBUG("median_distance: %f\n", median_distance); /* shogun has no square and factor two in its kernel width, MATLAB does * median_width = sqrt(0.5*median_distance), we do this */ float64_t shogun_sigma=median_distance; SG_DEBUG("kernel width (shogun): %f\n", shogun_sigma); /* now of all kernels, find the one which has its width closest * Cast is safe due to constructor of MMDKernelSelection class */ CCombinedKernel* combined=(CCombinedKernel*)m_mmd->get_kernel(); CKernel* current=combined->get_first_kernel(); float64_t min_distance=CMath::MAX_REAL_NUMBER; CKernel* min_kernel=NULL; float64_t distance; for (index_t i=0; i<combined->get_num_subkernels(); ++i) { REQUIRE(current->get_kernel_type()==K_GAUSSIAN, "%s::select_kernel(): " "%d-th kernel is not a Gaussian but \"%s\"!\n", get_name(), i, current->get_name()); /* check if width is closer to median width */ distance=CMath::abs(((CGaussianKernel*)current)->get_width()- shogun_sigma); if (distance<min_distance) { min_distance=distance; min_kernel=current; } /* next kernel */ SG_UNREF(current); current=combined->get_next_kernel(); } SG_UNREF(combined); /* returned referenced kernel */ SG_REF(min_kernel); return min_kernel; } <commit_msg>fixed a memory leak<commit_after>/* * 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 3 of the License, or * (at your option) any later version. * * Written (W) 2013 Heiko Strathmann */ #include <shogun/statistics/MMDKernelSelectionMedian.h> #include <shogun/statistics/LinearTimeMMD.h> #include <shogun/features/streaming/StreamingFeatures.h> #include <shogun/statistics/QuadraticTimeMMD.h> #include <shogun/distance/EuclideanDistance.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/kernel/CombinedKernel.h> #include <shogun/mathematics/Statistics.h> using namespace shogun; CMMDKernelSelectionMedian::CMMDKernelSelectionMedian() : CMMDKernelSelection() { init(); } CMMDKernelSelectionMedian::CMMDKernelSelectionMedian( CKernelTwoSampleTestStatistic* mmd, index_t num_data_distance) : CMMDKernelSelection(mmd) { /* assert that a combined kernel is used */ CKernel* kernel=mmd->get_kernel(); CFeatures* lhs=kernel->get_lhs(); CFeatures* rhs=kernel->get_rhs(); REQUIRE(kernel, "%s::%s(): No kernel set!\n", get_name(), get_name()); REQUIRE(kernel->get_kernel_type()==K_COMBINED, "%s::%s(): Requires " "CombinedKernel as kernel. Yours is %s", get_name(), get_name(), kernel->get_name()); /* assert that all subkernels are Gaussian kernels */ CCombinedKernel* combined=(CCombinedKernel*)kernel; CKernel* subkernel=combined->get_first_kernel(); index_t i=0; while (subkernel) { REQUIRE(kernel, "%s::%s(): Subkernel (i) of current kernel is not" " of type GaussianKernel\n", get_name(), get_name(), i); SG_UNREF(subkernel); subkernel=combined->get_next_kernel(); i++; } /* assert 64 bit dense features since EuclideanDistance can only handle * those */ if (m_mmd->get_statistic_type()==S_QUADRATIC_TIME_MMD) { CFeatures* features=((CQuadraticTimeMMD*)m_mmd)->get_p_and_q(); REQUIRE(features->get_feature_class()==C_DENSE && features->get_feature_type()==F_DREAL, "%s::select_kernel(): " "Only 64 bit float dense features allowed, these are \"%s\"" " and of type %d\n", get_name(), features->get_name(), features->get_feature_type()); SG_UNREF(features); } else if (m_mmd->get_statistic_type()==S_LINEAR_TIME_MMD) { CStreamingFeatures* p=((CLinearTimeMMD*)m_mmd)->get_streaming_p(); CStreamingFeatures* q=((CLinearTimeMMD*)m_mmd)->get_streaming_q(); REQUIRE(p->get_feature_class()==C_STREAMING_DENSE && p->get_feature_type()==F_DREAL, "%s::select_kernel(): " "Only 64 bit float streaming dense features allowed, these (p) " "are \"%s\" and of type %d\n", get_name(), p->get_name(), p->get_feature_type()); REQUIRE(p->get_feature_class()==C_STREAMING_DENSE && p->get_feature_type()==F_DREAL, "%s::select_kernel(): " "Only 64 bit float streaming dense features allowed, these (q) " "are \"%s\" and of type %d\n", get_name(), q->get_name(), q->get_feature_type()); SG_UNREF(p); SG_UNREF(q); } SG_UNREF(kernel); SG_UNREF(lhs); SG_UNREF(rhs); init(); m_num_data_distance=num_data_distance; } CMMDKernelSelectionMedian::~CMMDKernelSelectionMedian() { } void CMMDKernelSelectionMedian::init() { SG_WARNING("register params!\n") /* this is a sensible value */ m_num_data_distance=1000; } SGVector<float64_t> CMMDKernelSelectionMedian::compute_measures() { SG_ERROR("%s::compute_measures(): Not implemented. Use select_kernel() " "method!\n", get_name()); return SGVector<float64_t>(); } CKernel* CMMDKernelSelectionMedian::select_kernel() { /* number of data for distace */ index_t num_data=CMath::min(m_num_data_distance, m_mmd->get_m()); SGMatrix<float64_t> dists; /* compute all pairwise distances, depends which mmd statistic is used */ if (m_mmd->get_statistic_type()==S_QUADRATIC_TIME_MMD) { /* fixed data, create merged copy of a random subset */ /* create vector with that correspond to the num_data first points of * each distribution, remember data is stored jointly */ SGVector<index_t> subset(num_data*2); index_t m=m_mmd->get_m(); for (index_t i=0; i<num_data; ++i) { /* num_data samples from each half of joint sample */ subset[i]=i; subset[i+num_data]=i+m; } /* add subset and compute pairwise distances */ CQuadraticTimeMMD* quad_mmd=(CQuadraticTimeMMD*)m_mmd; CFeatures* features=quad_mmd->get_p_and_q(); features->add_subset(subset); /* cast is safe, see constructor */ CDenseFeatures<float64_t>* dense_features= (CDenseFeatures<float64_t>*) features; dense_features->get_feature_matrix().display_matrix("dense"); CEuclideanDistance* distance=new CEuclideanDistance(dense_features, dense_features); dists=distance->get_distance_matrix(); features->remove_subset(); SG_UNREF(distance); SG_UNREF(features); } else if (m_mmd->get_statistic_type()==S_LINEAR_TIME_MMD) { /* just stream the desired number of points */ CLinearTimeMMD* linear_mmd=(CLinearTimeMMD*)m_mmd; CStreamingFeatures* p=linear_mmd->get_streaming_p(); CStreamingFeatures* q=linear_mmd->get_streaming_q(); /* cast is safe, see constructor */ CDenseFeatures<float64_t>* p_streamed=(CDenseFeatures<float64_t>*) p->get_streamed_features(num_data); CDenseFeatures<float64_t>* q_streamed=(CDenseFeatures<float64_t>*) q->get_streamed_features(num_data); /* for safety */ SG_REF(p_streamed); SG_REF(q_streamed); /* create merged feature object */ CDenseFeatures<float64_t>* merged=(CDenseFeatures<float64_t>*) p_streamed->create_merged_copy(q_streamed); /* compute pairwise distances */ CEuclideanDistance* distance=new CEuclideanDistance(merged, merged); dists=distance->get_distance_matrix(); /* clean up */ SG_UNREF(distance); SG_UNREF(p_streamed); SG_UNREF(q_streamed); SG_UNREF(p); SG_UNREF(q); } /* create a vector where the zeros have been removed, use upper triangle * only since distances are symmetric */ SGVector<float64_t> dist_vec(dists.num_rows*(dists.num_rows-1)/2); index_t write_idx=0; for (index_t i=0; i<dists.num_rows; ++i) { for (index_t j=i+1; j<dists.num_rows; ++j) dist_vec[write_idx++]=dists(i,j); } /* now we have distance matrix, compute median, allow to modify matrix */ float64_t median_distance=CStatistics::median(dist_vec, true); SG_DEBUG("median_distance: %f\n", median_distance); /* shogun has no square and factor two in its kernel width, MATLAB does * median_width = sqrt(0.5*median_distance), we do this */ float64_t shogun_sigma=median_distance; SG_DEBUG("kernel width (shogun): %f\n", shogun_sigma); /* now of all kernels, find the one which has its width closest * Cast is safe due to constructor of MMDKernelSelection class */ CCombinedKernel* combined=(CCombinedKernel*)m_mmd->get_kernel(); CKernel* current=combined->get_first_kernel(); float64_t min_distance=CMath::MAX_REAL_NUMBER; CKernel* min_kernel=NULL; float64_t distance; for (index_t i=0; i<combined->get_num_subkernels(); ++i) { REQUIRE(current->get_kernel_type()==K_GAUSSIAN, "%s::select_kernel(): " "%d-th kernel is not a Gaussian but \"%s\"!\n", get_name(), i, current->get_name()); /* check if width is closer to median width */ distance=CMath::abs(((CGaussianKernel*)current)->get_width()- shogun_sigma); if (distance<min_distance) { min_distance=distance; min_kernel=current; } /* next kernel */ SG_UNREF(current); current=combined->get_next_kernel(); } SG_UNREF(combined); /* returned referenced kernel */ SG_REF(min_kernel); return min_kernel; } <|endoftext|>
<commit_before>#include "entity_validator_ui.h" #include "entity_list.h" #include "halley/editor_extensions/entity_validator.h" using namespace Halley; EntityValidatorUI::EntityValidatorUI(String id, UIFactory& factory) : UIWidget(std::move(id), {}, UISizer()) , factory(factory) { factory.loadUI(*this, "ui/halley/entity_validator"); setActive(false); } void EntityValidatorUI::onMakeUI() { getWidgetAs<UIImage>("capsule")->addBehaviour(std::make_shared<UIPulseSpriteBehaviour>(Colour4f(1, 0, 0), 2.0, 1.0)); } void EntityValidatorUI::setValidator(EntityValidator& v) { validator = &v; refresh(); } void EntityValidatorUI::setEntity(EntityData& e, IEntityEditor& editor, Resources& resources) { curEntity = &e; entityEditor = &editor; gameResources = &resources; isPrefab = !curEntity->getPrefab().isEmpty() && gameResources->exists<Prefab>(curEntity->getPrefab()); if (isPrefab) { const auto prefab = gameResources->get<Prefab>(curEntity->getPrefab()); curEntityInstance = prefab->getEntityData().instantiateWithAsCopy(*curEntity); } refresh(); } void EntityValidatorUI::refresh() { if (!curEntity || !validator) { return; } std::vector<IEntityValidator::Result> result; if (isPrefab) { result = validator->validateEntity(curEntityInstance, true); } else { result = validator->validateEntity(*curEntity, false); } if (result != curResultSet) { curResultSet = std::move(result); setActive(!curResultSet.empty()); auto parent = getWidget("validationFields"); parent->clear(); bool first = true; for (const auto& curResult: curResultSet) { if (!first) { auto col = factory.getColourScheme()->getColour("taskError"); parent->add(std::make_shared<UIImage>(Sprite().setImage(factory.getResources(), "halley_ui/ui_separator.png").setColour(col)), 0, Vector4f(0, 4, 0, 4)); } first = false; auto label = std::make_shared<UILabel>("", factory.getStyle("labelLight"), curResult.errorMessage); label->setMaxWidth(300.0f); parent->add(label); for (const auto& action: curResult.suggestedActions) { if (validator->canApplyAction(*entityEditor, *curEntity, action.actionData)) { auto button = std::make_shared<UIButton>("action", factory.getStyle("buttonThin"), action.label); button->setHandle(UIEventType::ButtonClicked, [this, actionData = ConfigNode(action.actionData)] (const UIEvent& event) { Concurrent::execute(Executors::getMainThread(), [=] () { validator->applyAction(*entityEditor, *curEntity, actionData); entityEditor->reloadEntity(); }); }); parent->add(button); } } } } } EntityValidatorListUI::EntityValidatorListUI(String id, UIFactory& factory) : UIWidget(std::move(id), {}, UISizer()) , factory(factory) { factory.loadUI(*this, "ui/halley/entity_validator_list"); setActive(false); } void EntityValidatorListUI::onMakeUI() { setHandle(UIEventType::ButtonClicked, "prev", [=] (const UIEvent& event) { move(-1); }); setHandle(UIEventType::ButtonClicked, "next", [=] (const UIEvent& event) { move(1); }); getWidgetAs<UIImage>("capsule")->addBehaviour(std::make_shared<UIPulseSpriteBehaviour>(Colour4f(1, 0, 0), 2.0, 1.0)); description = getWidgetAs<UILabel>("description"); } void EntityValidatorListUI::update(Time t, bool moved) { const auto entityListStrong = entityList.lock(); if (entityListStrong) { const auto& list = entityListStrong->getList(); const auto curSel = list.getSelectedOption(); const auto iter = std::find(invalidEntities.begin(), invalidEntities.end(), curSel); const int curPos = iter != invalidEntities.end() ? static_cast<int>(iter - invalidEntities.begin() + 1) : 0; description->setText(LocalisedString::fromHardcodedString("Entities have validation errors [" + (curPos > 0 ? toString(curPos) : "-") + "/" + toString(invalidEntities.size()) + "]")); } } void EntityValidatorListUI::setList(std::weak_ptr<EntityList> list) { entityList = list; } void EntityValidatorListUI::setInvalidEntities(std::vector<int> entities) { invalidEntities = std::move(entities); setActive(!invalidEntities.empty()); } void EntityValidatorListUI::move(int delta) { auto& list = entityList.lock()->getList(); const auto curSel = list.getSelectedOption(); int newSel = curSel; if (delta == 1) { newSel = invalidEntities.front(); for (int e: invalidEntities) { if (e > curSel) { newSel = e; break; } } } else if (delta == -1) { newSel = invalidEntities.back(); for (int i = int(invalidEntities.size()); --i >= 0;) { int e = invalidEntities[i]; if (e < curSel) { newSel = e; break; } } } if (newSel != curSel) { list.setSelectedOption(newSel); } } <commit_msg>Tweak colour<commit_after>#include "entity_validator_ui.h" #include "entity_list.h" #include "halley/editor_extensions/entity_validator.h" using namespace Halley; EntityValidatorUI::EntityValidatorUI(String id, UIFactory& factory) : UIWidget(std::move(id), {}, UISizer()) , factory(factory) { factory.loadUI(*this, "ui/halley/entity_validator"); setActive(false); } void EntityValidatorUI::onMakeUI() { getWidgetAs<UIImage>("capsule")->addBehaviour(std::make_shared<UIPulseSpriteBehaviour>(Colour4f(1, 0, 0), 2.0, 1.0)); } void EntityValidatorUI::setValidator(EntityValidator& v) { validator = &v; refresh(); } void EntityValidatorUI::setEntity(EntityData& e, IEntityEditor& editor, Resources& resources) { curEntity = &e; entityEditor = &editor; gameResources = &resources; isPrefab = !curEntity->getPrefab().isEmpty() && gameResources->exists<Prefab>(curEntity->getPrefab()); if (isPrefab) { const auto prefab = gameResources->get<Prefab>(curEntity->getPrefab()); curEntityInstance = prefab->getEntityData().instantiateWithAsCopy(*curEntity); } refresh(); } void EntityValidatorUI::refresh() { if (!curEntity || !validator) { return; } std::vector<IEntityValidator::Result> result; if (isPrefab) { result = validator->validateEntity(curEntityInstance, true); } else { result = validator->validateEntity(*curEntity, false); } if (result != curResultSet) { curResultSet = std::move(result); setActive(!curResultSet.empty()); auto parent = getWidget("validationFields"); parent->clear(); bool first = true; for (const auto& curResult: curResultSet) { if (!first) { auto col = factory.getColourScheme()->getColour("ui_text"); parent->add(std::make_shared<UIImage>(Sprite().setImage(factory.getResources(), "halley_ui/ui_separator.png").setColour(col)), 0, Vector4f(0, 4, 0, 4)); } first = false; auto label = std::make_shared<UILabel>("", factory.getStyle("labelLight"), curResult.errorMessage); label->setMaxWidth(300.0f); parent->add(label); for (const auto& action: curResult.suggestedActions) { if (validator->canApplyAction(*entityEditor, *curEntity, action.actionData)) { auto button = std::make_shared<UIButton>("action", factory.getStyle("buttonThin"), action.label); button->setHandle(UIEventType::ButtonClicked, [this, actionData = ConfigNode(action.actionData)] (const UIEvent& event) { Concurrent::execute(Executors::getMainThread(), [=] () { validator->applyAction(*entityEditor, *curEntity, actionData); entityEditor->reloadEntity(); }); }); parent->add(button); } } } } } EntityValidatorListUI::EntityValidatorListUI(String id, UIFactory& factory) : UIWidget(std::move(id), {}, UISizer()) , factory(factory) { factory.loadUI(*this, "ui/halley/entity_validator_list"); setActive(false); } void EntityValidatorListUI::onMakeUI() { setHandle(UIEventType::ButtonClicked, "prev", [=] (const UIEvent& event) { move(-1); }); setHandle(UIEventType::ButtonClicked, "next", [=] (const UIEvent& event) { move(1); }); getWidgetAs<UIImage>("capsule")->addBehaviour(std::make_shared<UIPulseSpriteBehaviour>(Colour4f(1, 0, 0), 2.0, 1.0)); description = getWidgetAs<UILabel>("description"); } void EntityValidatorListUI::update(Time t, bool moved) { const auto entityListStrong = entityList.lock(); if (entityListStrong) { const auto& list = entityListStrong->getList(); const auto curSel = list.getSelectedOption(); const auto iter = std::find(invalidEntities.begin(), invalidEntities.end(), curSel); const int curPos = iter != invalidEntities.end() ? static_cast<int>(iter - invalidEntities.begin() + 1) : 0; description->setText(LocalisedString::fromHardcodedString("Entities have validation errors [" + (curPos > 0 ? toString(curPos) : "-") + "/" + toString(invalidEntities.size()) + "]")); } } void EntityValidatorListUI::setList(std::weak_ptr<EntityList> list) { entityList = list; } void EntityValidatorListUI::setInvalidEntities(std::vector<int> entities) { invalidEntities = std::move(entities); setActive(!invalidEntities.empty()); } void EntityValidatorListUI::move(int delta) { auto& list = entityList.lock()->getList(); const auto curSel = list.getSelectedOption(); int newSel = curSel; if (delta == 1) { newSel = invalidEntities.front(); for (int e: invalidEntities) { if (e > curSel) { newSel = e; break; } } } else if (delta == -1) { newSel = invalidEntities.back(); for (int i = int(invalidEntities.size()); --i >= 0;) { int e = invalidEntities[i]; if (e < curSel) { newSel = e; break; } } } if (newSel != curSel) { list.setSelectedOption(newSel); } } <|endoftext|>
<commit_before>/* Copyright libCellML Contributors 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 "libcellml/component.h" #include "libcellml/importsource.h" #include "libcellml/model.h" #include "libcellml/parser.h" #include "libcellml/variable.h" #include "libcellml/units.h" #include <algorithm> #include <fstream> #include <map> #include <sstream> #include <stack> #include <utility> #include <vector> namespace libcellml { /** * @brief The Model::ModelImpl struct. * * This struct is the private implementation struct for the Model class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct Model::ModelImpl { std::vector<UnitsPtr>::iterator findUnits(const std::string &name); std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units); std::vector<UnitsPtr> mUnits; }; std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr &u) -> bool { return u->getName() == name; }); } std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr &u) -> bool { return u == units; }); } Model::Model() #ifndef SWIG : std::enable_shared_from_this<Model>() , mPimpl(new ModelImpl()) #else : mPimpl(new ModelImpl()) #endif { } Model::~Model() { delete mPimpl; } Model::Model(const Model &rhs) : ComponentEntity(rhs) #ifndef SWIG , std::enable_shared_from_this<Model>() #endif , mPimpl(new ModelImpl()) { mPimpl->mUnits = rhs.mPimpl->mUnits; } Model::Model(Model &&rhs) noexcept : ComponentEntity(std::move(rhs)) #ifndef SWIG , std::enable_shared_from_this<Model>() #endif ,mPimpl(rhs.mPimpl) { rhs.mPimpl = nullptr; } Model& Model::operator=(Model rhs) { ComponentEntity::operator= (rhs); rhs.swap(*this); return *this; } void Model::swap(Model &rhs) { std::swap(this->mPimpl, rhs.mPimpl); } void Model::doAddComponent(const ComponentPtr &component) { // Check for cycles. if (!hasParent(component.get())) { component->setParent(this); ComponentEntity::doAddComponent(component); } } void Model::addUnits(const UnitsPtr &units) { mPimpl->mUnits.push_back(units); } bool Model::removeUnits(size_t index) { bool status = false; if (index < mPimpl->mUnits.size()) { mPimpl->mUnits.erase(mPimpl->mUnits.begin() + index); status = true; } return status; } bool Model::removeUnits(const std::string &name) { bool status = false; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { mPimpl->mUnits.erase(result); status = true; } return status; } bool Model::removeUnits(const UnitsPtr &units) { bool status = false; auto result = mPimpl->findUnits(units); if (result != mPimpl->mUnits.end()) { mPimpl->mUnits.erase(result); status = true; } return status; } void Model::removeAllUnits() { mPimpl->mUnits.clear(); } bool Model::hasUnits(const std::string &name) const { return mPimpl->findUnits(name) != mPimpl->mUnits.end(); } bool Model::hasUnits(const UnitsPtr &units) const { return mPimpl->findUnits(units) != mPimpl->mUnits.end(); } UnitsPtr Model::getUnits(size_t index) const { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); } return units; } UnitsPtr Model::getUnits(const std::string &name) const { UnitsPtr units = nullptr; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { units = *result; } return units; } UnitsPtr Model::takeUnits(size_t index) { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); removeUnits(index); units->clearParent(); } return units; } UnitsPtr Model::takeUnits(const std::string &name) { return takeUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin()); } bool Model::replaceUnits(size_t index, const UnitsPtr &units) { bool status = false; if (removeUnits(index)) { mPimpl->mUnits.insert(mPimpl->mUnits.begin() + index, units); status = true; } return status; } bool Model::replaceUnits(const std::string &name, const UnitsPtr &units) { return replaceUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin(), units); } bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits) { return replaceUnits(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin(), newUnits); } size_t Model::unitsCount() const { return mPimpl->mUnits.size(); } /** * @brief Resolve the path of the given filename using the given base. * * Resolves the full path to the given @p filename using the @p base. * * This function is only intended to work with local files. It may not * work with bases that use the 'file://' prefix. * * @param filename The @c std::string relative path from the base path. * @param base The @c std::string location on local disk for determining the full path from. * @return The full path from the @p base location to the @p filename */ std::string resolvePath(const std::string &filename, const std::string &base) { // We can be naive here as we know what we are dealing with std::string path = base.substr(0, base.find_last_of('/')+1) + filename; return path; } void resolveImport(const ImportedEntityPtr &importedEntity, const std::string &baseFile) { if (importedEntity->isImport()) { ImportSourcePtr importSource = importedEntity->getImportSource(); if (!importSource->hasModel()) { std::string url = resolvePath(importSource->getUrl(), baseFile); std::ifstream file(url); if (file.good()) { std::stringstream buffer; buffer << file.rdbuf(); Parser parser; ModelPtr model = parser.parseModel(buffer.str()); importSource->setModel(model); model->resolveImports(url); } } } } void resolveComponentImports(const ComponentEntityPtr &parentComponentEntity, const std::string &baseFile) { for (size_t n = 0; n < parentComponentEntity->componentCount(); ++n) { ComponentPtr component = parentComponentEntity->getComponent(n); if (component->isImport()) { resolveImport(component, baseFile); } else { resolveComponentImports(component, baseFile); } } } void Model::resolveImports(const std::string &baseFile) { for (size_t n = 0; n < unitsCount(); ++n) { UnitsPtr units = getUnits(n); resolveImport(units, baseFile); } resolveComponentImports(shared_from_this(), baseFile); } bool isUnresolvedImport(const ImportedEntityPtr &importedEntity) { bool unresolvedImport = false; if (importedEntity->isImport()) { ImportSourcePtr importedSource = importedEntity->getImportSource(); if (!importedSource->hasModel()) { unresolvedImport = true; } } return unresolvedImport; } bool hasUnresolvedComponentImports(const ComponentEntityPtr &parentComponentEntity); bool doHasUnresolvedComponentImports(const ComponentPtr &component) { bool unresolvedImports = false; if (component->isImport()) { unresolvedImports = isUnresolvedImport(component); if (!unresolvedImports) { // Check that the imported component can import all it needs from its model. ImportSourcePtr importedSource = component->getImportSource(); if (importedSource->hasModel()) { ModelPtr importedModel = importedSource->getModel(); ComponentPtr importedComponent = importedModel->getComponent(component->getImportReference()); unresolvedImports = doHasUnresolvedComponentImports(importedComponent); } } } else { unresolvedImports = hasUnresolvedComponentImports(component); } return unresolvedImports; } bool hasUnresolvedComponentImports(const ComponentEntityPtr &parentComponentEntity) { bool unresolvedImports = false; for (size_t n = 0; n < parentComponentEntity->componentCount() && !unresolvedImports; ++n) { ComponentPtr component = parentComponentEntity->getComponent(n); unresolvedImports = doHasUnresolvedComponentImports(component); } return unresolvedImports; } bool Model::hasUnresolvedImports() { bool unresolvedImports = false; for (size_t n = 0; n < unitsCount() && !unresolvedImports; ++n) { UnitsPtr units = getUnits(n); unresolvedImports = isUnresolvedImport(units); } if (!unresolvedImports) { unresolvedImports = hasUnresolvedComponentImports(shared_from_this()); } return unresolvedImports; } } <commit_msg>Make Clang-Tidy happy.<commit_after>/* Copyright libCellML Contributors 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 "libcellml/component.h" #include "libcellml/importsource.h" #include "libcellml/model.h" #include "libcellml/parser.h" #include "libcellml/variable.h" #include "libcellml/units.h" #include <algorithm> #include <fstream> #include <map> #include <sstream> #include <stack> #include <utility> #include <vector> namespace libcellml { /** * @brief The Model::ModelImpl struct. * * This struct is the private implementation struct for the Model class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct Model::ModelImpl { std::vector<UnitsPtr>::iterator findUnits(const std::string &name); std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units); std::vector<UnitsPtr> mUnits; }; std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr &u) -> bool { return u->getName() == name; }); } std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr &u) -> bool { return u == units; }); } Model::Model() : mPimpl(new ModelImpl()) { } Model::~Model() { delete mPimpl; } Model::Model(const Model &rhs) : ComponentEntity(rhs) #ifndef SWIG , std::enable_shared_from_this<Model>(rhs) #endif , mPimpl(new ModelImpl()) { mPimpl->mUnits = rhs.mPimpl->mUnits; } Model::Model(Model &&rhs) noexcept : ComponentEntity(std::move(rhs)) , mPimpl(rhs.mPimpl) { rhs.mPimpl = nullptr; } Model& Model::operator=(Model rhs) { ComponentEntity::operator= (rhs); rhs.swap(*this); return *this; } void Model::swap(Model &rhs) { std::swap(this->mPimpl, rhs.mPimpl); } void Model::doAddComponent(const ComponentPtr &component) { // Check for cycles. if (!hasParent(component.get())) { component->setParent(this); ComponentEntity::doAddComponent(component); } } void Model::addUnits(const UnitsPtr &units) { mPimpl->mUnits.push_back(units); } bool Model::removeUnits(size_t index) { bool status = false; if (index < mPimpl->mUnits.size()) { mPimpl->mUnits.erase(mPimpl->mUnits.begin() + index); status = true; } return status; } bool Model::removeUnits(const std::string &name) { bool status = false; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { mPimpl->mUnits.erase(result); status = true; } return status; } bool Model::removeUnits(const UnitsPtr &units) { bool status = false; auto result = mPimpl->findUnits(units); if (result != mPimpl->mUnits.end()) { mPimpl->mUnits.erase(result); status = true; } return status; } void Model::removeAllUnits() { mPimpl->mUnits.clear(); } bool Model::hasUnits(const std::string &name) const { return mPimpl->findUnits(name) != mPimpl->mUnits.end(); } bool Model::hasUnits(const UnitsPtr &units) const { return mPimpl->findUnits(units) != mPimpl->mUnits.end(); } UnitsPtr Model::getUnits(size_t index) const { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); } return units; } UnitsPtr Model::getUnits(const std::string &name) const { UnitsPtr units = nullptr; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { units = *result; } return units; } UnitsPtr Model::takeUnits(size_t index) { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); removeUnits(index); units->clearParent(); } return units; } UnitsPtr Model::takeUnits(const std::string &name) { return takeUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin()); } bool Model::replaceUnits(size_t index, const UnitsPtr &units) { bool status = false; if (removeUnits(index)) { mPimpl->mUnits.insert(mPimpl->mUnits.begin() + index, units); status = true; } return status; } bool Model::replaceUnits(const std::string &name, const UnitsPtr &units) { return replaceUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin(), units); } bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits) { return replaceUnits(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin(), newUnits); } size_t Model::unitsCount() const { return mPimpl->mUnits.size(); } /** * @brief Resolve the path of the given filename using the given base. * * Resolves the full path to the given @p filename using the @p base. * * This function is only intended to work with local files. It may not * work with bases that use the 'file://' prefix. * * @param filename The @c std::string relative path from the base path. * @param base The @c std::string location on local disk for determining the full path from. * @return The full path from the @p base location to the @p filename */ std::string resolvePath(const std::string &filename, const std::string &base) { // We can be naive here as we know what we are dealing with std::string path = base.substr(0, base.find_last_of('/')+1) + filename; return path; } void resolveImport(const ImportedEntityPtr &importedEntity, const std::string &baseFile) { if (importedEntity->isImport()) { ImportSourcePtr importSource = importedEntity->getImportSource(); if (!importSource->hasModel()) { std::string url = resolvePath(importSource->getUrl(), baseFile); std::ifstream file(url); if (file.good()) { std::stringstream buffer; buffer << file.rdbuf(); Parser parser; ModelPtr model = parser.parseModel(buffer.str()); importSource->setModel(model); model->resolveImports(url); } } } } void resolveComponentImports(const ComponentEntityPtr &parentComponentEntity, const std::string &baseFile) { for (size_t n = 0; n < parentComponentEntity->componentCount(); ++n) { ComponentPtr component = parentComponentEntity->getComponent(n); if (component->isImport()) { resolveImport(component, baseFile); } else { resolveComponentImports(component, baseFile); } } } void Model::resolveImports(const std::string &baseFile) { for (size_t n = 0; n < unitsCount(); ++n) { UnitsPtr units = getUnits(n); resolveImport(units, baseFile); } resolveComponentImports(shared_from_this(), baseFile); } bool isUnresolvedImport(const ImportedEntityPtr &importedEntity) { bool unresolvedImport = false; if (importedEntity->isImport()) { ImportSourcePtr importedSource = importedEntity->getImportSource(); if (!importedSource->hasModel()) { unresolvedImport = true; } } return unresolvedImport; } bool hasUnresolvedComponentImports(const ComponentEntityPtr &parentComponentEntity); bool doHasUnresolvedComponentImports(const ComponentPtr &component) { bool unresolvedImports = false; if (component->isImport()) { unresolvedImports = isUnresolvedImport(component); if (!unresolvedImports) { // Check that the imported component can import all it needs from its model. ImportSourcePtr importedSource = component->getImportSource(); if (importedSource->hasModel()) { ModelPtr importedModel = importedSource->getModel(); ComponentPtr importedComponent = importedModel->getComponent(component->getImportReference()); unresolvedImports = doHasUnresolvedComponentImports(importedComponent); } } } else { unresolvedImports = hasUnresolvedComponentImports(component); } return unresolvedImports; } bool hasUnresolvedComponentImports(const ComponentEntityPtr &parentComponentEntity) { bool unresolvedImports = false; for (size_t n = 0; n < parentComponentEntity->componentCount() && !unresolvedImports; ++n) { ComponentPtr component = parentComponentEntity->getComponent(n); unresolvedImports = doHasUnresolvedComponentImports(component); } return unresolvedImports; } bool Model::hasUnresolvedImports() { bool unresolvedImports = false; for (size_t n = 0; n < unitsCount() && !unresolvedImports; ++n) { UnitsPtr units = getUnits(n); unresolvedImports = isUnresolvedImport(units); } if (!unresolvedImports) { unresolvedImports = hasUnresolvedComponentImports(shared_from_this()); } return unresolvedImports; } } <|endoftext|>
<commit_before>#include "command.hh" #include "store-api.hh" #include "fs-accessor.hh" #include "nar-accessor.hh" #include "common-args.hh" #include "json.hh" using namespace nix; struct MixLs : virtual Args, MixJSON { std::string path; bool recursive = false; bool verbose = false; bool showDirectory = false; MixLs() { mkFlag('R', "recursive", "list subdirectories recursively", &recursive); mkFlag('l', "long", "show more file information", &verbose); mkFlag('d', "directory", "show directories rather than their contents", &showDirectory); } void listText(ref<FSAccessor> accessor) { std::function<void(const FSAccessor::Stat &, const Path &, const std::string &, bool)> doPath; auto showFile = [&](const Path & curPath, const std::string & relPath) { if (verbose) { auto st = accessor->stat(curPath); std::string tp = st.type == FSAccessor::Type::tRegular ? (st.isExecutable ? "-r-xr-xr-x" : "-r--r--r--") : st.type == FSAccessor::Type::tSymlink ? "lrwxrwxrwx" : "dr-xr-xr-x"; std::cout << (format("%s %20d %s") % tp % st.fileSize % relPath); if (st.type == FSAccessor::Type::tSymlink) std::cout << " -> " << accessor->readLink(curPath) ; std::cout << "\n"; if (recursive && st.type == FSAccessor::Type::tDirectory) doPath(st, curPath, relPath, false); } else { std::cout << relPath << "\n"; if (recursive) { auto st = accessor->stat(curPath); if (st.type == FSAccessor::Type::tDirectory) doPath(st, curPath, relPath, false); } } }; doPath = [&](const FSAccessor::Stat & st, const Path & curPath, const std::string & relPath, bool showDirectory) { if (st.type == FSAccessor::Type::tDirectory && !showDirectory) { auto names = accessor->readDirectory(curPath); for (auto & name : names) showFile(curPath + "/" + name, relPath + "/" + name); } else showFile(curPath, relPath); }; auto st = accessor->stat(path); if (st.type == FSAccessor::Type::tMissing) throw Error(format("path '%1%' does not exist") % path); doPath(st, path, st.type == FSAccessor::Type::tDirectory ? "." : baseNameOf(path), showDirectory); } void list(ref<FSAccessor> accessor) { if (path == "/") path = ""; if (json) { JSONPlaceholder jsonRoot(std::cout); listNar(jsonRoot, accessor, path, recursive); } else listText(accessor); } }; struct CmdLsStore : StoreCommand, MixLs { CmdLsStore() { expectArg("path", &path); } Examples examples() override { return { Example{ "To list the contents of a store path in a binary cache:", "nix ls-store --store https://cache.nixos.org/ -lR /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10" }, }; } std::string name() override { return "ls-store"; } std::string description() override { return "show information about a store path"; } void run(ref<Store> store) override { list(store->getFSAccessor()); } }; struct CmdLsNar : Command, MixLs { Path narPath; CmdLsNar() { expectArg("nar", &narPath); expectArg("path", &path); } Examples examples() override { return { Example{ "To list a specific file in a NAR:", "nix ls-nar -l hello.nar /bin/hello" }, }; } std::string name() override { return "ls-nar"; } std::string description() override { return "show information about the contents of a NAR file"; } void run() override { list(makeNarAccessor(make_ref<std::string>(readFile(narPath)))); } }; static RegisterCommand r1(make_ref<CmdLsStore>()); static RegisterCommand r2(make_ref<CmdLsNar>()); <commit_msg>nix ls-nar: allow reading from FIFOs<commit_after>#include "command.hh" #include "store-api.hh" #include "fs-accessor.hh" #include "nar-accessor.hh" #include "common-args.hh" #include "json.hh" using namespace nix; struct MixLs : virtual Args, MixJSON { std::string path; bool recursive = false; bool verbose = false; bool showDirectory = false; MixLs() { mkFlag('R', "recursive", "list subdirectories recursively", &recursive); mkFlag('l', "long", "show more file information", &verbose); mkFlag('d', "directory", "show directories rather than their contents", &showDirectory); } void listText(ref<FSAccessor> accessor) { std::function<void(const FSAccessor::Stat &, const Path &, const std::string &, bool)> doPath; auto showFile = [&](const Path & curPath, const std::string & relPath) { if (verbose) { auto st = accessor->stat(curPath); std::string tp = st.type == FSAccessor::Type::tRegular ? (st.isExecutable ? "-r-xr-xr-x" : "-r--r--r--") : st.type == FSAccessor::Type::tSymlink ? "lrwxrwxrwx" : "dr-xr-xr-x"; std::cout << (format("%s %20d %s") % tp % st.fileSize % relPath); if (st.type == FSAccessor::Type::tSymlink) std::cout << " -> " << accessor->readLink(curPath) ; std::cout << "\n"; if (recursive && st.type == FSAccessor::Type::tDirectory) doPath(st, curPath, relPath, false); } else { std::cout << relPath << "\n"; if (recursive) { auto st = accessor->stat(curPath); if (st.type == FSAccessor::Type::tDirectory) doPath(st, curPath, relPath, false); } } }; doPath = [&](const FSAccessor::Stat & st, const Path & curPath, const std::string & relPath, bool showDirectory) { if (st.type == FSAccessor::Type::tDirectory && !showDirectory) { auto names = accessor->readDirectory(curPath); for (auto & name : names) showFile(curPath + "/" + name, relPath + "/" + name); } else showFile(curPath, relPath); }; auto st = accessor->stat(path); if (st.type == FSAccessor::Type::tMissing) throw Error(format("path '%1%' does not exist") % path); doPath(st, path, st.type == FSAccessor::Type::tDirectory ? "." : baseNameOf(path), showDirectory); } void list(ref<FSAccessor> accessor) { if (path == "/") path = ""; if (json) { JSONPlaceholder jsonRoot(std::cout); listNar(jsonRoot, accessor, path, recursive); } else listText(accessor); } }; struct CmdLsStore : StoreCommand, MixLs { CmdLsStore() { expectArg("path", &path); } Examples examples() override { return { Example{ "To list the contents of a store path in a binary cache:", "nix ls-store --store https://cache.nixos.org/ -lR /nix/store/0i2jd68mp5g6h2sa5k9c85rb80sn8hi9-hello-2.10" }, }; } std::string name() override { return "ls-store"; } std::string description() override { return "show information about a store path"; } void run(ref<Store> store) override { list(store->getFSAccessor()); } }; struct CmdLsNar : Command, MixLs { Path narPath; CmdLsNar() { expectArg("nar", &narPath); expectArg("path", &path); } Examples examples() override { return { Example{ "To list a specific file in a NAR:", "nix ls-nar -l hello.nar /bin/hello" }, }; } std::string name() override { return "ls-nar"; } std::string description() override { return "show information about the contents of a NAR file"; } void run() override { list(makeNarAccessor(make_ref<std::string>(readFile(narPath, true)))); } }; static RegisterCommand r1(make_ref<CmdLsStore>()); static RegisterCommand r2(make_ref<CmdLsNar>()); <|endoftext|>
<commit_before>#include "nan.h" #include "nanodbc.h" #include "picojson.h" using std::string; static v8::Persistent<v8::FunctionTemplate> nodbc_constructor; class NodbcConnection : node::ObjectWrap { public: static void Init(); static NAN_METHOD(New); static NAN_METHOD(IsConnected); static NAN_METHOD(Open); static NAN_METHOD(Close); private: nanodbc::connection connection; }; NAN_METHOD(NodbcConnection::New) { NanScope(); NodbcConnection *obj = new NodbcConnection(); obj->Wrap(args.Holder()); NanReturnValue(args.Holder()); } NAN_METHOD(NodbcConnection::IsConnected) { NanScope(); NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder()); NanReturnValue(NanNew(self->connection.connected())); } class OpenWorker : public NanAsyncWorker { public: OpenWorker(NanCallback *callback, nanodbc::connection *connection, string connectionString) : NanAsyncWorker(callback), connection(connection), connectionString(connectionString) {} void Execute() { try { connection->connect(connectionString); } catch (const nanodbc::database_error &err) { SetErrorMessage(err.what()); } } private: nanodbc::connection *connection; string connectionString; }; NAN_METHOD(NodbcConnection::Open) { NanScope(); NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder()); string connectionString(*NanAsciiString(args[0].As<v8::String>())); NanCallback *callback = new NanCallback(args[1].As<v8::Function>()); OpenWorker *worker = new OpenWorker(callback, &self->connection, connectionString); worker->SaveToPersistent("database", args.Holder()); NanAsyncQueueWorker(worker); NanReturnUndefined(); } class CloseWorker : public NanAsyncWorker { public: CloseWorker(NanCallback *callback, nanodbc::connection *connection) : NanAsyncWorker(callback), connection(connection) {} void Execute() { connection->disconnect(); } private: nanodbc::connection *connection; }; NAN_METHOD(NodbcConnection::Close) { NanScope(); NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder()); NanCallback *callback = new NanCallback(args[0].As<v8::Function>()); CloseWorker *worker = new CloseWorker(callback, &self->connection); worker->SaveToPersistent("database", args.Holder()); NanAsyncQueueWorker(worker); NanReturnUndefined(); } void NodbcConnection::Init() { v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(NodbcConnection::New); NanAssignPersistent(nodbc_constructor, tpl); tpl->SetClassName(NanNew("NodbcConnection")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "isConnected", NodbcConnection::IsConnected); NODE_SET_PROTOTYPE_METHOD(tpl, "open", NodbcConnection::Open); NODE_SET_PROTOTYPE_METHOD(tpl, "close", NodbcConnection::Close); } void Init(v8::Handle<v8::Object> target) { NodbcConnection::Init(); target->Set(NanNew("NodbcConnection"), NanNew<v8::FunctionTemplate>(nodbc_constructor)->GetFunction()); } NODE_MODULE(nodbc, Init) <commit_msg>Add implementation of execute.<commit_after>#include "nan.h" #include "nanodbc.h" #include "picojson.h" using std::string; static v8::Persistent<v8::FunctionTemplate> nodbc_constructor; class NodbcConnection : node::ObjectWrap { public: static void Init(); static NAN_METHOD(New); static NAN_METHOD(IsConnected); static NAN_METHOD(Open); static NAN_METHOD(Close); static NAN_METHOD(Execute); private: nanodbc::connection connection; }; NAN_METHOD(NodbcConnection::New) { NanScope(); NodbcConnection *obj = new NodbcConnection(); obj->Wrap(args.Holder()); NanReturnValue(args.Holder()); } NAN_METHOD(NodbcConnection::IsConnected) { NanScope(); NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder()); NanReturnValue(NanNew(self->connection.connected())); } class OpenWorker : public NanAsyncWorker { public: OpenWorker(NanCallback *callback, nanodbc::connection *connection, string connectionString) : NanAsyncWorker(callback), connection(connection), connectionString(connectionString) {} void Execute() { try { connection->connect(connectionString); } catch (const nanodbc::database_error &err) { SetErrorMessage(err.what()); } } private: nanodbc::connection *connection; string connectionString; }; NAN_METHOD(NodbcConnection::Open) { NanScope(); NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder()); string connectionString(*NanAsciiString(args[0].As<v8::String>())); NanCallback *callback = new NanCallback(args[1].As<v8::Function>()); OpenWorker *worker = new OpenWorker(callback, &self->connection, connectionString); worker->SaveToPersistent("database", args.Holder()); NanAsyncQueueWorker(worker); NanReturnUndefined(); } class CloseWorker : public NanAsyncWorker { public: CloseWorker(NanCallback *callback, nanodbc::connection *connection) : NanAsyncWorker(callback), connection(connection) {} void Execute() { connection->disconnect(); } private: nanodbc::connection *connection; }; NAN_METHOD(NodbcConnection::Close) { NanScope(); NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder()); NanCallback *callback = new NanCallback(args[0].As<v8::Function>()); CloseWorker *worker = new CloseWorker(callback, &self->connection); worker->SaveToPersistent("database", args.Holder()); NanAsyncQueueWorker(worker); NanReturnUndefined(); } class ExecuteWorker : public NanAsyncWorker { public: ExecuteWorker(NanCallback *callback, nanodbc::connection *connection, string query) : NanAsyncWorker(callback), connection(connection), query(query) {} void Execute() { try { nanodbc::result result = nanodbc::execute(*connection, query); picojson::array rows; const short columns = result.columns(); while (result.next()) { picojson::object row; for (short col = 0; col < columns; col++) { row[result.column_name(col)] = picojson::value(result.get<string>(col)); } rows.push_back(picojson::value(row)); } json = picojson::value(rows).serialize(); } catch (const nanodbc::database_error &err) { SetErrorMessage(err.what()); } } void HandleOKCallback() { NanScope(); v8::Local<v8::Value> argv[] = { NanNull(), NanNew(json.c_str()) }; callback->Call(2, argv); }; private: nanodbc::connection *connection; string query; string json; }; NAN_METHOD(NodbcConnection::Execute) { NanScope(); NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder()); string query(*NanAsciiString(args[0].As<v8::String>())); NanCallback *callback = new NanCallback(args[1].As<v8::Function>()); ExecuteWorker *worker = new ExecuteWorker(callback, &self->connection, query); worker->SaveToPersistent("database", args.Holder()); NanAsyncQueueWorker(worker); NanReturnUndefined(); } void NodbcConnection::Init() { v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(NodbcConnection::New); NanAssignPersistent(nodbc_constructor, tpl); tpl->SetClassName(NanNew("NodbcConnection")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "isConnected", NodbcConnection::IsConnected); NODE_SET_PROTOTYPE_METHOD(tpl, "open", NodbcConnection::Open); NODE_SET_PROTOTYPE_METHOD(tpl, "close", NodbcConnection::Close); NODE_SET_PROTOTYPE_METHOD(tpl, "execute", NodbcConnection::Execute); } void Init(v8::Handle<v8::Object> target) { NodbcConnection::Init(); target->Set(NanNew("NodbcConnection"), NanNew<v8::FunctionTemplate>(nodbc_constructor)->GetFunction()); } NODE_MODULE(nodbc, Init) <|endoftext|>
<commit_before>#include <ecto/plasm.hpp> #include <ecto/tendril.hpp> #include <ecto/module.hpp> #include <string> #include <map> #include <set> #include <utility> //this quiets a deprecated warning #define BOOST_NO_HASH #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <boost/graph/graphviz.hpp> using boost::vertex_property_tag; using boost::adjacency_list; using boost::vecS; using boost::bidirectionalS; using boost::property; using boost::property_map; using boost::graph_traits; namespace ecto { struct ModuleGraph { typedef std::pair<module::ptr, std::string> _Vertex; struct Vertex : public _Vertex { Vertex() : _Vertex() { } Vertex(const module::ptr& p, const std::string& s) : _Vertex(p, s) { } struct Tag { typedef vertex_property_tag kind; }; typedef property<Tag, Vertex> Property; size_t uid; }; struct opless { inline bool operator()(const Vertex&lhs, const Vertex& rhs) const { return lhs.first.get() < rhs.first.get() || (lhs.first.get() == rhs.first.get() && lhs.second < rhs.second); } }; typedef adjacency_list<boost::setS, vecS, boost::bidirectionalS, Vertex::Property> graph_t; typedef graph_traits<graph_t> GraphTraits; typedef graph_traits<graph_t>::vertex_descriptor Vertex_Desc; graph_t graph_, root_graph_; void add_edge(module::ptr from_m, const std::string& out_name, module::ptr to_m, const std::string& in_name) { Vertex from = make_vert(from_m, out_name); Vertex to = make_vert(to_m, in_name); Vertex root_from = make_vert(from_m); Vertex root_to = make_vert(to_m); boost::add_edge(root_from.uid, from.uid, graph_); boost::add_edge(root_from.uid, root_to.uid, root_graph_); boost::add_edge(from.uid, to.uid, graph_); boost::add_edge(to.uid, root_to.uid, graph_); } Vertex& get_vert(size_t uid) { return boost::get(Vertex::Tag(), graph_)[uid]; } Vertex make_vert(const module::ptr& p, const std::string& s = "root") { Vertex v(p, s); getUID(v); get_vert(v.uid) = v; return v; } struct Dirtier { Dirtier(ModuleGraph&g) : graph(g) { } void operator()(const Vertex_Desc& v) { graph.get_vert(v).first->dirty(true); if(graph.graph_.out_edge_list(v).empty()) return; GraphTraits::out_edge_iterator out_i, out_end; GraphTraits::edge_descriptor e; for (boost::tie(out_i, out_end) = boost::out_edges(v, graph.root_graph_); out_i != out_end; ++out_i) { e = *out_i; Vertex_Desc targ = target(e, graph.root_graph_); (*this)(targ); } } ModuleGraph& graph; }; struct Goer { Goer(ModuleGraph&g) : graph(g) { } void operator()(const Vertex_Desc& v) { Vertex& vert = graph.get_vert(v); if (!vert.first->dirty()) return; GraphTraits::in_edge_iterator in_i, in_end; GraphTraits::edge_descriptor e; if(!graph.graph_.out_edge_list(v).empty()) for (boost::tie(in_i, in_end) = boost::in_edges(v, graph.root_graph_); in_i != in_end; ++in_i) { e = *in_i; Vertex_Desc targ = boost::source(e, graph.root_graph_); (*this)(targ); } vert.first->Process(); vert.first->dirty(true); } ModuleGraph& graph; }; void mark_dirty(module::ptr m) { Dirtier(*this)(make_vert(m).uid); } void go(module::ptr m) { Goer(*this)(make_vert(m).uid); } typedef std::set<Vertex, opless> module_set_t; module_set_t module_set; /** Assigns a unique vertex id, from the graph. * * @param v */ inline void getUID(Vertex& v) { //std::cout << v.first << v.second << std::endl; module_set_t::const_iterator it = module_set.find(v); if (it == module_set.end()) { v.uid = boost::add_vertex(graph_); module_set.insert(v).second; } else v.uid = it->uid; } }; struct plasm::impl { ModuleGraph modules_; }; plasm::plasm() : impl_(new impl) { } void plasm::connect(module::ptr from, const std::string& out_name, module::ptr to, const std::string& in_name) { impl_->modules_.add_edge(from, out_name, to, in_name); from->connect(out_name, to, in_name); } void plasm::markDirty(module::ptr m) { // Access the property accessor type for this graph impl_->modules_.mark_dirty(m); } void plasm::go(module::ptr m) { impl_->modules_.go(m); } void plasm::viz(std::ostream& out) const { boost::write_graphviz(out, impl_->modules_.graph_); } std::string plasm::viz() const { std::stringstream ss; viz(ss); return ss.str(); } } <commit_msg>fixme.<commit_after>#include <ecto/plasm.hpp> #include <ecto/tendril.hpp> #include <ecto/module.hpp> #include <string> #include <map> #include <set> #include <utility> //this quiets a deprecated warning #define BOOST_NO_HASH #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/tuple/tuple.hpp> #include <boost/graph/graphviz.hpp> using boost::vertex_property_tag; using boost::adjacency_list; using boost::vecS; using boost::bidirectionalS; using boost::property; using boost::property_map; using boost::graph_traits; namespace ecto { struct ModuleGraph { typedef std::pair<module::ptr, std::string> _Vertex; struct Vertex : public _Vertex { Vertex() : _Vertex() { } Vertex(const module::ptr& p, const std::string& s) : _Vertex(p, s) { } struct Tag { typedef vertex_property_tag kind; }; typedef property<Tag, Vertex> Property; size_t uid; }; struct opless { inline bool operator()(const Vertex&lhs, const Vertex& rhs) const { return lhs.first.get() < rhs.first.get() || (lhs.first.get() == rhs.first.get() && lhs.second < rhs.second); } }; typedef adjacency_list<boost::setS, vecS, boost::bidirectionalS, Vertex::Property> graph_t; typedef graph_traits<graph_t> GraphTraits; typedef graph_traits<graph_t>::vertex_descriptor Vertex_Desc; graph_t graph_, root_graph_; void add_edge(module::ptr from_m, const std::string& out_name, module::ptr to_m, const std::string& in_name) { Vertex from = make_vert(from_m, out_name); Vertex to = make_vert(to_m, in_name); Vertex root_from = make_vert(from_m); Vertex root_to = make_vert(to_m); boost::add_edge(root_from.uid, from.uid, graph_); boost::add_edge(root_from.uid, root_to.uid, root_graph_); boost::add_edge(from.uid, to.uid, graph_); boost::add_edge(to.uid, root_to.uid, graph_); } Vertex& get_vert(size_t uid) { return boost::get(Vertex::Tag(), graph_)[uid]; } Vertex make_vert(const module::ptr& p, const std::string& s = "root") { Vertex v(p, s); getUID(v); get_vert(v.uid) = v; return v; } struct Dirtier { Dirtier(ModuleGraph&g) : graph(g) { } void operator()(const Vertex_Desc& v) { graph.get_vert(v).first->dirty(true); //fixme!!! if(graph.graph_.out_edge_list(v).empty()) return; GraphTraits::out_edge_iterator out_i, out_end; GraphTraits::edge_descriptor e; for (boost::tie(out_i, out_end) = boost::out_edges(v, graph.root_graph_); out_i != out_end; ++out_i) { e = *out_i; Vertex_Desc targ = target(e, graph.root_graph_); (*this)(targ); } } ModuleGraph& graph; }; struct Goer { Goer(ModuleGraph&g) : graph(g) { } void operator()(const Vertex_Desc& v) { Vertex& vert = graph.get_vert(v); if (!vert.first->dirty()) return; GraphTraits::in_edge_iterator in_i, in_end; GraphTraits::edge_descriptor e; //fixme!!! if(!graph.graph_.out_edge_list(v).empty()) for (boost::tie(in_i, in_end) = boost::in_edges(v, graph.root_graph_); in_i != in_end; ++in_i) { e = *in_i; Vertex_Desc targ = boost::source(e, graph.root_graph_); (*this)(targ); } vert.first->Process(); vert.first->dirty(true); } ModuleGraph& graph; }; void mark_dirty(module::ptr m) { Dirtier(*this)(make_vert(m).uid); } void go(module::ptr m) { Goer(*this)(make_vert(m).uid); } typedef std::set<Vertex, opless> module_set_t; module_set_t module_set; /** Assigns a unique vertex id, from the graph. * * @param v */ inline void getUID(Vertex& v) { //std::cout << v.first << v.second << std::endl; module_set_t::const_iterator it = module_set.find(v); if (it == module_set.end()) { v.uid = boost::add_vertex(graph_); module_set.insert(v).second; } else v.uid = it->uid; } }; struct plasm::impl { ModuleGraph modules_; }; plasm::plasm() : impl_(new impl) { } void plasm::connect(module::ptr from, const std::string& out_name, module::ptr to, const std::string& in_name) { impl_->modules_.add_edge(from, out_name, to, in_name); from->connect(out_name, to, in_name); } void plasm::markDirty(module::ptr m) { // Access the property accessor type for this graph impl_->modules_.mark_dirty(m); } void plasm::go(module::ptr m) { impl_->modules_.go(m); } void plasm::viz(std::ostream& out) const { boost::write_graphviz(out, impl_->modules_.graph_); } std::string plasm::viz() const { std::stringstream ss; viz(ss); return ss.str(); } } <|endoftext|>
<commit_before>#include "standard.h" #include "utils.h" #include "serversocket.h" #include "logger.cpp" #include "proxysocket.h" using namespace std; ServerSocket mainSocket; char *remoteUrl; int remotePort; Modes mode = CLIENT; // For closing the sockets safely when Ctrl+C SIGINT is received void intHandler(int dummy) { info("\nClosing socket\n"); mainSocket.closeSocket(); exit(0); } // To ignore SIGPIPE being carried over to the parent // When client closes pipe void pipeHandler(int dummy) { info("Connection closed due to SIGPIPE"); } void exchangeData(ProxySocket& sock) { vector<char> buffer((BUFSIZE+5)*sizeof(char)); vector<char> duffer((BUFSIZE+5)*sizeof(char)); ProxySocket outsock = ProxySocket(remoteUrl, remotePort, mode==CLIENT?HTTP:PLAIN); bool areTheyStillThere = true; setNonBlocking(sock.fd); int a, b; do { a = outsock.recvFromSocket(buffer, 0, b); if (a == -1) { areTheyStillThere = false; break; } if (a == 0) { logger << "Got nothing from remote"; } else { // TODO If sock is HTTP, don't send till there's a request read sock.sendFromSocket(buffer, b, a); logger << "Sent " << a << " bytes from remote to local"; } buffer[0] = 0; a = sock.recvFromSocket(duffer, 0, b); if (a == -1) { areTheyStillThere = false; break; } if (a == 0) { logger << "Got nothing from client"; // TODO Send empty HTTP requests if outsock is HTTP } else { outsock.sendFromSocket(duffer, b, a); logger << "Sent " << a << " bytes from local to remote"; } duffer[0] = 0; sleep(1); } while (areTheyStillThere); } int main(int argc, char * argv[]) { int portNumber, pid; signal(SIGINT, intHandler); signal(SIGPIPE, pipeHandler); signal(SIGCHLD, SIG_IGN); // CLI argument parsing if (argc != 4 && argc != 5) error("Usage format: ./http-server <local port> <remote url> <remotePort>"); portNumber = atoi(argv[1]); remoteUrl = argv[2]; remotePort = atoi(argv[3]); if (argc == 5) { if (strcmp(argv[4], "SERVER") == 0) { mode = SERVER; info("Running as server"); } else { info("Running as client"); } } // Class ServerSocket handles the connection logic mainSocket.listenOnPort(portNumber); // The main loop which receives and handles connections while (1) { // Accept connections and create a class instance // Forks as needed mainSocket.connectToSocket(exchangeData, mode); } return 0; } <commit_msg>Decent lag working model, unsynced<commit_after>#include "standard.h" #include "utils.h" #include "serversocket.h" #include "logger.cpp" #include "proxysocket.h" using namespace std; ServerSocket mainSocket; char *remoteUrl; int remotePort; Modes mode = CLIENT; // For closing the sockets safely when Ctrl+C SIGINT is received void intHandler(int dummy) { info("\nClosing socket\n"); mainSocket.closeSocket(); exit(0); } // To ignore SIGPIPE being carried over to the parent // When client closes pipe void pipeHandler(int dummy) { info("Connection closed due to SIGPIPE"); } void exchangeData(ProxySocket& sock) { vector<char> buffer((BUFSIZE+5)*sizeof(char)); vector<char> duffer((BUFSIZE+5)*sizeof(char)); ProxySocket outsock = ProxySocket(remoteUrl, remotePort, mode==CLIENT?HTTP:PLAIN); bool areTheyStillThere = true; setNonBlocking(sock.fd); int a, b; bool canIRespond = false; do { a = outsock.recvFromSocket(buffer, 0, b); if (a == -1) { areTheyStillThere = false; break; } if (a == 0) { logger << "Got nothing from remote"; } else { // TODO If sock is HTTP, don't send till there's a request // read // if (sock.protocol == PLAIN || canIRespond) { // sock.sendFromSocket(buffer, b, a); // canIRespond = false; // } sock.sendFromSocket(buffer, b, a); logger << "Sent " << a << " bytes from remote to local"; } buffer[0] = 0; a = sock.recvFromSocket(duffer, 0, b); if (a == -1) { areTheyStillThere = false; break; } if (a == 0) { logger << "Got nothing from client"; // if (outsock.protocol == HTTP) { // outsock.sendEmptyHttp(); // } // TODO Send empty HTTP requests if outsock is HTTP } else { outsock.sendFromSocket(duffer, b, a); logger << "Sent " << a << " bytes from local to remote"; } duffer[0] = 0; usleep(100000); } while (areTheyStillThere); } int main(int argc, char * argv[]) { int portNumber, pid; signal(SIGINT, intHandler); signal(SIGPIPE, pipeHandler); signal(SIGCHLD, SIG_IGN); // CLI argument parsing if (argc != 4 && argc != 5) error("Usage format: ./http-server <local port> <remote url> <remotePort>"); portNumber = atoi(argv[1]); remoteUrl = argv[2]; remotePort = atoi(argv[3]); if (argc == 5) { if (strcmp(argv[4], "SERVER") == 0) { mode = SERVER; info("Running as server"); } else { info("Running as client"); } } // Class ServerSocket handles the connection logic mainSocket.listenOnPort(portNumber); // The main loop which receives and handles connections while (1) { // Accept connections and create a class instance // Forks as needed mainSocket.connectToSocket(exchangeData, mode); } return 0; } <|endoftext|>
<commit_before>// @(#)root/gl:$Id$ // Author: Bertrand Bellenot 2008 /************************************************************************* * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TGLOverlayButton.h" #include "TColor.h" #include "TMath.h" #include <TGLRnrCtx.h> #include <TGLIncludes.h> #include <TGLSelectRecord.h> #include <TGLUtil.h> #include <TGLCamera.h> #include <TGLViewerBase.h> //______________________________________________________________________________ // // // GL-overaly button. // // ClassImp(TGLOverlayButton); //______________________________________________________________________________ TGLOverlayButton::TGLOverlayButton(TGLViewerBase *parent, const char *text, Float_t posx, Float_t posy, Float_t width, Float_t height) : TGLOverlayElement(), fText(text), fActiveID(-1), fBackColor(0x8080ff), fTextColor(0xffffff), fNormAlpha(0.2), fHighAlpha(1.0), fPosX(posx), fPosY(posy), fWidth(width), fHeight(height) { // Constructor. if (parent) parent->AddOverlayElement(this); } /******************************************************************************/ void TGLOverlayButton::Render(TGLRnrCtx& rnrCtx) { // Render the overlay elements. Float_t r, g, b; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); if (rnrCtx.Selection()) { TGLRect rect(*rnrCtx.GetPickRectangle()); rnrCtx.GetCamera()->WindowToViewport(rect); gluPickMatrix(rect.X(), rect.Y(), rect.Width(), rect.Height(), (Int_t*) rnrCtx.GetCamera()->RefViewport().CArr()); } const TGLRect& vp = rnrCtx.RefCamera().RefViewport(); glOrtho(vp.X(), vp.Width(), vp.Y(), vp.Height(), 0, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); Float_t offset = (fPosY >= 0.0)? 0.0 : vp.Height()-fHeight; TGLCapabilitySwitch lights_off(GL_LIGHTING, kFALSE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel(GL_FLAT); glClearColor(0.0, 0.0, 0.0, 0.0); // Button rendering { TGLCapabilitySwitch move_to_back(GL_POLYGON_OFFSET_FILL, kTRUE); glPolygonOffset(0.5f, 0.5f); glPushMatrix(); glTranslatef(fPosX, offset+fPosY, 0); // First the border, same color as text TColor::Pixel2RGB(fTextColor, r, g, b); (fActiveID == 1) ? TGLUtil::Color4f(r, g, b, fHighAlpha):TGLUtil::Color4f(r, g, b, fNormAlpha); TGLUtil::LineWidth(1); glBegin(GL_LINE_LOOP); glVertex2f(0.0, 0.0); glVertex2f(0.0, fHeight); glVertex2f(fWidth, fHeight); glVertex2f(fWidth, 0.0); glEnd(); // then the button itself, with its own color // decrease a bit the highlight, to avoid bad effects... TColor::Pixel2RGB(fBackColor, r, g, b); (fActiveID == 1) ? TGLUtil::Color4f(r, g, b, fHighAlpha * 0.8):TGLUtil::Color4f(r, g, b, fNormAlpha); glBegin(GL_QUADS); glVertex2f(0.0, 0.0); glVertex2f(0.0, fHeight); glVertex2f(fWidth, fHeight); glVertex2f(fWidth, 0.0); glEnd(); glPopMatrix(); } // Text rendering { rnrCtx.RegisterFontNoScale(TMath::Nint(fHeight*0.8), "arial", TGLFont::kPixmap, fFont); fFont.PreRender(kFALSE); TColor::Pixel2RGB(fTextColor, r, g, b); (fActiveID == 1) ? TGLUtil::Color4f(r, g, b, fHighAlpha):TGLUtil::Color4f(r, g, b, fNormAlpha); glPushMatrix(); glTranslatef(fPosX+(fWidth/2.0), offset+fPosY+(fHeight/2.0), 0); Float_t llx, lly, llz, urx, ury, urz; fFont.BBox(fText.Data(), llx, lly, llz, urx, ury, urz); glRasterPos2i(0, 0); glBitmap(0, 0, 0, 0, -urx*0.5f, -ury*0.4f, 0); fFont.Render(fText.Data()); fFont.PostRender(); glPopMatrix(); } glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } //______________________________________________________________________________ void TGLOverlayButton::Clicked(TGLViewerBase *viewer) { // Emits "Clicked(TGLViewerBase*)" signal. // Called when user click on the GL button. Emit("Clicked(TGLViewerBase*)", (Long_t)viewer); } /******************************************************************************/ // Virtual event handlers from TGLOverlayElement /******************************************************************************/ //______________________________________________________________________________ Bool_t TGLOverlayButton::Handle(TGLRnrCtx & rnrCtx, TGLOvlSelectRecord & rec, Event_t * event) { // Handle overlay event. // Return TRUE if event was handled. if (event->fCode != kButton1) { return kFALSE; } switch (event->fType) { case kButtonPress: if (rec.GetItem(1) == 1) { return kTRUE; } break; case kButtonRelease: if (rec.GetItem(1) == 1) { Clicked(rnrCtx.GetViewer()); return kTRUE; } break; default: break; } return kFALSE; } //______________________________________________________________________________ Bool_t TGLOverlayButton::MouseEnter(TGLOvlSelectRecord& /*rec*/) { // Mouse has entered overlay area. fActiveID = 1; return kTRUE; } //______________________________________________________________________________ void TGLOverlayButton::MouseLeave() { // Mouse has left overlay area. fActiveID = -1; } <commit_msg>From Bertrand: Fix gl-name handling, improve text centering.<commit_after>// @(#)root/gl:$Id$ // Author: Bertrand Bellenot 2008 /************************************************************************* * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TGLOverlayButton.h" #include "TColor.h" #include "TMath.h" #include <TGLRnrCtx.h> #include <TGLIncludes.h> #include <TGLSelectRecord.h> #include <TGLUtil.h> #include <TGLCamera.h> #include <TGLViewerBase.h> //______________________________________________________________________________ // // // GL-overaly button. // // ClassImp(TGLOverlayButton); //______________________________________________________________________________ TGLOverlayButton::TGLOverlayButton(TGLViewerBase *parent, const char *text, Float_t posx, Float_t posy, Float_t width, Float_t height) : TGLOverlayElement(), fText(text), fActiveID(-1), fBackColor(0x8080ff), fTextColor(0xffffff), fNormAlpha(0.2), fHighAlpha(1.0), fPosX(posx), fPosY(posy), fWidth(width), fHeight(height) { // Constructor. if (parent) parent->AddOverlayElement(this); } /******************************************************************************/ void TGLOverlayButton::Render(TGLRnrCtx& rnrCtx) { // Render the overlay elements. Float_t r, g, b; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); if (rnrCtx.Selection()) { TGLRect rect(*rnrCtx.GetPickRectangle()); rnrCtx.GetCamera()->WindowToViewport(rect); gluPickMatrix(rect.X(), rect.Y(), rect.Width(), rect.Height(), (Int_t*) rnrCtx.GetCamera()->RefViewport().CArr()); } const TGLRect& vp = rnrCtx.RefCamera().RefViewport(); glOrtho(vp.X(), vp.Width(), vp.Y(), vp.Height(), 0, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); Float_t offset = (fPosY >= 0.0)? 0.0 : vp.Height()-fHeight; TGLCapabilitySwitch lights_off(GL_LIGHTING, kFALSE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel(GL_FLAT); glClearColor(0.0, 0.0, 0.0, 0.0); glPushName(1); // Button rendering { TGLCapabilitySwitch move_to_back(GL_POLYGON_OFFSET_FILL, kTRUE); glPolygonOffset(0.5f, 0.5f); glPushMatrix(); glTranslatef(fPosX, offset+fPosY, 0); // First the border, same color as text TColor::Pixel2RGB(fTextColor, r, g, b); (fActiveID == 1) ? TGLUtil::Color4f(r, g, b, fHighAlpha):TGLUtil::Color4f(r, g, b, fNormAlpha); TGLUtil::LineWidth(1); glBegin(GL_LINE_LOOP); glVertex2f(0.0, 0.0); glVertex2f(0.0, fHeight); glVertex2f(fWidth, fHeight); glVertex2f(fWidth, 0.0); glEnd(); // then the button itself, with its own color // decrease a bit the highlight, to avoid bad effects... TColor::Pixel2RGB(fBackColor, r, g, b); (fActiveID == 1) ? TGLUtil::Color4f(r, g, b, fHighAlpha * 0.8):TGLUtil::Color4f(r, g, b, fNormAlpha); glBegin(GL_QUADS); glVertex2f(0.0, 0.0); glVertex2f(0.0, fHeight); glVertex2f(fWidth, fHeight); glVertex2f(fWidth, 0.0); glEnd(); glPopMatrix(); } // Text rendering { rnrCtx.RegisterFontNoScale(TMath::Nint(fHeight*0.8), "arial", TGLFont::kPixmap, fFont); fFont.PreRender(kFALSE); TColor::Pixel2RGB(fTextColor, r, g, b); (fActiveID == 1) ? TGLUtil::Color4f(r, g, b, fHighAlpha):TGLUtil::Color4f(r, g, b, fNormAlpha); glPushMatrix(); glTranslatef(fPosX+(fWidth/2.0), offset+fPosY+(fHeight/2.0), 0); Float_t llx, lly, llz, urx, ury, urz; fFont.BBox(fText.Data(), llx, lly, llz, urx, ury, urz); glRasterPos2i(0, 0); glBitmap(0, 0, 0, 0, -urx*0.5f, -ury*0.5f, 0); fFont.Render(fText.Data()); fFont.PostRender(); glPopMatrix(); } glPopName(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } //______________________________________________________________________________ void TGLOverlayButton::Clicked(TGLViewerBase *viewer) { // Emits "Clicked(TGLViewerBase*)" signal. // Called when user click on the GL button. Emit("Clicked(TGLViewerBase*)", (Long_t)viewer); } /******************************************************************************/ // Virtual event handlers from TGLOverlayElement /******************************************************************************/ //______________________________________________________________________________ Bool_t TGLOverlayButton::Handle(TGLRnrCtx & rnrCtx, TGLOvlSelectRecord & rec, Event_t * event) { // Handle overlay event. // Return TRUE if event was handled. if (event->fCode != kButton1) { return kFALSE; } switch (event->fType) { case kButtonPress: if (rec.GetItem(1) == 1) { return kTRUE; } break; case kButtonRelease: if (rec.GetItem(1) == 1) { Clicked(rnrCtx.GetViewer()); return kTRUE; } break; default: break; } return kFALSE; } //______________________________________________________________________________ Bool_t TGLOverlayButton::MouseEnter(TGLOvlSelectRecord& /*rec*/) { // Mouse has entered overlay area. fActiveID = 1; return kTRUE; } //______________________________________________________________________________ void TGLOverlayButton::MouseLeave() { // Mouse has left overlay area. fActiveID = -1; } <|endoftext|>
<commit_before>#include <netinet/in.h> #include <rapid/rapid.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <cassert> #include <cstring> #include <string> #include <thread> #include <openssl/err.h> #include <openssl/ssl.h> namespace rapid { class TlsManager { public: static TlsManager *instance() { static TlsManager *_instance = nullptr; if (_instance) { return _instance; } _instance = new TlsManager; return _instance; } bool failed() const { return _failed; } bool succeed() const { return !_failed; } void init() { SSL_library_init(); OpenSSL_add_all_algorithms(); SSL_load_error_strings(); auto method = TLSv1_server_method(); auto ctx = SSL_CTX_new(method); if (!ctx) { _failed = true; ERR_print_errors_fp(stderr); return; } _ctx = ctx; } bool load_certificate(const std::string &cert_path) { if (_ctx == nullptr) { return false; } if (SSL_CTX_use_certificate_file(_ctx, cert_path.c_str(), SSL_FILETYPE_PEM) <= 0) { return false; } return true; } bool load_private_key(const std::string &private_key_path) { if (_ctx == nullptr) { return false; } if (SSL_CTX_use_PrivateKey_file(_ctx, private_key_path.c_str(), SSL_FILETYPE_PEM) <= 0) { return false; } return true; } bool verify_private_key() { if (_ctx == nullptr) { return false; } if (!SSL_CTX_check_private_key(_ctx)) { return false; } return true; } bool recv_tls(int peer, const std::function<ResponsePtr(Request &)> &fn) { if (_ctx == nullptr) { return false; } SSL *ssl = SSL_new(_ctx); SSL_set_fd(ssl, peer); if (SSL_accept(ssl) == -1) { // ... } else { char buf[4096]; auto bytes = SSL_read(ssl, buf, sizeof(buf)); if (0 < bytes) { buf[bytes] = 0; Request request(buf); auto response = fn(request); auto response_s = response->message(); SSL_write(ssl, response_s->c_str(), static_cast<int>(response_s->size())); } } SSL_free(ssl); return true; } private: bool _failed = false; SSL_CTX *_ctx = nullptr; }; Server::Server() {} void Server::set_port(int port) { _port = port; } void Server::use_tls() { _use_tls = true; } void Server::set_tls_certificate_path(const std::string &path) { _cert_path = path; } void Server::set_tls_private_key_path(const std::string &path) { _pk_path = path; } void Server::run() { assert(_port != kUndefinedPort); auto th = std::thread([&] { _stopped = false; boot(); while (!_stop_requested) { dispatch_http_request(_sock); } close(_sock); _sock = -1; _stopped = true; }); th.detach(); } void Server::stop() { _stop_requested = true; } bool Server::stopped() const { return _stopped; } void Server::get(const std::string &pattern, const Handler &handler) { _dispatcher.add(Route(Method::Get, pattern, handler)); } void Server::post(const std::string &pattern, const Handler &handler) { _dispatcher.add(Route(Method::Post, pattern, handler)); } void Server::boot() { if (_sock == -1) { if (_use_tls) { TlsManager::instance()->init(); TlsManager::instance()->load_certificate(_cert_path); TlsManager::instance()->load_private_key(_pk_path); TlsManager::instance()->verify_private_key(); } _sock = socket(AF_INET, SOCK_STREAM, 0); int flag = 1; setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(_port); addr.sin_addr.s_addr = INADDR_ANY; addr.sin_len = sizeof(addr); bind(_sock, (struct sockaddr *)&addr, sizeof(addr)); listen(_sock, 5); } } void Server::dispatch_http_request(int socket) { struct sockaddr_in client_addr; auto len = sizeof(client_addr); auto peer = accept(socket, (struct sockaddr *)&client_addr, (socklen_t *)&len); if (_use_tls) { TlsManager::instance()->recv_tls(peer, [&](Request &request) -> ResponsePtr { return _dispatcher.dispatch(request); }); } else { char inbuf[4096]; auto inlen = recv(peer, inbuf, sizeof(inbuf), 0); inbuf[inlen] = '\0'; Request request(inbuf); auto response = _dispatcher.dispatch(request); auto response_s = response->message(); write(peer, response_s->c_str(), response_s->size()); } close(peer); } }<commit_msg>remove sin_len<commit_after>#include <netinet/in.h> #include <rapid/rapid.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <cassert> #include <cstring> #include <string> #include <thread> #include <openssl/err.h> #include <openssl/ssl.h> namespace rapid { class TlsManager { public: static TlsManager *instance() { static TlsManager *_instance = nullptr; if (_instance) { return _instance; } _instance = new TlsManager; return _instance; } bool failed() const { return _failed; } bool succeed() const { return !_failed; } void init() { SSL_library_init(); OpenSSL_add_all_algorithms(); SSL_load_error_strings(); auto method = TLSv1_server_method(); auto ctx = SSL_CTX_new(method); if (!ctx) { _failed = true; ERR_print_errors_fp(stderr); return; } _ctx = ctx; } bool load_certificate(const std::string &cert_path) { if (_ctx == nullptr) { return false; } if (SSL_CTX_use_certificate_file(_ctx, cert_path.c_str(), SSL_FILETYPE_PEM) <= 0) { return false; } return true; } bool load_private_key(const std::string &private_key_path) { if (_ctx == nullptr) { return false; } if (SSL_CTX_use_PrivateKey_file(_ctx, private_key_path.c_str(), SSL_FILETYPE_PEM) <= 0) { return false; } return true; } bool verify_private_key() { if (_ctx == nullptr) { return false; } if (!SSL_CTX_check_private_key(_ctx)) { return false; } return true; } bool recv_tls(int peer, const std::function<ResponsePtr(Request &)> &fn) { if (_ctx == nullptr) { return false; } SSL *ssl = SSL_new(_ctx); SSL_set_fd(ssl, peer); if (SSL_accept(ssl) == -1) { // ... } else { char buf[4096]; auto bytes = SSL_read(ssl, buf, sizeof(buf)); if (0 < bytes) { buf[bytes] = 0; Request request(buf); auto response = fn(request); auto response_s = response->message(); SSL_write(ssl, response_s->c_str(), static_cast<int>(response_s->size())); } } SSL_free(ssl); return true; } private: bool _failed = false; SSL_CTX *_ctx = nullptr; }; Server::Server() {} void Server::set_port(int port) { _port = port; } void Server::use_tls() { _use_tls = true; } void Server::set_tls_certificate_path(const std::string &path) { _cert_path = path; } void Server::set_tls_private_key_path(const std::string &path) { _pk_path = path; } void Server::run() { assert(_port != kUndefinedPort); auto th = std::thread([&] { _stopped = false; boot(); while (!_stop_requested) { dispatch_http_request(_sock); } close(_sock); _sock = -1; _stopped = true; }); th.detach(); } void Server::stop() { _stop_requested = true; } bool Server::stopped() const { return _stopped; } void Server::get(const std::string &pattern, const Handler &handler) { _dispatcher.add(Route(Method::Get, pattern, handler)); } void Server::post(const std::string &pattern, const Handler &handler) { _dispatcher.add(Route(Method::Post, pattern, handler)); } void Server::boot() { if (_sock == -1) { if (_use_tls) { TlsManager::instance()->init(); TlsManager::instance()->load_certificate(_cert_path); TlsManager::instance()->load_private_key(_pk_path); TlsManager::instance()->verify_private_key(); } _sock = socket(AF_INET, SOCK_STREAM, 0); int flag = 1; setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(_port); addr.sin_addr.s_addr = INADDR_ANY; bind(_sock, (struct sockaddr *)&addr, sizeof(addr)); listen(_sock, 5); } } void Server::dispatch_http_request(int socket) { struct sockaddr_in client_addr; auto len = sizeof(client_addr); auto peer = accept(socket, (struct sockaddr *)&client_addr, (socklen_t *)&len); if (_use_tls) { TlsManager::instance()->recv_tls(peer, [&](Request &request) -> ResponsePtr { return _dispatcher.dispatch(request); }); } else { char inbuf[4096]; auto inlen = recv(peer, inbuf, sizeof(inbuf), 0); inbuf[inlen] = '\0'; Request request(inbuf); auto response = _dispatcher.dispatch(request); auto response_s = response->message(); write(peer, response_s->c_str(), response_s->size()); } close(peer); } } <|endoftext|>
<commit_before>#include <franka/robot.h> #include <Poco/Net/DatagramSocket.h> #include <Poco/Net/NetException.h> #include <Poco/Net/StreamSocket.h> #include <Poco/Timespan.h> #include <chrono> #include <iostream> #include <sstream> #include "message_types.h" #include "network.h" namespace franka { class Robot::Impl { public: explicit Impl(const std::string& frankaAddress); ~Impl(); bool waitForRobotState(); const RobotState& getRobotState() const; ServerVersion getServerVersion() const; private: const uint16_t kFranka_port_tcp_; const uint16_t kRiLibraryVersion_; const std::chrono::seconds kTimeout_; uint16_t ri_version_; RobotState robot_state_; Poco::Net::StreamSocket tcp_socket_; Poco::Net::DatagramSocket udp_socket_; }; Robot::Robot(const std::string& frankaAddress) : impl_(new Robot::Impl(frankaAddress)) {} // Has to be declared here, as the Impl type is incomplete in the header Robot::~Robot() = default; bool Robot::waitForRobotState() { return impl_->waitForRobotState(); } const RobotState& Robot::getRobotState() const { return impl_->getRobotState(); } Robot::ServerVersion Robot::getServerVersion() const { return impl_->getServerVersion(); } NetworkException::NetworkException(std::string const& message) : std::runtime_error(message) {} ProtocolException::ProtocolException(std::string const& message) : std::runtime_error(message) {} IncompatibleVersionException::IncompatibleVersionException( std::string const& message) : std::runtime_error(message) {} /* Implementation */ Robot::Impl::Impl(const std::string& frankaAddress) : kFranka_port_tcp_{1337}, kRiLibraryVersion_{1}, kTimeout_{5}, ri_version_{0}, robot_state_{}, tcp_socket_{}, udp_socket_{} { try { tcp_socket_.connect({frankaAddress, kFranka_port_tcp_}, Poco::Timespan(kTimeout_.count(), 0)); tcp_socket_.setBlocking(true); tcp_socket_.setSendTimeout(Poco::Timespan(kTimeout_.count(), 0)); tcp_socket_.setReceiveTimeout(Poco::Timespan(kTimeout_.count(), 0)); udp_socket_.setReceiveTimeout(Poco::Timespan(kTimeout_.count(), 0)); udp_socket_.bind({"0.0.0.0", 0}); message_types::ConnectRequest connect_request; connect_request.function_id = message_types::FunctionId::kConnect; connect_request.ri_library_version = kRiLibraryVersion_; connect_request.udp_port = udp_socket_.address().port(); tcp_socket_.sendBytes(&connect_request, sizeof(connect_request)); message_types::ConnectReply connect_reply; readObject(tcp_socket_, connect_reply, kTimeout_); if (connect_reply.status_code != message_types::ConnectReply::StatusCode::kSuccess) { if (connect_reply.status_code == message_types::ConnectReply::StatusCode:: kIncompatibleLibraryVersion) { std::stringstream message; message << "libfranka: incompatible library version. " << "Server version: " << connect_reply.ri_version << "Library version: " << kRiLibraryVersion_; throw IncompatibleVersionException(message.str()); } throw ProtocolException("libfranka: protocol error"); } ri_version_ = connect_reply.ri_version; } catch (Poco::TimeoutException const& e) { throw NetworkException("libfranka: FRANKA connection timeout"); } catch (Poco::Exception const& e) { throw NetworkException(std::string{"libfranka: FRANKA connection: "} + e.what()); } } Robot::Impl::~Impl() { tcp_socket_.shutdown(); tcp_socket_.close(); udp_socket_.close(); } bool Robot::Impl::waitForRobotState() { try { Poco::Net::SocketAddress server_address; int bytes_received = udp_socket_.receiveFrom( &robot_state_, sizeof(robot_state_), server_address, 0); if (bytes_received == sizeof(robot_state_)) { return true; } if (bytes_received == 0) { return false; } throw ProtocolException("libfranka:: incorrect object size"); } catch (Poco::TimeoutException const& e) { throw NetworkException("libfranka: robot state read timeout"); } catch (Poco::Net::NetException const& e) { throw NetworkException(std::string{"libfranka: robot state read: "} + e.what()); } } const RobotState& Robot::Impl::getRobotState() const { return robot_state_; } Robot::ServerVersion Robot::Impl::getServerVersion() const { return ri_version_; } } // namespace franka <commit_msg>Simplify tcp receive.<commit_after>#include <franka/robot.h> #include <Poco/Net/DatagramSocket.h> #include <Poco/Net/NetException.h> #include <Poco/Net/StreamSocket.h> #include <chrono> #include <iostream> #include <sstream> #include "message_types.h" namespace franka { class Robot::Impl { public: explicit Impl(const std::string& frankaAddress); ~Impl(); bool waitForRobotState(); const RobotState& getRobotState() const; ServerVersion getServerVersion() const; protected: // Can throw NetworkException and ProtocolException template <class T> void tcpReceiveObject(T& object); private: const uint16_t kFranka_port_tcp_; const uint16_t kRiLibraryVersion_; const std::chrono::seconds kTimeout_; uint16_t ri_version_; RobotState robot_state_; Poco::Net::StreamSocket tcp_socket_; Poco::Net::DatagramSocket udp_socket_; }; Robot::Robot(const std::string& frankaAddress) : impl_(new Robot::Impl(frankaAddress)) {} // Has to be declared here, as the Impl type is incomplete in the header Robot::~Robot() = default; bool Robot::waitForRobotState() { return impl_->waitForRobotState(); } const RobotState& Robot::getRobotState() const { return impl_->getRobotState(); } Robot::ServerVersion Robot::getServerVersion() const { return impl_->getServerVersion(); } NetworkException::NetworkException(std::string const& message) : std::runtime_error(message) {} ProtocolException::ProtocolException(std::string const& message) : std::runtime_error(message) {} IncompatibleVersionException::IncompatibleVersionException( std::string const& message) : std::runtime_error(message) {} /* Implementation */ Robot::Impl::Impl(const std::string& frankaAddress) : kFranka_port_tcp_{1337}, kRiLibraryVersion_{1}, kTimeout_{5}, ri_version_{0}, robot_state_{}, tcp_socket_{}, udp_socket_{} { try { tcp_socket_.connect({frankaAddress, kFranka_port_tcp_}, Poco::Timespan(kTimeout_.count(), 0)); tcp_socket_.setBlocking(true); tcp_socket_.setSendTimeout(Poco::Timespan(kTimeout_.count(), 0)); tcp_socket_.setReceiveTimeout(Poco::Timespan(kTimeout_.count(), 0)); udp_socket_.setReceiveTimeout(Poco::Timespan(kTimeout_.count(), 0)); udp_socket_.bind({"0.0.0.0", 0}); message_types::ConnectRequest connect_request; connect_request.function_id = message_types::FunctionId::kConnect; connect_request.ri_library_version = kRiLibraryVersion_; connect_request.udp_port = udp_socket_.address().port(); tcp_socket_.sendBytes(&connect_request, sizeof(connect_request)); message_types::ConnectReply connect_reply; tcpReceiveObject(connect_reply); if (connect_reply.status_code != message_types::ConnectReply::StatusCode::kSuccess) { if (connect_reply.status_code == message_types::ConnectReply::StatusCode:: kIncompatibleLibraryVersion) { std::stringstream message; message << "libfranka: incompatible library version. " << "Server version: " << connect_reply.ri_version << "Library version: " << kRiLibraryVersion_; throw IncompatibleVersionException(message.str()); } throw ProtocolException("libfranka: protocol error"); } ri_version_ = connect_reply.ri_version; } catch (Poco::Net::NetException const& e) { throw NetworkException(std::string{"libfranka: FRANKA connection error: "} + e.what()); } catch (Poco::TimeoutException const& e) { throw NetworkException("libfranka: FRANKA connection timeout"); } catch (Poco::Exception const& e) { throw NetworkException(std::string{"libfranka: "} + e.what()); } } Robot::Impl::~Impl() { tcp_socket_.shutdown(); tcp_socket_.close(); udp_socket_.close(); } bool Robot::Impl::waitForRobotState() { try { Poco::Net::SocketAddress server_address; int bytes_received = udp_socket_.receiveFrom( &robot_state_, sizeof(robot_state_), server_address, 0); if (bytes_received == sizeof(robot_state_)) { return true; } if (bytes_received == 0) { return false; } throw ProtocolException("libfranka:: incorrect object size"); } catch (Poco::TimeoutException const& e) { throw NetworkException("libfranka: robot state read timeout"); } catch (Poco::Net::NetException const& e) { throw NetworkException(std::string{"libfranka: robot state read: "} + e.what()); } } const RobotState& Robot::Impl::getRobotState() const { return robot_state_; } Robot::ServerVersion Robot::Impl::getServerVersion() const { return ri_version_; } template <class T> void Robot::Impl::tcpReceiveObject(T& object) { try { int rv = tcp_socket_.receiveBytes(&object, sizeof(object)); if (rv == 0) { throw NetworkException("libfranka:: FRANKA connection closed"); } else if (rv != sizeof(object)) { throw ProtocolException("libfranka:: incorrect object size"); } } catch (Poco::Net::NetException const& e) { throw NetworkException(std::string{"libfranka: FRANKA connection error: "} + e.what()); } catch (Poco::TimeoutException const& e) { throw NetworkException("libfranka: FRANKA connection timeout"); } } } // namespace franka <|endoftext|>
<commit_before>#include "./scene.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <string> #include <vector> #include "./graphics/gl.h" #include "./input/invoke_manager.h" #include "./graphics/render_data.h" #include "./graphics/managers.h" #include "./graphics/volume_manager.h" #include "./graphics/shader_program.h" #include "./camera_controller.h" #include "./camera_rotation_controller.h" #include "./camera_zoom_controller.h" #include "./camera_move_controller.h" #include "./nodes.h" #include "./forces/labeller_frame_data.h" #include "./label_node.h" #include "./eigen_qdebug.h" #include "./utils/path_helper.h" Scene::Scene(std::shared_ptr<InvokeManager> invokeManager, std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels, std::shared_ptr<Forces::Labeller> labeller) : nodes(nodes), labels(labels), labeller(labeller), frustumOptimizer(nodes) { cameraController = std::make_shared<CameraController>(camera); cameraRotationController = std::make_shared<CameraRotationController>(camera); cameraZoomController = std::make_shared<CameraZoomController>(camera); cameraMoveController = std::make_shared<CameraMoveController>(camera); invokeManager->addHandler("cam", cameraController.get()); invokeManager->addHandler("cameraRotation", cameraRotationController.get()); invokeManager->addHandler("cameraZoom", cameraZoomController.get()); invokeManager->addHandler("cameraMove", cameraMoveController.get()); fbo = std::unique_ptr<Graphics::FrameBufferObject>( new Graphics::FrameBufferObject()); managers = std::make_shared<Graphics::Managers>(); } Scene::~Scene() { qDebug() << "Destructor of Scene"; } void Scene::initialize() { glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f)); quad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/textureForRenderBuffer.frag"); fbo->initialize(gl, width, height); haBuffer = std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height)); managers->getShaderManager()->initialize(gl, haBuffer); Graphics::VolumeManager::instance->initialize(gl); managers->getObjectManager()->initialize(gl, 128, 10000000); haBuffer->initialize(gl, managers); quad->initialize(gl, managers); managers->getTextureManager()->initialize(gl, true, 8); } void Scene::update(double frameTime, QSet<Qt::Key> keysPressed) { this->frameTime = frameTime; cameraController->setFrameTime(frameTime); cameraRotationController->setFrameTime(frameTime); cameraZoomController->setFrameTime(frameTime); cameraMoveController->setFrameTime(frameTime); frustumOptimizer.update(camera.getViewMatrix()); camera.updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); auto newPositions = labeller->update(Forces::LabellerFrameData( frameTime, camera.getProjectionMatrix(), camera.getViewMatrix())); for (auto &labelNode : nodes->getLabelNodes()) { labelNode->labelPosition = newPositions[labelNode->label.id]; } } void Scene::render() { if (shouldResize) { camera.resize(width, height); fbo->resize(width, height); shouldResize = false; } glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); fbo->bind(); glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); RenderData renderData; renderData.projectionMatrix = camera.getProjectionMatrix(); renderData.viewMatrix = camera.getViewMatrix(); renderData.cameraPosition = camera.getPosition(); renderData.modelMatrix = Eigen::Matrix4f::Identity(); haBuffer->clearAndPrepare(managers); nodes->render(gl, managers, renderData); managers->getObjectManager()->render(renderData); haBuffer->render(managers, renderData); // doPick(); fbo->unbind(); renderScreenQuad(); } void Scene::renderScreenQuad() { RenderData renderData; renderData.projectionMatrix = Eigen::Matrix4f::Identity(); renderData.viewMatrix = Eigen::Matrix4f::Identity(); renderData.modelMatrix = Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix(); fbo->bindColorTexture(GL_TEXTURE0); // fbo->bindDepthTexture(GL_TEXTURE0); quad->getShaderProgram()->bind(); quad->getShaderProgram()->setUniform("textureSampler", 0); quad->renderImmediately(gl, managers, renderData); } void Scene::resize(int width, int height) { this->width = width; this->height = height; shouldResize = true; } void Scene::pick(int id, Eigen::Vector2f position) { pickingPosition = position; performPicking = true; pickingLabelId = id; } void Scene::doPick() { if (!performPicking) return; float depth = -2.0f; fbo->bindDepthTexture(GL_TEXTURE0); glAssert(gl->glReadPixels(pickingPosition.x(), height - pickingPosition.y() - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth)); Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f / width - 1.0f, pickingPosition.y() * -2.0f / height + 1.0f, depth * 2.0f - 1.0f, 1.0f); Eigen::Matrix4f viewProjection = camera.getProjectionMatrix() * camera.getViewMatrix(); Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC; positionWorld = positionWorld / positionWorld.w(); qWarning() << "picked:" << positionWorld; performPicking = false; auto label = labels->getById(pickingLabelId); label.anchorPosition = toVector3f(positionWorld); labels->update(label); } <commit_msg>Clear nodes in Scene destructor.<commit_after>#include "./scene.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <string> #include <vector> #include "./graphics/gl.h" #include "./input/invoke_manager.h" #include "./graphics/render_data.h" #include "./graphics/managers.h" #include "./graphics/volume_manager.h" #include "./graphics/shader_program.h" #include "./camera_controller.h" #include "./camera_rotation_controller.h" #include "./camera_zoom_controller.h" #include "./camera_move_controller.h" #include "./nodes.h" #include "./forces/labeller_frame_data.h" #include "./label_node.h" #include "./eigen_qdebug.h" #include "./utils/path_helper.h" Scene::Scene(std::shared_ptr<InvokeManager> invokeManager, std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels, std::shared_ptr<Forces::Labeller> labeller) : nodes(nodes), labels(labels), labeller(labeller), frustumOptimizer(nodes) { cameraController = std::make_shared<CameraController>(camera); cameraRotationController = std::make_shared<CameraRotationController>(camera); cameraZoomController = std::make_shared<CameraZoomController>(camera); cameraMoveController = std::make_shared<CameraMoveController>(camera); invokeManager->addHandler("cam", cameraController.get()); invokeManager->addHandler("cameraRotation", cameraRotationController.get()); invokeManager->addHandler("cameraZoom", cameraZoomController.get()); invokeManager->addHandler("cameraMove", cameraMoveController.get()); fbo = std::unique_ptr<Graphics::FrameBufferObject>( new Graphics::FrameBufferObject()); managers = std::make_shared<Graphics::Managers>(); } Scene::~Scene() { nodes->clear(); qInfo() << "Destructor of Scene" << "Remaining managers instances" << managers.use_count(); } void Scene::initialize() { glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f)); quad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/textureForRenderBuffer.frag"); fbo->initialize(gl, width, height); haBuffer = std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height)); managers->getShaderManager()->initialize(gl, haBuffer); Graphics::VolumeManager::instance->initialize(gl); managers->getObjectManager()->initialize(gl, 128, 10000000); haBuffer->initialize(gl, managers); quad->initialize(gl, managers); managers->getTextureManager()->initialize(gl, true, 8); } void Scene::update(double frameTime, QSet<Qt::Key> keysPressed) { this->frameTime = frameTime; cameraController->setFrameTime(frameTime); cameraRotationController->setFrameTime(frameTime); cameraZoomController->setFrameTime(frameTime); cameraMoveController->setFrameTime(frameTime); frustumOptimizer.update(camera.getViewMatrix()); camera.updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); auto newPositions = labeller->update(Forces::LabellerFrameData( frameTime, camera.getProjectionMatrix(), camera.getViewMatrix())); for (auto &labelNode : nodes->getLabelNodes()) { labelNode->labelPosition = newPositions[labelNode->label.id]; } } void Scene::render() { if (shouldResize) { camera.resize(width, height); fbo->resize(width, height); shouldResize = false; } glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); fbo->bind(); glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); RenderData renderData; renderData.projectionMatrix = camera.getProjectionMatrix(); renderData.viewMatrix = camera.getViewMatrix(); renderData.cameraPosition = camera.getPosition(); renderData.modelMatrix = Eigen::Matrix4f::Identity(); haBuffer->clearAndPrepare(managers); nodes->render(gl, managers, renderData); managers->getObjectManager()->render(renderData); haBuffer->render(managers, renderData); // doPick(); fbo->unbind(); renderScreenQuad(); } void Scene::renderScreenQuad() { RenderData renderData; renderData.projectionMatrix = Eigen::Matrix4f::Identity(); renderData.viewMatrix = Eigen::Matrix4f::Identity(); renderData.modelMatrix = Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix(); fbo->bindColorTexture(GL_TEXTURE0); // fbo->bindDepthTexture(GL_TEXTURE0); quad->getShaderProgram()->bind(); quad->getShaderProgram()->setUniform("textureSampler", 0); quad->renderImmediately(gl, managers, renderData); } void Scene::resize(int width, int height) { this->width = width; this->height = height; shouldResize = true; } void Scene::pick(int id, Eigen::Vector2f position) { pickingPosition = position; performPicking = true; pickingLabelId = id; } void Scene::doPick() { if (!performPicking) return; float depth = -2.0f; fbo->bindDepthTexture(GL_TEXTURE0); glAssert(gl->glReadPixels(pickingPosition.x(), height - pickingPosition.y() - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth)); Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f / width - 1.0f, pickingPosition.y() * -2.0f / height + 1.0f, depth * 2.0f - 1.0f, 1.0f); Eigen::Matrix4f viewProjection = camera.getProjectionMatrix() * camera.getViewMatrix(); Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC; positionWorld = positionWorld / positionWorld.w(); qWarning() << "picked:" << positionWorld; performPicking = false; auto label = labels->getById(pickingLabelId); label.anchorPosition = toVector3f(positionWorld); labels->update(label); } <|endoftext|>
<commit_before>#if _WIN32 #pragma warning(disable : 4522 4996 4267) #endif #include "./scene.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <string> #include <vector> #include <map> #include "./graphics/gl.h" #include "./input/invoke_manager.h" #include "./graphics/render_data.h" #include "./graphics/managers.h" #include "./graphics/volume_manager.h" #include "./graphics/shader_program.h" #include "./graphics/buffer_drawer.h" #include "./camera_controllers.h" #include "./nodes.h" #include "./camera_node.h" #include "./label_node.h" #include "./eigen_qdebug.h" #include "./utils/path_helper.h" #include "./placement/distance_transform.h" #include "./placement/apollonius.h" #include "./texture_mapper_manager.h" #include "./constraint_buffer_object.h" #include "./labelling_coordinator.h" #include "./recording_automation.h" Scene::Scene(int layerCount, std::shared_ptr<InvokeManager> invokeManager, std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels, std::shared_ptr<LabellingCoordinator> labellingCoordinator, std::shared_ptr<TextureMapperManager> textureMapperManager, std::shared_ptr<RecordingAutomation> recordingAutomation) : nodes(nodes), labels(labels), labellingCoordinator(labellingCoordinator), frustumOptimizer(nodes), textureMapperManager(textureMapperManager), recordingAutomation(recordingAutomation) { cameraControllers = std::make_shared<CameraControllers>(invokeManager, getCamera()); fbo = std::make_shared<Graphics::FrameBufferObject>(layerCount); constraintBufferObject = std::make_shared<ConstraintBufferObject>(); managers = std::make_shared<Graphics::Managers>(); } Scene::~Scene() { nodes->clearForShutdown(); qInfo() << "Destructor of Scene" << "Remaining managers instances" << managers.use_count(); } void Scene::initialize() { quad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/textureForRenderBuffer.frag"); screenQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/combineLayers.frag"); positionQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/positionRenderTarget.frag"); distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/distanceTransform.frag"); transparentQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/transparentOverlay.frag"); sliceQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/textureSlice.frag"); fbo->initialize(gl, width, height); picker = std::make_unique<Picker>(fbo, gl, labels, nodes); picker->resize(width, height); constraintBufferObject->initialize(gl, textureMapperManager->getBufferSize(), textureMapperManager->getBufferSize()); haBuffer = std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height)); managers->getShaderManager()->initialize(gl, haBuffer); managers->getObjectManager()->initialize(gl, 512, 10000000); quad->initialize(gl, managers); screenQuad->initialize(gl, managers); positionQuad->initialize(gl, managers); distanceTransformQuad->initialize(gl, managers); transparentQuad->initialize(gl, managers); sliceQuad->initialize(gl, managers); managers->getTextureManager()->initialize(gl, true, 8); haBuffer->initialize(gl, managers); textureMapperManager->createTextureMappersForLayers(fbo->getLayerCount()); textureMapperManager->resize(width, height); textureMapperManager->initialize(gl, fbo, constraintBufferObject); labellingCoordinator->initialize(gl, textureMapperManager->getBufferSize(), managers, textureMapperManager, width, height); recordingAutomation->initialize(gl); recordingAutomation->resize(width, height); } void Scene::cleanup() { labellingCoordinator->cleanup(); textureMapperManager->cleanup(); } void Scene::update(double frameTime) { auto camera = getCamera(); if (camera->needsResizing()) camera->resize(width, height); this->frameTime = frameTime; cameraControllers->update(camera, frameTime); frustumOptimizer.update(camera->getViewMatrix()); camera->updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); camera->updateAnimation(frameTime); haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); RenderData newRenderData = createRenderData(); bool isIdle = newRenderData.viewProjectionMatrix == renderData.viewProjectionMatrix; renderData = newRenderData; labellingCoordinator->update(frameTime, isIdle, camera->getProjectionMatrix(), camera->getViewMatrix(), activeLayerNumber); } void Scene::render() { qInfo() << "Scene::render"; auto camera = getCamera(); if (shouldResize) { camera->resize(width, height); fbo->resize(width, height); shouldResize = false; } glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClearColor(0.0f, 0.0f, 0.0f, 0.0f)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); renderNodesWithHABufferIntoFBO(); textureMapperManager->update(); constraintBufferObject->bind(); labellingCoordinator->updatePlacement(); constraintBufferObject->unbind(); glAssert(gl->glViewport(0, 0, width, height)); if (labellingEnabled) { fbo->bind(); glAssert(gl->glDisable(GL_DEPTH_TEST)); glAssert(gl->glEnable(GL_STENCIL_TEST)); nodes->renderLabels(gl, managers, renderData); glAssert(gl->glDisable(GL_STENCIL_TEST)); fbo->unbind(); } renderScreenQuad(); nodes->renderOverlays(gl, managers, renderData); if (showConstraintOverlay) { constraintBufferObject->bindTexture(GL_TEXTURE0); renderQuad(transparentQuad, Eigen::Matrix4f::Identity()); } if (showBufferDebuggingViews) renderDebuggingViews(renderData); glAssert(gl->glEnable(GL_DEPTH_TEST)); recordingAutomation->update(); } void Scene::renderNodesWithHABufferIntoFBO() { fbo->bind(); glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)); haBuffer->clearAndPrepare(managers); nodes->render(gl, managers, renderData); managers->getObjectManager()->render(renderData); std::vector<float> zValues = labellingCoordinator->updateClusters(); haBuffer->setLayerZValues(zValues, fbo->getLayerCount()); haBuffer->render(managers, renderData); picker->doPick(renderData.viewProjectionMatrix); fbo->unbind(); } void Scene::renderDebuggingViews(const RenderData &renderData) { fbo->bindColorTexture(GL_TEXTURE0); for (int i = 0; i < fbo->getLayerCount(); ++i) { auto transformation = Eigen::Affine3f( Eigen::Translation3f(Eigen::Vector3f(-0.8f + 0.4f * i, -0.4f, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderSliceIntoQuad(transformation.matrix(), i); } fbo->bindAccumulatedLayersTexture(GL_TEXTURE0); auto transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f( -0.8f + 0.4f * fbo->getLayerCount(), -0.4f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); fbo->bindDepthTexture(GL_TEXTURE0); transformation = Eigen::Affine3f( Eigen::Translation3f(Eigen::Vector3f(-0.8f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); textureMapperManager->bindOcclusionTexture(); transformation = Eigen::Affine3f( Eigen::Translation3f(Eigen::Vector3f(-0.4f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); textureMapperManager->bindSaliencyTexture(); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(distanceTransformQuad, transformation.matrix()); int layerIndex = activeLayerNumber == 0 ? 0 : activeLayerNumber - 1; if (layerIndex < fbo->getLayerCount()) textureMapperManager->bindApollonius(layerIndex); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); constraintBufferObject->bindTexture(GL_TEXTURE0); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); } void Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad, Eigen::Matrix4f modelMatrix) { RenderData renderData; renderData.modelMatrix = modelMatrix; quad->getShaderProgram()->bind(); quad->getShaderProgram()->setUniform("textureSampler", 0); quad->renderImmediately(gl, managers, renderData); } void Scene::renderSliceIntoQuad(Eigen::Matrix4f modelMatrix, int slice) { RenderData renderData; renderData.modelMatrix = modelMatrix; sliceQuad->getShaderProgram()->bind(); sliceQuad->getShaderProgram()->setUniform("textureSampler", 0); sliceQuad->getShaderProgram()->setUniform("slice", slice); sliceQuad->renderImmediately(gl, managers, renderData); } void Scene::renderScreenQuad() { if (activeLayerNumber == 0) { fbo->bindColorTexture(GL_TEXTURE0); screenQuad->getShaderProgram()->setUniform("layers", 0); /* screenQuad->getShaderProgram()->setUniform("layer2", 1); screenQuad->getShaderProgram()->setUniform("layer3", 2); screenQuad->getShaderProgram()->setUniform("layer4", 3); */ renderQuad(screenQuad, Eigen::Matrix4f::Identity()); gl->glActiveTexture(GL_TEXTURE0); } else if (activeLayerNumber == 9) { fbo->bindAccumulatedLayersTexture(GL_TEXTURE0); renderQuad(quad, Eigen::Matrix4f::Identity()); } else { fbo->bindColorTexture(GL_TEXTURE0); renderSliceIntoQuad(Eigen::Matrix4f::Identity(), activeLayerNumber - 1); } } void Scene::resize(int width, int height) { this->width = width; this->height = height; shouldResize = true; labellingCoordinator->resize(width, height); recordingAutomation->resize(width, height); } RenderData Scene::createRenderData() { auto camera = getCamera(); return RenderData(frameTime, camera->getProjectionMatrix(), camera->getViewMatrix(), camera->getPosition(), Eigen::Vector2f(width, height)); } void Scene::pick(int id, Eigen::Vector2f position) { if (picker.get()) picker->pick(id, position); } void Scene::enableBufferDebuggingViews(bool enable) { showBufferDebuggingViews = enable; } void Scene::enableConstraingOverlay(bool enable) { showConstraintOverlay = enable; } void Scene::enableLabelling(bool enable) { labellingEnabled = enable; labellingCoordinator->setEnabled(enable); } std::shared_ptr<Camera> Scene::getCamera() { return nodes->getCameraNode()->getCamera(); } void Scene::setRenderLayer(int layerNumber) { activeLayerNumber = layerNumber; } <commit_msg>Minor: remove commented out code.<commit_after>#if _WIN32 #pragma warning(disable : 4522 4996 4267) #endif #include "./scene.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <string> #include <vector> #include <map> #include "./graphics/gl.h" #include "./input/invoke_manager.h" #include "./graphics/render_data.h" #include "./graphics/managers.h" #include "./graphics/volume_manager.h" #include "./graphics/shader_program.h" #include "./graphics/buffer_drawer.h" #include "./camera_controllers.h" #include "./nodes.h" #include "./camera_node.h" #include "./label_node.h" #include "./eigen_qdebug.h" #include "./utils/path_helper.h" #include "./placement/distance_transform.h" #include "./placement/apollonius.h" #include "./texture_mapper_manager.h" #include "./constraint_buffer_object.h" #include "./labelling_coordinator.h" #include "./recording_automation.h" Scene::Scene(int layerCount, std::shared_ptr<InvokeManager> invokeManager, std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels, std::shared_ptr<LabellingCoordinator> labellingCoordinator, std::shared_ptr<TextureMapperManager> textureMapperManager, std::shared_ptr<RecordingAutomation> recordingAutomation) : nodes(nodes), labels(labels), labellingCoordinator(labellingCoordinator), frustumOptimizer(nodes), textureMapperManager(textureMapperManager), recordingAutomation(recordingAutomation) { cameraControllers = std::make_shared<CameraControllers>(invokeManager, getCamera()); fbo = std::make_shared<Graphics::FrameBufferObject>(layerCount); constraintBufferObject = std::make_shared<ConstraintBufferObject>(); managers = std::make_shared<Graphics::Managers>(); } Scene::~Scene() { nodes->clearForShutdown(); qInfo() << "Destructor of Scene" << "Remaining managers instances" << managers.use_count(); } void Scene::initialize() { quad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/textureForRenderBuffer.frag"); screenQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/combineLayers.frag"); positionQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/positionRenderTarget.frag"); distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/distanceTransform.frag"); transparentQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/transparentOverlay.frag"); sliceQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/textureSlice.frag"); fbo->initialize(gl, width, height); picker = std::make_unique<Picker>(fbo, gl, labels, nodes); picker->resize(width, height); constraintBufferObject->initialize(gl, textureMapperManager->getBufferSize(), textureMapperManager->getBufferSize()); haBuffer = std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height)); managers->getShaderManager()->initialize(gl, haBuffer); managers->getObjectManager()->initialize(gl, 512, 10000000); quad->initialize(gl, managers); screenQuad->initialize(gl, managers); positionQuad->initialize(gl, managers); distanceTransformQuad->initialize(gl, managers); transparentQuad->initialize(gl, managers); sliceQuad->initialize(gl, managers); managers->getTextureManager()->initialize(gl, true, 8); haBuffer->initialize(gl, managers); textureMapperManager->createTextureMappersForLayers(fbo->getLayerCount()); textureMapperManager->resize(width, height); textureMapperManager->initialize(gl, fbo, constraintBufferObject); labellingCoordinator->initialize(gl, textureMapperManager->getBufferSize(), managers, textureMapperManager, width, height); recordingAutomation->initialize(gl); recordingAutomation->resize(width, height); } void Scene::cleanup() { labellingCoordinator->cleanup(); textureMapperManager->cleanup(); } void Scene::update(double frameTime) { auto camera = getCamera(); if (camera->needsResizing()) camera->resize(width, height); this->frameTime = frameTime; cameraControllers->update(camera, frameTime); frustumOptimizer.update(camera->getViewMatrix()); camera->updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); camera->updateAnimation(frameTime); haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); RenderData newRenderData = createRenderData(); bool isIdle = newRenderData.viewProjectionMatrix == renderData.viewProjectionMatrix; renderData = newRenderData; labellingCoordinator->update(frameTime, isIdle, camera->getProjectionMatrix(), camera->getViewMatrix(), activeLayerNumber); } void Scene::render() { qInfo() << "Scene::render"; auto camera = getCamera(); if (shouldResize) { camera->resize(width, height); fbo->resize(width, height); shouldResize = false; } glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClearColor(0.0f, 0.0f, 0.0f, 0.0f)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); renderNodesWithHABufferIntoFBO(); textureMapperManager->update(); constraintBufferObject->bind(); labellingCoordinator->updatePlacement(); constraintBufferObject->unbind(); glAssert(gl->glViewport(0, 0, width, height)); if (labellingEnabled) { fbo->bind(); glAssert(gl->glDisable(GL_DEPTH_TEST)); glAssert(gl->glEnable(GL_STENCIL_TEST)); nodes->renderLabels(gl, managers, renderData); glAssert(gl->glDisable(GL_STENCIL_TEST)); fbo->unbind(); } renderScreenQuad(); nodes->renderOverlays(gl, managers, renderData); if (showConstraintOverlay) { constraintBufferObject->bindTexture(GL_TEXTURE0); renderQuad(transparentQuad, Eigen::Matrix4f::Identity()); } if (showBufferDebuggingViews) renderDebuggingViews(renderData); glAssert(gl->glEnable(GL_DEPTH_TEST)); recordingAutomation->update(); } void Scene::renderNodesWithHABufferIntoFBO() { fbo->bind(); glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)); haBuffer->clearAndPrepare(managers); nodes->render(gl, managers, renderData); managers->getObjectManager()->render(renderData); std::vector<float> zValues = labellingCoordinator->updateClusters(); haBuffer->setLayerZValues(zValues, fbo->getLayerCount()); haBuffer->render(managers, renderData); picker->doPick(renderData.viewProjectionMatrix); fbo->unbind(); } void Scene::renderDebuggingViews(const RenderData &renderData) { fbo->bindColorTexture(GL_TEXTURE0); for (int i = 0; i < fbo->getLayerCount(); ++i) { auto transformation = Eigen::Affine3f( Eigen::Translation3f(Eigen::Vector3f(-0.8f + 0.4f * i, -0.4f, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderSliceIntoQuad(transformation.matrix(), i); } fbo->bindAccumulatedLayersTexture(GL_TEXTURE0); auto transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f( -0.8f + 0.4f * fbo->getLayerCount(), -0.4f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); fbo->bindDepthTexture(GL_TEXTURE0); transformation = Eigen::Affine3f( Eigen::Translation3f(Eigen::Vector3f(-0.8f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); textureMapperManager->bindOcclusionTexture(); transformation = Eigen::Affine3f( Eigen::Translation3f(Eigen::Vector3f(-0.4f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); textureMapperManager->bindSaliencyTexture(); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(distanceTransformQuad, transformation.matrix()); int layerIndex = activeLayerNumber == 0 ? 0 : activeLayerNumber - 1; if (layerIndex < fbo->getLayerCount()) textureMapperManager->bindApollonius(layerIndex); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); constraintBufferObject->bindTexture(GL_TEXTURE0); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8f, -0.8f, 0.0f)) * Eigen::Scaling(Eigen::Vector3f(0.2f, 0.2f, 1.0f))); renderQuad(quad, transformation.matrix()); } void Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad, Eigen::Matrix4f modelMatrix) { RenderData renderData; renderData.modelMatrix = modelMatrix; quad->getShaderProgram()->bind(); quad->getShaderProgram()->setUniform("textureSampler", 0); quad->renderImmediately(gl, managers, renderData); } void Scene::renderSliceIntoQuad(Eigen::Matrix4f modelMatrix, int slice) { RenderData renderData; renderData.modelMatrix = modelMatrix; sliceQuad->getShaderProgram()->bind(); sliceQuad->getShaderProgram()->setUniform("textureSampler", 0); sliceQuad->getShaderProgram()->setUniform("slice", slice); sliceQuad->renderImmediately(gl, managers, renderData); } void Scene::renderScreenQuad() { if (activeLayerNumber == 0) { fbo->bindColorTexture(GL_TEXTURE0); screenQuad->getShaderProgram()->setUniform("layers", 0); renderQuad(screenQuad, Eigen::Matrix4f::Identity()); gl->glActiveTexture(GL_TEXTURE0); } else if (activeLayerNumber == 9) { fbo->bindAccumulatedLayersTexture(GL_TEXTURE0); renderQuad(quad, Eigen::Matrix4f::Identity()); } else { fbo->bindColorTexture(GL_TEXTURE0); renderSliceIntoQuad(Eigen::Matrix4f::Identity(), activeLayerNumber - 1); } } void Scene::resize(int width, int height) { this->width = width; this->height = height; shouldResize = true; labellingCoordinator->resize(width, height); recordingAutomation->resize(width, height); } RenderData Scene::createRenderData() { auto camera = getCamera(); return RenderData(frameTime, camera->getProjectionMatrix(), camera->getViewMatrix(), camera->getPosition(), Eigen::Vector2f(width, height)); } void Scene::pick(int id, Eigen::Vector2f position) { if (picker.get()) picker->pick(id, position); } void Scene::enableBufferDebuggingViews(bool enable) { showBufferDebuggingViews = enable; } void Scene::enableConstraingOverlay(bool enable) { showConstraintOverlay = enable; } void Scene::enableLabelling(bool enable) { labellingEnabled = enable; labellingCoordinator->setEnabled(enable); } std::shared_ptr<Camera> Scene::getCamera() { return nodes->getCameraNode()->getCamera(); } void Scene::setRenderLayer(int layerNumber) { activeLayerNumber = layerNumber; } <|endoftext|>
<commit_before>#include "defs.h" #include "search.h" #include "eval.h" #include "movegen.h" #include "transptable.h" #include <string> #include <ostream> #include <time.h> #include <iostream> Search::Search(const Board& board, int depth, int maxTime, bool logUci) { _logUci = logUci; _iterDeep(board, depth, maxTime); } void Search::_iterDeep(const Board& board, int depth, int maxTime) { _tt.clear(); int timeRemaining = maxTime; clock_t startTime; for(int i=1;i<=depth;i++) { startTime = clock(); _rootMax(board, i); clock_t timeTaken = clock() - startTime; timeRemaining -= (float(timeTaken) / CLOCKS_PER_SEC)*1000; getPv(board); // Log UCI info about this iteration if (_logUci) { std::string pvString; for(auto move : getPv(board)) { pvString += move.getNotation() + " "; } std::cout << "info depth " + std::to_string(i) + " "; std::cout << "score cp " + std::to_string(_bestScore) + " "; std::cout << "pv " + pvString; std::cout << std::endl; } if (timeRemaining < 0) { return; } } } MoveList Search::getPv(const Board& board) { if (!_tt.contains(board.getZKey())) { return MoveList(); } int scoreToFind = -_tt.getScore(board.getZKey()); ZKey movedZKey; for (auto moveBoard : MoveGen(board).getLegalMoves()) { CMove move = moveBoard.first; Board movedBoard = moveBoard.second; movedZKey = movedBoard.getZKey(); if (_tt.contains(movedZKey) && _tt.getScore(movedZKey) == scoreToFind) { MoveList pvList = getPv(movedBoard); pvList.insert(pvList.begin(), move); return pvList; } } return MoveList(); } CMove Search::getBestMove() { return _bestMove; } void Search::_rootMax(const Board& board, int depth) { MoveGen movegen(board); MoveBoardList legalMoves = movegen.getLegalMoves(); int bestScore = -INF; int currScore; CMove bestMove; for (auto moveBoard : legalMoves) { CMove move = moveBoard.first; Board movedBoard = moveBoard.second; currScore = -_negaMax(movedBoard, depth-1, -INF, INF); if (currScore > bestScore) { bestMove = move; bestScore = currScore; } } // If we couldn't find a path other than checkmate, just pick the first legal move if (bestMove.getFlags() & CMove::NULL_MOVE) { bestMove = legalMoves.at(0).first; } _tt.set(board.getZKey(), bestScore, depth, TranspTable::EXACT); _bestMove = bestMove; _bestScore = bestScore; } int Search::_negaMax(const Board& board, int depth, int alpha, int beta) { int alphaOrig = alpha; ZKey zKey = board.getZKey(); // Check transposition table cache if (_tt.contains(zKey) && (_tt.getDepth(zKey) >= depth)) { switch(_tt.getFlag(zKey)) { case TranspTable::EXACT: return _tt.getScore(zKey); case TranspTable::UPPER_BOUND: alpha = std::max(alpha, _tt.getScore(zKey)); break; case TranspTable::LOWER_BOUND: beta = std::min(beta, _tt.getScore(zKey)); break; } if (alpha > beta) { return _tt.getScore(zKey); } } MoveGen movegen(board); MoveBoardList legalMoves = movegen.getLegalMoves(); // Check for checkmate if (legalMoves.size() == 0 && board.colorIsInCheck(board.getActivePlayer())) { _tt.set(board.getZKey(), -INF, depth, TranspTable::EXACT); return -INF; } // Eval if depth is 0 if (depth == 0) { int score = Eval(board, board.getActivePlayer()).getScore(); _tt.set(board.getZKey(), score, 0, TranspTable::EXACT); return score; } int bestScore = -INF; for (auto moveBoard : legalMoves) { Board movedBoard = moveBoard.second; bestScore = std::max(bestScore, -_negaMax(movedBoard, depth-1, -beta, -alpha)); alpha = std::max(alpha, bestScore); if (alpha > beta) { break; } } // Store bestScore in transposition table TranspTable::Flag flag; if (bestScore < alphaOrig) { flag = TranspTable::UPPER_BOUND; } else if (bestScore >= beta) { flag = TranspTable::LOWER_BOUND; } else { flag = TranspTable::EXACT; } _tt.set(zKey, bestScore, depth, flag); return bestScore; } <commit_msg>UCI log n moves to checkmate information<commit_after>#include "defs.h" #include "search.h" #include "eval.h" #include "movegen.h" #include "transptable.h" #include <string> #include <ostream> #include <time.h> #include <iostream> Search::Search(const Board& board, int depth, int maxTime, bool logUci) { _logUci = logUci; _iterDeep(board, depth, maxTime); } void Search::_iterDeep(const Board& board, int depth, int maxTime) { _tt.clear(); int timeRemaining = maxTime; clock_t startTime; for(int i=1;i<=depth;i++) { startTime = clock(); _rootMax(board, i); clock_t timeTaken = clock() - startTime; timeRemaining -= (float(timeTaken) / CLOCKS_PER_SEC)*1000; // Log UCI info about this iteration if (_logUci) { std::string pvString; MoveList pv = getPv(board); for(auto move : pv) { pvString += move.getNotation() + " "; } std::string scoreString; if (_bestScore == INF) { scoreString = "mate " + std::to_string(pv.size()); } else if (_bestScore == -INF) { scoreString = "mate -" + std::to_string(pv.size()); } else { scoreString = "cp " + std::to_string(_bestScore); } std::cout << "info depth " + std::to_string(i) + " "; std::cout << "score " + scoreString + " "; std::cout << "pv " + pvString; std::cout << std::endl; } if (timeRemaining < 0) { return; } } } MoveList Search::getPv(const Board& board) { if (!_tt.contains(board.getZKey())) { return MoveList(); } int scoreToFind = -_tt.getScore(board.getZKey()); ZKey movedZKey; for (auto moveBoard : MoveGen(board).getLegalMoves()) { CMove move = moveBoard.first; Board movedBoard = moveBoard.second; movedZKey = movedBoard.getZKey(); if (_tt.contains(movedZKey) && _tt.getScore(movedZKey) == scoreToFind) { MoveList pvList = getPv(movedBoard); pvList.insert(pvList.begin(), move); return pvList; } } return MoveList(); } CMove Search::getBestMove() { return _bestMove; } void Search::_rootMax(const Board& board, int depth) { MoveGen movegen(board); MoveBoardList legalMoves = movegen.getLegalMoves(); int bestScore = -INF; int currScore; CMove bestMove; for (auto moveBoard : legalMoves) { CMove move = moveBoard.first; Board movedBoard = moveBoard.second; currScore = -_negaMax(movedBoard, depth-1, -INF, INF); if (currScore > bestScore) { bestMove = move; bestScore = currScore; } } // If we couldn't find a path other than checkmate, just pick the first legal move if (bestMove.getFlags() & CMove::NULL_MOVE) { bestMove = legalMoves.at(0).first; } _tt.set(board.getZKey(), bestScore, depth, TranspTable::EXACT); _bestMove = bestMove; _bestScore = bestScore; } int Search::_negaMax(const Board& board, int depth, int alpha, int beta) { int alphaOrig = alpha; ZKey zKey = board.getZKey(); // Check transposition table cache if (_tt.contains(zKey) && (_tt.getDepth(zKey) >= depth)) { switch(_tt.getFlag(zKey)) { case TranspTable::EXACT: return _tt.getScore(zKey); case TranspTable::UPPER_BOUND: alpha = std::max(alpha, _tt.getScore(zKey)); break; case TranspTable::LOWER_BOUND: beta = std::min(beta, _tt.getScore(zKey)); break; } if (alpha > beta) { return _tt.getScore(zKey); } } MoveGen movegen(board); MoveBoardList legalMoves = movegen.getLegalMoves(); // Check for checkmate if (legalMoves.size() == 0 && board.colorIsInCheck(board.getActivePlayer())) { _tt.set(board.getZKey(), -INF, depth, TranspTable::EXACT); return -INF; } // Eval if depth is 0 if (depth == 0) { int score = Eval(board, board.getActivePlayer()).getScore(); _tt.set(board.getZKey(), score, 0, TranspTable::EXACT); return score; } int bestScore = -INF; for (auto moveBoard : legalMoves) { Board movedBoard = moveBoard.second; bestScore = std::max(bestScore, -_negaMax(movedBoard, depth-1, -beta, -alpha)); alpha = std::max(alpha, bestScore); if (alpha > beta) { break; } } // Store bestScore in transposition table TranspTable::Flag flag; if (bestScore < alphaOrig) { flag = TranspTable::UPPER_BOUND; } else if (bestScore >= beta) { flag = TranspTable::LOWER_BOUND; } else { flag = TranspTable::EXACT; } _tt.set(zKey, bestScore, depth, flag); return bestScore; } <|endoftext|>
<commit_before>// Copyright (c) 2014-2016 The Dash developers // Copyright (c) 2016-2020 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "spork.h" #include "messagesigner.h" #include "net.h" #include "netmessagemaker.h" #include "net_processing.h" #include "sporkdb.h" #include "validation.h" #include <iostream> #define MAKE_SPORK_DEF(name, defaultValue) CSporkDef(name, defaultValue, #name) std::vector<CSporkDef> sporkDefs = { MAKE_SPORK_DEF(SPORK_5_MAX_VALUE, 1000), // 1000 PIV MAKE_SPORK_DEF(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_13_ENABLE_SUPERBLOCKS, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_14_NEW_PROTOCOL_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_16_ZEROCOIN_MAINTENANCE_MODE, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_18_ZEROCOIN_PUBLICSPEND_V4, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_19_COLDSTAKING_MAINTENANCE, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_20_SAPLING_MAINTENANCE, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_21_LEGACY_MNS_MAX_HEIGHT, 4070908800ULL), // OFF }; CSporkManager sporkManager; std::map<uint256, CSporkMessage> mapSporks; CSporkManager::CSporkManager() { for (auto& sporkDef : sporkDefs) { sporkDefsById.emplace(sporkDef.sporkId, &sporkDef); sporkDefsByName.emplace(sporkDef.name, &sporkDef); } } void CSporkManager::Clear() { strMasterPrivKey = ""; mapSporksActive.clear(); } // PIVX: on startup load spork values from previous session if they exist in the sporkDB void CSporkManager::LoadSporksFromDB() { for (const auto& sporkDef : sporkDefs) { // attempt to read spork from sporkDB CSporkMessage spork; if (!pSporkDB->ReadSpork(sporkDef.sporkId, spork)) { LogPrintf("%s : no previous value for %s found in database\n", __func__, sporkDef.name); continue; } // TODO: Temporary workaround for v5.0 clients to ensure up-to-date protocol version spork if (spork.nSporkID == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) { LogPrintf("%s : Spork 15 signed at %d\n", __func__, spork.nTimeSigned); // 1578338986 is the timestamp that spork 15 was last signed at for mainnet for the previous // protocol bump. If the timestamp in the DB is equal or lower than this, we know that // the value is stale and should ignore it to prevent un-necessary disconnections in the // version handshake process. This value is also suitable for testnet as the timestamp // for this spork on that network was signed shortly after this. if (spork.nTimeSigned <= 1578338986 ) { LogPrintf("%s : Stale spork 15 detected, clearing...\n", __func__); CSporkManager::Clear(); return; } } // add spork to memory mapSporks[spork.GetHash()] = spork; mapSporksActive[spork.nSporkID] = spork; std::time_t result = spork.nValue; // If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format std::string sporkName = sporkManager.GetSporkNameByID(spork.nSporkID); if (spork.nValue > 1000000) { char* res = std::ctime(&result); LogPrintf("%s : loaded spork %s with value %d : %s\n", __func__, sporkName.c_str(), spork.nValue, ((res) ? res : "no time") ); } else { LogPrintf("%s : loaded spork %s with value %d\n", __func__, sporkName, spork.nValue); } } } void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (fLiteMode) return; // disable all masternode related functionality if (strCommand == NetMsgType::SPORK) { int banScore = ProcessSporkMsg(vRecv); if (banScore > 0) { LOCK(cs_main); Misbehaving(pfrom->GetId(), banScore); } } if (strCommand == NetMsgType::GETSPORKS) { ProcessGetSporks(pfrom, strCommand, vRecv); } } int CSporkManager::ProcessSporkMsg(CDataStream& vRecv) { CSporkMessage spork; vRecv >> spork; return ProcessSporkMsg(spork); } int CSporkManager::ProcessSporkMsg(CSporkMessage& spork) { // Ignore spork messages about unknown/deleted sporks std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID); if (strSpork == "Unknown") return 0; // Do not accept sporks signed way too far into the future if (spork.nTimeSigned > GetAdjustedTime() + 2 * 60 * 60) { LogPrint(BCLog::SPORKS, "%s : ERROR: too far into the future\n", __func__); return 100; } // reject old signature version if (spork.nMessVersion != MessageVersion::MESS_VER_HASH) { LogPrint(BCLog::SPORKS, "%s : nMessVersion=%d not accepted anymore\n", __func__, spork.nMessVersion); return 0; } uint256 hash = spork.GetHash(); std::string sporkName = sporkManager.GetSporkNameByID(spork.nSporkID); std::string strStatus; { LOCK(cs); if (mapSporksActive.count(spork.nSporkID)) { // spork is active if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) { // spork in memory has been signed more recently LogPrint(BCLog::SPORKS, "%s : spork %d (%s) in memory is more recent: %d >= %d\n", __func__, spork.nSporkID, sporkName, mapSporksActive[spork.nSporkID].nTimeSigned, spork.nTimeSigned); return 0; } else { // update active spork strStatus = "updated"; } } else { // spork is not active strStatus = "new"; } } const bool fRequireNew = spork.nTimeSigned >= Params().GetConsensus().nTime_EnforceNewSporkKey; bool fValidSig = spork.CheckSignature(spork.GetPublicKey().GetID()); if (!fValidSig && !fRequireNew) { // See if window is open that allows for old spork key to sign messages if (GetAdjustedTime() < Params().GetConsensus().nTime_RejectOldSporkKey) { CPubKey pubkeyold = spork.GetPublicKeyOld(); fValidSig = spork.CheckSignature(pubkeyold.GetID()); } } if (!fValidSig) { LogPrint(BCLog::SPORKS, "%s : Invalid Signature\n", __func__); return 100; } // Log valid spork value change LogPrintf("%s : got %s spork %d (%s) with value %d (signed at %d)\n", __func__, strStatus, spork.nSporkID, sporkName, spork.nValue, spork.nTimeSigned); { LOCK(cs); mapSporks[hash] = spork; mapSporksActive[spork.nSporkID] = spork; } spork.Relay(); // PIVX: add to spork database. pSporkDB->WriteSpork(spork.nSporkID, spork); // All good. return 0; } void CSporkManager::ProcessGetSporks(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { LOCK(cs); std::map<SporkId, CSporkMessage>::iterator it = mapSporksActive.begin(); while (it != mapSporksActive.end()) { g_connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SPORK, it->second)); it++; } // end message if (Params().IsRegTestNet()) { // For now, only use it on regtest. CSporkMessage msg(SPORK_INVALID, 0, 0); g_connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SPORK, msg)); } } bool CSporkManager::UpdateSpork(SporkId nSporkID, int64_t nValue) { CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetTime()); if(spork.Sign(strMasterPrivKey)){ spork.Relay(); AddSporkMessage(spork); return true; } return false; } void CSporkManager::AddSporkMessage(const CSporkMessage& spork) { LOCK(cs); mapSporks[spork.GetHash()] = spork; mapSporksActive[spork.nSporkID] = spork; } // grab the spork value, and see if it's off bool CSporkManager::IsSporkActive(SporkId nSporkID) { return GetSporkValue(nSporkID) < GetAdjustedTime(); } // grab the value of the spork on the network, or the default int64_t CSporkManager::GetSporkValue(SporkId nSporkID) { LOCK(cs); if (mapSporksActive.count(nSporkID)) { return mapSporksActive[nSporkID].nValue; } else { auto it = sporkDefsById.find(nSporkID); if (it != sporkDefsById.end()) { return it->second->defaultValue; } else { LogPrintf("%s : Unknown Spork %d\n", __func__, nSporkID); } } return -1; } SporkId CSporkManager::GetSporkIDByName(std::string strName) { auto it = sporkDefsByName.find(strName); if (it == sporkDefsByName.end()) { LogPrintf("%s : Unknown Spork name '%s'\n", __func__, strName); return SPORK_INVALID; } return it->second->sporkId; } std::string CSporkManager::GetSporkNameByID(SporkId nSporkID) { auto it = sporkDefsById.find(nSporkID); if (it == sporkDefsById.end()) { LogPrint(BCLog::SPORKS, "%s : Unknown Spork ID %d\n", __func__, nSporkID); return "Unknown"; } return it->second->name; } bool CSporkManager::SetPrivKey(std::string strPrivKey) { CSporkMessage spork; spork.Sign(strPrivKey); bool fValidSig = spork.CheckSignature(spork.GetPublicKey().GetID()); if (!fValidSig) { // See if window is open that allows for old spork key to sign messages if (GetAdjustedTime() < Params().GetConsensus().nTime_RejectOldSporkKey) { CPubKey pubkeyold = spork.GetPublicKeyOld(); fValidSig = spork.CheckSignature(pubkeyold.GetID()); } } if (fValidSig) { LOCK(cs); // Test signing successful, proceed LogPrintf("%s : Successfully initialized as spork signer\n", __func__); strMasterPrivKey = strPrivKey; return true; } return false; } std::string CSporkManager::ToString() const { LOCK(cs); return strprintf("Sporks: %llu", mapSporksActive.size()); } uint256 CSporkMessage::GetSignatureHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << nMessVersion; ss << nSporkID; ss << nValue; ss << nTimeSigned; return ss.GetHash(); } std::string CSporkMessage::GetStrMessage() const { return std::to_string(nSporkID) + std::to_string(nValue) + std::to_string(nTimeSigned); } const CPubKey CSporkMessage::GetPublicKey() const { return CPubKey(ParseHex(Params().GetConsensus().strSporkPubKey)); } const CPubKey CSporkMessage::GetPublicKeyOld() const { return CPubKey(ParseHex(Params().GetConsensus().strSporkPubKeyOld)); } void CSporkMessage::Relay() { CInv inv(MSG_SPORK, GetHash()); g_connman->RelayInv(inv); } <commit_msg>[Refactoring] Use AddSporkMessage globally for maps update<commit_after>// Copyright (c) 2014-2016 The Dash developers // Copyright (c) 2016-2020 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "spork.h" #include "messagesigner.h" #include "net.h" #include "netmessagemaker.h" #include "net_processing.h" #include "sporkdb.h" #include "validation.h" #include <iostream> #define MAKE_SPORK_DEF(name, defaultValue) CSporkDef(name, defaultValue, #name) std::vector<CSporkDef> sporkDefs = { MAKE_SPORK_DEF(SPORK_5_MAX_VALUE, 1000), // 1000 PIV MAKE_SPORK_DEF(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_13_ENABLE_SUPERBLOCKS, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_14_NEW_PROTOCOL_ENFORCEMENT, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_16_ZEROCOIN_MAINTENANCE_MODE, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_18_ZEROCOIN_PUBLICSPEND_V4, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_19_COLDSTAKING_MAINTENANCE, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_20_SAPLING_MAINTENANCE, 4070908800ULL), // OFF MAKE_SPORK_DEF(SPORK_21_LEGACY_MNS_MAX_HEIGHT, 4070908800ULL), // OFF }; CSporkManager sporkManager; std::map<uint256, CSporkMessage> mapSporks; CSporkManager::CSporkManager() { for (auto& sporkDef : sporkDefs) { sporkDefsById.emplace(sporkDef.sporkId, &sporkDef); sporkDefsByName.emplace(sporkDef.name, &sporkDef); } } void CSporkManager::Clear() { strMasterPrivKey = ""; mapSporksActive.clear(); } // PIVX: on startup load spork values from previous session if they exist in the sporkDB void CSporkManager::LoadSporksFromDB() { for (const auto& sporkDef : sporkDefs) { // attempt to read spork from sporkDB CSporkMessage spork; if (!pSporkDB->ReadSpork(sporkDef.sporkId, spork)) { LogPrintf("%s : no previous value for %s found in database\n", __func__, sporkDef.name); continue; } // TODO: Temporary workaround for v5.0 clients to ensure up-to-date protocol version spork if (spork.nSporkID == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) { LogPrintf("%s : Spork 15 signed at %d\n", __func__, spork.nTimeSigned); // 1578338986 is the timestamp that spork 15 was last signed at for mainnet for the previous // protocol bump. If the timestamp in the DB is equal or lower than this, we know that // the value is stale and should ignore it to prevent un-necessary disconnections in the // version handshake process. This value is also suitable for testnet as the timestamp // for this spork on that network was signed shortly after this. if (spork.nTimeSigned <= 1578338986 ) { LogPrintf("%s : Stale spork 15 detected, clearing...\n", __func__); CSporkManager::Clear(); return; } } // add spork to memory AddSporkMessage(spork); mapSporks[spork.GetHash()] = spork; mapSporksActive[spork.nSporkID] = spork; std::time_t result = spork.nValue; // If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format std::string sporkName = sporkManager.GetSporkNameByID(spork.nSporkID); if (spork.nValue > 1000000) { char* res = std::ctime(&result); LogPrintf("%s : loaded spork %s with value %d : %s\n", __func__, sporkName.c_str(), spork.nValue, ((res) ? res : "no time") ); } else { LogPrintf("%s : loaded spork %s with value %d\n", __func__, sporkName, spork.nValue); } } } void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (fLiteMode) return; // disable all masternode related functionality if (strCommand == NetMsgType::SPORK) { int banScore = ProcessSporkMsg(vRecv); if (banScore > 0) { LOCK(cs_main); Misbehaving(pfrom->GetId(), banScore); } } if (strCommand == NetMsgType::GETSPORKS) { ProcessGetSporks(pfrom, strCommand, vRecv); } } int CSporkManager::ProcessSporkMsg(CDataStream& vRecv) { CSporkMessage spork; vRecv >> spork; return ProcessSporkMsg(spork); } int CSporkManager::ProcessSporkMsg(CSporkMessage& spork) { // Ignore spork messages about unknown/deleted sporks std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID); if (strSpork == "Unknown") return 0; // Do not accept sporks signed way too far into the future if (spork.nTimeSigned > GetAdjustedTime() + 2 * 60 * 60) { LogPrint(BCLog::SPORKS, "%s : ERROR: too far into the future\n", __func__); return 100; } // reject old signature version if (spork.nMessVersion != MessageVersion::MESS_VER_HASH) { LogPrint(BCLog::SPORKS, "%s : nMessVersion=%d not accepted anymore\n", __func__, spork.nMessVersion); return 0; } std::string sporkName = sporkManager.GetSporkNameByID(spork.nSporkID); std::string strStatus; { LOCK(cs); if (mapSporksActive.count(spork.nSporkID)) { // spork is active if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) { // spork in memory has been signed more recently LogPrint(BCLog::SPORKS, "%s : spork %d (%s) in memory is more recent: %d >= %d\n", __func__, spork.nSporkID, sporkName, mapSporksActive[spork.nSporkID].nTimeSigned, spork.nTimeSigned); return 0; } else { // update active spork strStatus = "updated"; } } else { // spork is not active strStatus = "new"; } } const bool fRequireNew = spork.nTimeSigned >= Params().GetConsensus().nTime_EnforceNewSporkKey; bool fValidSig = spork.CheckSignature(spork.GetPublicKey().GetID()); if (!fValidSig && !fRequireNew) { // See if window is open that allows for old spork key to sign messages if (GetAdjustedTime() < Params().GetConsensus().nTime_RejectOldSporkKey) { CPubKey pubkeyold = spork.GetPublicKeyOld(); fValidSig = spork.CheckSignature(pubkeyold.GetID()); } } if (!fValidSig) { LogPrint(BCLog::SPORKS, "%s : Invalid Signature\n", __func__); return 100; } // Log valid spork value change LogPrintf("%s : got %s spork %d (%s) with value %d (signed at %d)\n", __func__, strStatus, spork.nSporkID, sporkName, spork.nValue, spork.nTimeSigned); AddSporkMessage(spork); spork.Relay(); // PIVX: add to spork database. pSporkDB->WriteSpork(spork.nSporkID, spork); // All good. return 0; } void CSporkManager::ProcessGetSporks(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { LOCK(cs); std::map<SporkId, CSporkMessage>::iterator it = mapSporksActive.begin(); while (it != mapSporksActive.end()) { g_connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SPORK, it->second)); it++; } // end message if (Params().IsRegTestNet()) { // For now, only use it on regtest. CSporkMessage msg(SPORK_INVALID, 0, 0); g_connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SPORK, msg)); } } bool CSporkManager::UpdateSpork(SporkId nSporkID, int64_t nValue) { CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetTime()); if(spork.Sign(strMasterPrivKey)){ spork.Relay(); AddSporkMessage(spork); return true; } return false; } void CSporkManager::AddSporkMessage(const CSporkMessage& spork) { LOCK(cs); mapSporks[spork.GetHash()] = spork; mapSporksActive[spork.nSporkID] = spork; } // grab the spork value, and see if it's off bool CSporkManager::IsSporkActive(SporkId nSporkID) { return GetSporkValue(nSporkID) < GetAdjustedTime(); } // grab the value of the spork on the network, or the default int64_t CSporkManager::GetSporkValue(SporkId nSporkID) { LOCK(cs); if (mapSporksActive.count(nSporkID)) { return mapSporksActive[nSporkID].nValue; } else { auto it = sporkDefsById.find(nSporkID); if (it != sporkDefsById.end()) { return it->second->defaultValue; } else { LogPrintf("%s : Unknown Spork %d\n", __func__, nSporkID); } } return -1; } SporkId CSporkManager::GetSporkIDByName(std::string strName) { auto it = sporkDefsByName.find(strName); if (it == sporkDefsByName.end()) { LogPrintf("%s : Unknown Spork name '%s'\n", __func__, strName); return SPORK_INVALID; } return it->second->sporkId; } std::string CSporkManager::GetSporkNameByID(SporkId nSporkID) { auto it = sporkDefsById.find(nSporkID); if (it == sporkDefsById.end()) { LogPrint(BCLog::SPORKS, "%s : Unknown Spork ID %d\n", __func__, nSporkID); return "Unknown"; } return it->second->name; } bool CSporkManager::SetPrivKey(std::string strPrivKey) { CSporkMessage spork; spork.Sign(strPrivKey); bool fValidSig = spork.CheckSignature(spork.GetPublicKey().GetID()); if (!fValidSig) { // See if window is open that allows for old spork key to sign messages if (GetAdjustedTime() < Params().GetConsensus().nTime_RejectOldSporkKey) { CPubKey pubkeyold = spork.GetPublicKeyOld(); fValidSig = spork.CheckSignature(pubkeyold.GetID()); } } if (fValidSig) { LOCK(cs); // Test signing successful, proceed LogPrintf("%s : Successfully initialized as spork signer\n", __func__); strMasterPrivKey = strPrivKey; return true; } return false; } std::string CSporkManager::ToString() const { LOCK(cs); return strprintf("Sporks: %llu", mapSporksActive.size()); } uint256 CSporkMessage::GetSignatureHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << nMessVersion; ss << nSporkID; ss << nValue; ss << nTimeSigned; return ss.GetHash(); } std::string CSporkMessage::GetStrMessage() const { return std::to_string(nSporkID) + std::to_string(nValue) + std::to_string(nTimeSigned); } const CPubKey CSporkMessage::GetPublicKey() const { return CPubKey(ParseHex(Params().GetConsensus().strSporkPubKey)); } const CPubKey CSporkMessage::GetPublicKeyOld() const { return CPubKey(ParseHex(Params().GetConsensus().strSporkPubKeyOld)); } void CSporkMessage::Relay() { CInv inv(MSG_SPORK, GetHash()); g_connman->RelayInv(inv); } <|endoftext|>
<commit_before>#include "io.h" /* Writes noise, fractal and water info to file_name */ void writeFile(string file_name, NoiseParams *noise_params, WaterParams *water_params) { /*ofstream myfile(file_name); if (myfile.is_open()) { /* Write header myfile << IO_HEADER_STRING << endl; /* The order is not important /* Noise myfile << "noise_type " << noise_params->type << endl; myfile << "noise_width " << noise_params->width << endl; myfile << "noise_height " << noise_params->height << endl; myfile << "noise_offset " << noise_params->offset << endl; myfile << "noise_amplitude " << noise_params->amplitude << endl; myfile << "noise_seed " << noise_params->seed << endl; /* Fractal if (fractal_params->enable) { myfile << "fractal_enable " << "true" << endl; myfile << "fractal_H " << fractal_params->H << endl; myfile << "fractal_lacunarity " << fractal_params->lacunarity << endl; myfile << "fractal_octaves " << fractal_params->octaves << endl; myfile << "fractal_offset " << fractal_params->offset << endl; myfile << "fractal_amplitude " << fractal_params->amplitude << endl; } else { myfile << "fractal_enable " << "false" << endl; } /* Water myfile << "water_height " << water_params->height << endl; myfile << "water_transparency " << water_params->transparency << endl; myfile << "water_depth_alpha_factor " << water_params->depth_alpha_factor << endl; myfile << "water_depth_color_factor " << water_params->depth_color_factor << endl; myfile << "water_color " << water_params->color[0] << ' ' << water_params->color[1] << ' ' << water_params->color[2] << endl; myfile.close(); std::cout << "[Info] Data saved to " << file_name << endl; } else { std::cout << "[Error] Could not save data: the file " << file_name << " could not be opened." << endl; }*/ } void loadFromFile(string file_name, NoiseParams *noise_params, WaterParams *water_params) { /*string line; ifstream myfile(file_name); if (myfile.is_open()) { int line_no = 0; while (getline(myfile, line)) { line_no++; if (line_no == 1) { if (line.compare(IO_HEADER_STRING)) { // the first line doesn't match the header -> illegal format std::cout << "Error: Illegal header. Aborting load." << endl; return; } } string str = line; // construct a stream from the string stringstream strstr(str); // use stream iterators to copy the stream to the vector as whitespace separated strings istream_iterator<string> it(strstr); istream_iterator<string> end; vector<string> results(it, end); /* Load fractal if (!results[0].compare("fractal_enable")) { if (!results[1].compare("true")) { fractal_params->enable = true; } else { } } else if (!results[0].compare("fractal_H")) { fractal_params->H = ::atof(results[1].c_str()); } else if (!results[0].compare("fractal_lacunarity")) { fractal_params->lacunarity = ::atoi(results[1].c_str()); } else if (!results[0].compare("fractal_octaves")) { fractal_params->octaves = ::atoi(results[1].c_str()); } else if (!results[0].compare("fractal_offset")) { fractal_params->offset = ::atof(results[1].c_str()); } else if (!results[0].compare("fractal_amplitude")) { fractal_params->amplitude = ::atof(results[1].c_str()); } /* Load noise else if (!results[0].compare("noise_type")) { int type = ::atoi(results[1].c_str()); switch (type) { case 0: noise_params->type = COPY_TEXTURE; break; case 1: noise_params->type = NO_NOISE; break; case 2: noise_params->type = RANDOM_NOISE; break; case 3: noise_params->type = PERLIN_NOISE; break; case 4: noise_params->type = PERLIN_NOISE_ABS; break; default: std::cout << "[Error] Unkown NoiseType" << endl; break; } } else if (!results[0].compare("noise_width")) { noise_params->width = ::atoi(results[1].c_str()); } else if (!results[0].compare("noise_height")) { noise_params->height = ::atoi(results[1].c_str()); } else if (!results[0].compare("noise_offset")) { noise_params->offset = ::atof(results[1].c_str()); } else if (!results[0].compare("noise_amplitude")) { noise_params->amplitude = ::atof(results[1].c_str()); } else if (!results[0].compare("noise_seed")) { noise_params->seed = ::atof(results[1].c_str()); } /* Load water else if (!results[0].compare("water_height")) { water_params->height = ::atof(results[1].c_str()); } else if (!results[0].compare("water_transparency")) { water_params->transparency = ::atof(results[1].c_str()); } else if (!results[0].compare("water_depth_alpha_factor")) { water_params->depth_alpha_factor = ::atof(results[1].c_str()); } else if (!results[0].compare("water_depth_color_factor")) { water_params->depth_color_factor = ::atof(results[1].c_str()); } else if (!results[0].compare("water_color")) { water_params->color = vec3(::atof(results[1].c_str()), ::atof(results[2].c_str()), ::atof(results[3].c_str())); } } myfile.close(); std::cout << "[Info] Data loaded from " << file_name << endl; } else { std::cout << "[Error] Could not load data: the file" << file_name << " could not be opened." << endl; }*/ } bool save_screenshot(string filename, int w, int h) { //This prevents the images getting padded // when the width multiplied by 3 is not a multiple of 4 glPixelStorei(GL_PACK_ALIGNMENT, 1); int nSize = w*h * 3; // First let's create our buffer, 3 channels per Pixel char* dataBuffer = (char*)malloc(nSize*sizeof(char)); if (!dataBuffer) return false; // Let's fetch them from the backbuffer // We request the pixels in GL_BGR format, thanks to Berzeger for the tip glReadPixels((GLint)0, (GLint)0, (GLint)w, (GLint)h, GL_BGR, GL_UNSIGNED_BYTE, dataBuffer); //Now the file creation FILE *filePtr = fopen(filename.c_str(), "wb"); if (!filePtr) return false; unsigned char TGAheader[12] = { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; unsigned char header[6] = { w % 256, w / 256, h % 256, h / 256, 24, 0 }; // We write the headers fwrite(TGAheader, sizeof(unsigned char), 12, filePtr); fwrite(header, sizeof(unsigned char), 6, filePtr); // And finally our image data fwrite(dataBuffer, sizeof(GLubyte), nSize, filePtr); fclose(filePtr); return true; } string get_unique_name() { std::stringstream ss; time_t t = time(0); struct tm * now = localtime(&t); ss << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << '-' << now->tm_hour << '-' << now->tm_min << '-' << now->tm_sec << ".tga"; return ss.str(); }<commit_msg>Free data buffer after screenshot<commit_after>#include "io.h" /* Writes noise, fractal and water info to file_name */ void writeFile(string file_name, NoiseParams *noise_params, WaterParams *water_params) { /*ofstream myfile(file_name); if (myfile.is_open()) { /* Write header myfile << IO_HEADER_STRING << endl; /* The order is not important /* Noise myfile << "noise_type " << noise_params->type << endl; myfile << "noise_width " << noise_params->width << endl; myfile << "noise_height " << noise_params->height << endl; myfile << "noise_offset " << noise_params->offset << endl; myfile << "noise_amplitude " << noise_params->amplitude << endl; myfile << "noise_seed " << noise_params->seed << endl; /* Fractal if (fractal_params->enable) { myfile << "fractal_enable " << "true" << endl; myfile << "fractal_H " << fractal_params->H << endl; myfile << "fractal_lacunarity " << fractal_params->lacunarity << endl; myfile << "fractal_octaves " << fractal_params->octaves << endl; myfile << "fractal_offset " << fractal_params->offset << endl; myfile << "fractal_amplitude " << fractal_params->amplitude << endl; } else { myfile << "fractal_enable " << "false" << endl; } /* Water myfile << "water_height " << water_params->height << endl; myfile << "water_transparency " << water_params->transparency << endl; myfile << "water_depth_alpha_factor " << water_params->depth_alpha_factor << endl; myfile << "water_depth_color_factor " << water_params->depth_color_factor << endl; myfile << "water_color " << water_params->color[0] << ' ' << water_params->color[1] << ' ' << water_params->color[2] << endl; myfile.close(); std::cout << "[Info] Data saved to " << file_name << endl; } else { std::cout << "[Error] Could not save data: the file " << file_name << " could not be opened." << endl; }*/ } void loadFromFile(string file_name, NoiseParams *noise_params, WaterParams *water_params) { /*string line; ifstream myfile(file_name); if (myfile.is_open()) { int line_no = 0; while (getline(myfile, line)) { line_no++; if (line_no == 1) { if (line.compare(IO_HEADER_STRING)) { // the first line doesn't match the header -> illegal format std::cout << "Error: Illegal header. Aborting load." << endl; return; } } string str = line; // construct a stream from the string stringstream strstr(str); // use stream iterators to copy the stream to the vector as whitespace separated strings istream_iterator<string> it(strstr); istream_iterator<string> end; vector<string> results(it, end); /* Load fractal if (!results[0].compare("fractal_enable")) { if (!results[1].compare("true")) { fractal_params->enable = true; } else { } } else if (!results[0].compare("fractal_H")) { fractal_params->H = ::atof(results[1].c_str()); } else if (!results[0].compare("fractal_lacunarity")) { fractal_params->lacunarity = ::atoi(results[1].c_str()); } else if (!results[0].compare("fractal_octaves")) { fractal_params->octaves = ::atoi(results[1].c_str()); } else if (!results[0].compare("fractal_offset")) { fractal_params->offset = ::atof(results[1].c_str()); } else if (!results[0].compare("fractal_amplitude")) { fractal_params->amplitude = ::atof(results[1].c_str()); } /* Load noise else if (!results[0].compare("noise_type")) { int type = ::atoi(results[1].c_str()); switch (type) { case 0: noise_params->type = COPY_TEXTURE; break; case 1: noise_params->type = NO_NOISE; break; case 2: noise_params->type = RANDOM_NOISE; break; case 3: noise_params->type = PERLIN_NOISE; break; case 4: noise_params->type = PERLIN_NOISE_ABS; break; default: std::cout << "[Error] Unkown NoiseType" << endl; break; } } else if (!results[0].compare("noise_width")) { noise_params->width = ::atoi(results[1].c_str()); } else if (!results[0].compare("noise_height")) { noise_params->height = ::atoi(results[1].c_str()); } else if (!results[0].compare("noise_offset")) { noise_params->offset = ::atof(results[1].c_str()); } else if (!results[0].compare("noise_amplitude")) { noise_params->amplitude = ::atof(results[1].c_str()); } else if (!results[0].compare("noise_seed")) { noise_params->seed = ::atof(results[1].c_str()); } /* Load water else if (!results[0].compare("water_height")) { water_params->height = ::atof(results[1].c_str()); } else if (!results[0].compare("water_transparency")) { water_params->transparency = ::atof(results[1].c_str()); } else if (!results[0].compare("water_depth_alpha_factor")) { water_params->depth_alpha_factor = ::atof(results[1].c_str()); } else if (!results[0].compare("water_depth_color_factor")) { water_params->depth_color_factor = ::atof(results[1].c_str()); } else if (!results[0].compare("water_color")) { water_params->color = vec3(::atof(results[1].c_str()), ::atof(results[2].c_str()), ::atof(results[3].c_str())); } } myfile.close(); std::cout << "[Info] Data loaded from " << file_name << endl; } else { std::cout << "[Error] Could not load data: the file" << file_name << " could not be opened." << endl; }*/ } bool save_screenshot(string filename, int w, int h) { glPixelStorei(GL_PACK_ALIGNMENT, 1); int nSize = w*h * 3; // 3 channels per Pixel char* dataBuffer = (char*)malloc(nSize*sizeof(char)); if (!dataBuffer) return false; glReadPixels((GLint)0, (GLint)0, (GLint)w, (GLint)h, GL_BGR, GL_UNSIGNED_BYTE, dataBuffer); FILE *filePtr = fopen(filename.c_str(), "wb"); if (!filePtr) return false; unsigned char TGAheader[12] = { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; unsigned char header[6] = { w % 256, w / 256, h % 256, h / 256, 24, 0 }; // Write headers fwrite(TGAheader, sizeof(unsigned char), 12, filePtr); fwrite(header, sizeof(unsigned char), 6, filePtr); // Write image data fwrite(dataBuffer, sizeof(GLubyte), nSize, filePtr); fclose(filePtr); delete[] dataBuffer; return true; } string get_unique_name() { std::stringstream ss; time_t t = time(0); struct tm * now = localtime(&t); ss << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << '-' << now->tm_hour << '-' << now->tm_min << '-' << now->tm_sec << ".tga"; return ss.str(); }<|endoftext|>
<commit_before><commit_msg>Fixed Vector2 to Integer2 cast in Application.<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Motor Calibration tool: Set motor PWM pulse widths to any value in us ******************************************************************************/ #include "MotorCalibration.h" #include <signal.h> ////////////////////// // Global Variables // ////////////////////// // Stop main loop? int stoploop = 0; /****************************************************************************** * void ctrlC(int signo) * * Control-C Handler ******************************************************************************/ void ctroC(int signo) { if (signo == SIGINT) { stoploop = 1; printf("\nReceived SIGINT Ctrl-C\n"); } } /****************************************************************************** * Main Function ******************************************************************************/ int main() { // Initialize WiringPi wiringPiSetupGpio(); // Setup ctrl-c catcher signal(SIGINT, ctrlC); int fd = pca9685Setup(PIN_BASE, PCA9685_ADDR, HERTZ); pca9685PWMReset(fd); for( int i = 0; i < 3; i++ ) { pwmWrite (PIN_BASE+i, 2674); printf("Initialized motor at pin_base: %i\n", PIN_BASE+i); } // Run main while loop, wait until it's time to stop while(!stoploop) { int motornum = 0, motoroutput; //std::cout << "Input motor number: "; //std::cin >> motornum; std::cout << "Input motor output: "; std::cin >> motoroutput; // Spin those motors //pwmWrite(motornum + PIN_BASE, motoroutput); pwmWrite(PIN_BASE + 0, motoroutput); pwmWrite(PIN_BASE + 1, motoroutput); std::cout << "Set Motor " << motornum << " to " << motoroutput << std::endl << std::endl; } // Shut off motors pwmWrite(PIN_BASE + 0, 2647); pwmWrite(PIN_BASE + 1, 2647); pwmWrite(PIN_BASE + 2, 2647); return 0; } <commit_msg>motorcalibration exits cleanly, but still need to quit to end program<commit_after>/****************************************************************************** * Motor Calibration tool: Set motor PWM pulse widths to any value in us ******************************************************************************/ #include "MotorCalibration.h" #include <signal.h> ////////////////////// // Global Variables // ////////////////////// // Stop main loop? int stoploop = 0; /****************************************************************************** * void ctrlC(int signo) * * Control-C Handler ******************************************************************************/ void ctrlC(int signo) { if (signo == SIGINT) { stoploop = 1; printf("\nReceived SIGINT Ctrl-C\n"); for( int i = 0; i < 3; i++ ) { pwmWrite (300+i, 2674); printf("Motor zeroed at pin_base: %i\n", PIN_BASE+i); } printf("exited cleanly\n"); } } /****************************************************************************** * Main Function ******************************************************************************/ int main() { // Initialize WiringPi wiringPiSetupGpio(); // Setup ctrl-c catcher signal(SIGINT, ctrlC); int fd = pca9685Setup(PIN_BASE, PCA9685_ADDR, HERTZ); pca9685PWMReset(fd); for( int i = 0; i < 3; i++ ) { pwmWrite (PIN_BASE+i, 2674); printf("Initialized motor at pin_base: %i\n", PIN_BASE+i); } // Run main while loop, wait until it's time to stop while(!stoploop) { int motornum = 0, motoroutput; //std::cout << "Input motor number: "; //std::cin >> motornum; std::cout << "Input motor output: "; std::cin >> motoroutput; // Spin those motors //pwmWrite(motornum + PIN_BASE, motoroutput); pwmWrite(PIN_BASE + 0, motoroutput); pwmWrite(PIN_BASE + 1, motoroutput); std::cout << "Set Motor " << motornum << " to " << motoroutput << std::endl << std::endl; } // Shut off motors pwmWrite(PIN_BASE + 0, 2647); pwmWrite(PIN_BASE + 1, 2647); pwmWrite(PIN_BASE + 2, 2647); return 0; } <|endoftext|>
<commit_before> #include "cameraManager.h" #define STRINGIFY(s) #s void cameraManager::setup(){ useSideCamera = false; currentCamera = &easyCam; string fragShaderSrc = STRINGIFY( uniform sampler2DRect tex0; // line image uniform sampler2DRect tex1; // rock image void main(void){ vec2 st = gl_TexCoord[0].st; vec4 colorA = texture2DRect(tex0, st); vec4 colorB = texture2DRect(tex1, st); if (colorA.x > 0.01){ gl_FragColor = vec4(colorB.x, colorB.y, colorB.z, colorA.x); } else { discard; } } ); shader.setupShaderFromSource(GL_FRAGMENT_SHADER, fragShaderSrc); shader.linkProgram(); } void cameraManager::update(){ if(!useSideCamera){ currentCamera = &baseCamera; } else{ //update camera positions; ofVec3f center = baseCamera.screenToWorld( ofPoint(1920/2,1080) / 2 ); ofVec3f camP = baseCamera.getPosition(); center = camP + (center - camP).normalize() * 351*2; sideCam.setPosition(center + ofVec3f(1920,0,0)); sideCam.lookAt(center,ofVec3f(0,1,0)); topCamera.setPosition(center + ofVec3f(0,1080, 0)); topCamera.lookAt(center,ofVec3f(1,0,0)); } } void cameraManager::drawCameraInternals(ofImage &person, ofImage &mask, ofImage &backplate){ ofPoint a,b,c,d, e; ofRectangle window; window.set(0,0,1920, 1080); a = baseCamera.screenToWorld( ofPoint(0,1080), window); b = baseCamera.screenToWorld( ofPoint(1920,1080), window); c = baseCamera.screenToWorld( ofPoint(0,0), window); d = baseCamera.screenToWorld( ofPoint(1920,0), window); ofPoint camP = baseCamera.getPosition(); ofPoint aFar = camP + (a - camP).normalize() * 351*7; ofPoint bFar = camP + (b - camP).normalize() * 351*7; ofPoint cFar = camP + (c - camP).normalize() * 351*7; ofPoint dFar = camP + (d - camP).normalize() * 351*7; a = camP + (a - camP).normalize() * 351*5; b = camP + (b - camP).normalize() * 351*5; c = camP + (c - camP).normalize() * 351*5; d = camP + (d - camP).normalize() * 351*5; e = camP + (e - camP).normalize() * 351*4; // draw the backplate: backplate.bind(); ofMesh mesh; mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP); mesh.addVertex( aFar) ; mesh.addTexCoord( ofPoint(0,backplate.getHeight())); mesh.addVertex( bFar) ; mesh.addTexCoord( ofPoint(backplate.getWidth(),backplate.getHeight())); mesh.addVertex( cFar) ; mesh.addTexCoord( ofPoint(0,0)); mesh.addVertex( dFar ) ; mesh.addTexCoord( ofPoint(backplate.getWidth(), 0)); mesh.draw(); backplate.unbind(); // figure out a Z distance. shader.begin(); shader.setUniformTexture("tex0", mask, 1); shader.setUniformTexture("tex1", person, 2); //frame.mask.bind(); mesh.clear(); mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP); mesh.addVertex( a) ; mesh.addTexCoord( ofPoint(0,person.getHeight())); mesh.addVertex( b) ; mesh.addTexCoord( ofPoint(person.getWidth(),person.getHeight())); mesh.addVertex( c) ; mesh.addTexCoord( ofPoint(0,0)); mesh.addVertex( d ) ; mesh.addTexCoord( ofPoint(person.getWidth(), 0)); mesh.draw(); //backplate.unbind(); shader.end(); ofLine( baseCamera.getPosition(), a); ofLine( baseCamera.getPosition(), b); ofLine( baseCamera.getPosition(), c); ofLine( baseCamera.getPosition(), d); } void cameraManager::cameraStart(){ if(useSideCamera){ currentCamera->begin(); ofPushStyle(); ofPushMatrix(); ofNoFill(); ofColor(255,0,0); // ofDrawSphere(depthToRGBTranslation, 10); ofNode n; n.setPosition(CCM.depthToRGBTranslation); n.draw(); ofColor(0,250,0); ofSphere(0,0,0,10); ofFill(); ofSetColor(255,0,0); if(ofGetKeyPressed('m')){ ofMultMatrix(CCM.extrinsics); } ofSetLineWidth(5); ofLine(ofVec3f(0,0,0), ofVec3f(0,0,-100)); ofPopMatrix(); ofPopStyle(); ofEnableDepthTest(); } else{ ofVec3f camPos(0,0,0); camPos = CCM.extrinsics * camPos; baseCamera.setTransformMatrix(CCM.extrinsics); baseCamera.setFov( CCM.rgbCalibration.getDistortedIntrinsics().getFov().y ); baseCamera.begin(ofRectangle(0,0,1920, 1080)); ofEnableDepthTest(); } // this helps for easy cam, bring the scene nearer to 0,0,0 if (currentCamera == &easyCam){ ofRectangle window; window.set(0,0,1920, 1080); ofPoint e = baseCamera.screenToWorld( ofPoint(1920,1080) / 2.0, window); ofPoint camP = baseCamera.getPosition(); e = camP + (e - camP).normalize() * 351*4; ofTranslate(-e.x, -e.y, -e.z); } } void cameraManager::cameraEnd(){ if(useSideCamera){ currentCamera->end(); } else{ baseCamera.end(); } } void cameraManager::keyPressed(int key){ if(key == ' '){ useSideCamera = !useSideCamera; if (useSideCamera){ //currentCamera = &easyCam; } } if(useSideCamera){ if(key == OF_KEY_LEFT){ if(currentCamera == &easyCam){ currentCamera = &sideCam; } else if(currentCamera == &sideCam){ currentCamera = &topCamera; } else { currentCamera = &easyCam; } } else if(key == OF_KEY_RIGHT){ if(currentCamera == &easyCam){ currentCamera = &topCamera; } else if(currentCamera == &topCamera){ currentCamera = &sideCam; } else { currentCamera = &easyCam; } } } } <commit_msg>I need backplate drawn outside of camera to do some depth stuff with the rhonda line renderer (its needs a flat zdepth to composite ok)<commit_after> #include "cameraManager.h" #define STRINGIFY(s) #s void cameraManager::setup(){ useSideCamera = false; currentCamera = &easyCam; string fragShaderSrc = STRINGIFY( uniform sampler2DRect tex0; // line image uniform sampler2DRect tex1; // rock image void main(void){ vec2 st = gl_TexCoord[0].st; vec4 colorA = texture2DRect(tex0, st); vec4 colorB = texture2DRect(tex1, st); if (colorA.x > 0.01){ gl_FragColor = vec4(colorB.x, colorB.y, colorB.z, colorA.x); } else { discard; } } ); shader.setupShaderFromSource(GL_FRAGMENT_SHADER, fragShaderSrc); shader.linkProgram(); } void cameraManager::update(){ if(!useSideCamera){ currentCamera = &baseCamera; } else{ //update camera positions; ofVec3f center = baseCamera.screenToWorld( ofPoint(1920/2,1080) / 2 ); ofVec3f camP = baseCamera.getPosition(); center = camP + (center - camP).normalize() * 351*2; sideCam.setPosition(center + ofVec3f(1920,0,0)); sideCam.lookAt(center,ofVec3f(0,1,0)); topCamera.setPosition(center + ofVec3f(0,1080, 0)); topCamera.lookAt(center,ofVec3f(1,0,0)); } } void cameraManager::drawCameraInternals(ofImage &person, ofImage &mask, ofImage &backplate){ ofPoint a,b,c,d, e; ofRectangle window; window.set(0,0,1920, 1080); a = baseCamera.screenToWorld( ofPoint(0,1080), window); b = baseCamera.screenToWorld( ofPoint(1920,1080), window); c = baseCamera.screenToWorld( ofPoint(0,0), window); d = baseCamera.screenToWorld( ofPoint(1920,0), window); ofPoint camP = baseCamera.getPosition(); ofPoint aFar = camP + (a - camP).normalize() * 351*7; ofPoint bFar = camP + (b - camP).normalize() * 351*7; ofPoint cFar = camP + (c - camP).normalize() * 351*7; ofPoint dFar = camP + (d - camP).normalize() * 351*7; a = camP + (a - camP).normalize() * 351*5; b = camP + (b - camP).normalize() * 351*5; c = camP + (c - camP).normalize() * 351*5; d = camP + (d - camP).normalize() * 351*5; e = camP + (e - camP).normalize() * 351*4; // draw the backplate: ofMesh mesh; /* // I want to draw the backplay flat with no depth b/c of how the line renderer needs to fuck with depth. backplate.bind(); ofMesh mesh; mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP); mesh.addVertex( aFar) ; mesh.addTexCoord( ofPoint(0,backplate.getHeight())); mesh.addVertex( bFar) ; mesh.addTexCoord( ofPoint(backplate.getWidth(),backplate.getHeight())); mesh.addVertex( cFar) ; mesh.addTexCoord( ofPoint(0,0)); mesh.addVertex( dFar ) ; mesh.addTexCoord( ofPoint(backplate.getWidth(), 0)); mesh.draw(); backplate.unbind(); */ // figure out a Z distance. shader.begin(); shader.setUniformTexture("tex0", mask, 1); shader.setUniformTexture("tex1", person, 2); //frame.mask.bind(); mesh.clear(); mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP); mesh.addVertex( a) ; mesh.addTexCoord( ofPoint(0,person.getHeight())); mesh.addVertex( b) ; mesh.addTexCoord( ofPoint(person.getWidth(),person.getHeight())); mesh.addVertex( c) ; mesh.addTexCoord( ofPoint(0,0)); mesh.addVertex( d ) ; mesh.addTexCoord( ofPoint(person.getWidth(), 0)); mesh.draw(); //backplate.unbind(); shader.end(); ofLine( baseCamera.getPosition(), a); ofLine( baseCamera.getPosition(), b); ofLine( baseCamera.getPosition(), c); ofLine( baseCamera.getPosition(), d); } void cameraManager::cameraStart(){ if(useSideCamera){ currentCamera->begin(); ofPushStyle(); ofPushMatrix(); ofNoFill(); ofColor(255,0,0); // ofDrawSphere(depthToRGBTranslation, 10); ofNode n; n.setPosition(CCM.depthToRGBTranslation); n.draw(); ofColor(0,250,0); ofSphere(0,0,0,10); ofFill(); ofSetColor(255,0,0); if(ofGetKeyPressed('m')){ ofMultMatrix(CCM.extrinsics); } ofSetLineWidth(5); ofLine(ofVec3f(0,0,0), ofVec3f(0,0,-100)); ofPopMatrix(); ofPopStyle(); ofEnableDepthTest(); } else{ ofVec3f camPos(0,0,0); camPos = CCM.extrinsics * camPos; baseCamera.setTransformMatrix(CCM.extrinsics); baseCamera.setFov( CCM.rgbCalibration.getDistortedIntrinsics().getFov().y ); baseCamera.begin(ofRectangle(0,0,1920, 1080)); ofEnableDepthTest(); } // this helps for easy cam, bring the scene nearer to 0,0,0 if (currentCamera == &easyCam){ ofRectangle window; window.set(0,0,1920, 1080); ofPoint e = baseCamera.screenToWorld( ofPoint(1920,1080) / 2.0, window); ofPoint camP = baseCamera.getPosition(); e = camP + (e - camP).normalize() * 351*4; ofTranslate(-e.x, -e.y, -e.z); } } void cameraManager::cameraEnd(){ if(useSideCamera){ currentCamera->end(); } else{ baseCamera.end(); } } void cameraManager::keyPressed(int key){ if(key == ' '){ useSideCamera = !useSideCamera; if (useSideCamera){ //currentCamera = &easyCam; } } if(useSideCamera){ if(key == OF_KEY_LEFT){ if(currentCamera == &easyCam){ currentCamera = &sideCam; } else if(currentCamera == &sideCam){ currentCamera = &topCamera; } else { currentCamera = &easyCam; } } else if(key == OF_KEY_RIGHT){ if(currentCamera == &easyCam){ currentCamera = &topCamera; } else if(currentCamera == &topCamera){ currentCamera = &sideCam; } else { currentCamera = &easyCam; } } } } <|endoftext|>
<commit_before>#ifndef HDF5_HPP__ #define HDF5_HPP__ #define IO_BASE_DEFINITION__ #include "Io.hpp" #ifdef HAS_HDF5 #include <hdf5.h> #endif #include <map> #include <csignal> #ifdef HAS_HDF5 static const hid_t DATA_TYPE = H5T_NATIVE_FLOAT; #endif /// Compare with bool Hdf5::errorCheck(...) #define ERRORCHECK(STATUS) errorCheck(STATUS, __FILE__, __LINE__, __FUNCTION__) /// Compare with void Hdf5::pushError(...) #define PUSHERROR(E) pushError(E, __FILE__, __LINE__, __FUNCTION__) class Hdf5 : public Io { public: Hdf5(int superDomainSize); ~Hdf5(); bool isEnabled(); bool openRead(const string &filename); bool openWrite(const string &filename); array_info_t getArrayInfo(const string& variableName, const string& group); bool readVariable( const string& variableName, const string& group, const array_info_t& info, void* data ); bool readAttribute( const string& attributeName, void* data, int& dataLength, const identify_data_type& dataType, const string& group); bool writeVariable( const string& variableName, const string& group, const array_info_t& info, const void* data ); bool writeAttribute( const string& attributeName, const void* data, const int& dataLength , const identify_data_type& dataType, const string& group); void getBcastArrayInfo( const string& group, array_info_t& info ); void getLocalArrayInfo( const string& group, array_info_t& info ); void putArrayInfo( const string& group, const array_info_t& info ); bool verifyShape( const string& variableName, const string& group, const array_info_t& info ); const list<string> getVariableNames(); const list<string> getAttributeNames(); bool close(); protected: #ifdef HAS_HDF5 map<string,hid_t> h5groups; template<class T> hsize_t* hsize_convert(const T* v, const int &s, hsize_t *n, const int &max=MAX_ARRAY_DIMENSION) const { for (int i=0; i<max; i++) n[i]=(i<=s?v[i]:0); return n; } hid_t identifyH5Type( const identify_data_type& dataType, const string& v) const { switch (dataType) { case identify_byte_t: return H5T_NATIVE_UCHAR; case identify_char_t: return H5T_C_S1; case identify_string_t: return H5T_C_S1; case identify_short_t: return H5T_NATIVE_SHORT; case identify_int_t: return H5T_NATIVE_INT; case identify_long_t: return H5T_NATIVE_LONG; case identify_float_t: return H5T_NATIVE_FLOAT; case identify_double_t: return H5T_NATIVE_DOUBLE; case identify_unknown_t: default: cerr << "Unknown type for identifyH5Type with variable " << v << endl; raise(SIGABRT); return -1; } } identify_data_type H5identifyType( const hid_t h5type, const string& v ) const { if (H5Tequal(h5type,H5T_NATIVE_UCHAR)) return identify_byte_t; if (H5Tequal(h5type,H5T_C_S1)) return identify_char_t; if (H5Tequal(h5type,H5T_NATIVE_SHORT)) return identify_short_t; if (H5Tequal(h5type,H5T_NATIVE_INT)) return identify_int_t; if (H5Tequal(h5type,H5T_NATIVE_LONG)) return identify_long_t; if (H5Tequal(h5type,H5T_NATIVE_FLOAT)) return identify_float_t; if (H5Tequal(h5type,H5T_NATIVE_DOUBLE)) return identify_double_t; cerr << "Unknown type for H5identifyType with variable " << v << endl; raise(SIGABRT); return identify_unknown_t; } /** * \brief Check for Hdf5 errors. If a problem is found, push error message(s) to errorStack. * * \note Use ERRORCHECK preprocessor macro to help set Hdf5::errorCheck arguments! * * \param status hdf5 error status flag (should be < 0 denotes error) * \param file Name of source file containing the error * \param line Line number where error occured * \param func Name of function which error occured within. * * \return true if an error was found. */ bool errorCheck(const int &status, const char *file, const int &line, const char *func); hid_t createGroup(const string &groupName); virtual bool open(const string &filename, const hid_t &accessMode ); hid_t fileId, classId, majorErrorId, minorErrorId; void pushError(const string &e, const char *file, const int &line, const char *func); #else int fileId; #endif }; #endif <commit_msg>Bug fix: comparisons using H5Tequal against native data types only work when you call H5Tget_native_type(h5type)!<commit_after>#ifndef HDF5_HPP__ #define HDF5_HPP__ #define IO_BASE_DEFINITION__ #include "Io.hpp" #ifdef HAS_HDF5 #include <hdf5.h> #endif #include <map> #include <csignal> #ifdef HAS_HDF5 static const hid_t DATA_TYPE = H5T_NATIVE_FLOAT; #endif /// Compare with bool Hdf5::errorCheck(...) #define ERRORCHECK(STATUS) errorCheck(STATUS, __FILE__, __LINE__, __FUNCTION__) /// Compare with void Hdf5::pushError(...) #define PUSHERROR(E) pushError(E, __FILE__, __LINE__, __FUNCTION__) /** * \todo { Some Hdf5 operations require closing hid_t objects. These * are not always obvious. For example: * - H5Dget_type(...) * - H5Aget_type(...) * Modify code so we close access where required. See Hdf5 * documentation for more info. } */ class Hdf5 : public Io { public: Hdf5(int superDomainSize); ~Hdf5(); bool isEnabled(); bool openRead(const string &filename); bool openWrite(const string &filename); array_info_t getArrayInfo(const string& variableName, const string& group); bool readVariable( const string& variableName, const string& group, const array_info_t& info, void* data ); bool readAttribute( const string& attributeName, void* data, int& dataLength, const identify_data_type& dataType, const string& group); bool writeVariable( const string& variableName, const string& group, const array_info_t& info, const void* data ); bool writeAttribute( const string& attributeName, const void* data, const int& dataLength , const identify_data_type& dataType, const string& group); void getBcastArrayInfo( const string& group, array_info_t& info ); void getLocalArrayInfo( const string& group, array_info_t& info ); void putArrayInfo( const string& group, const array_info_t& info ); bool verifyShape( const string& variableName, const string& group, const array_info_t& info ); const list<string> getVariableNames(); const list<string> getAttributeNames(); bool close(); protected: #ifdef HAS_HDF5 map<string,hid_t> h5groups; template<class T> hsize_t* hsize_convert(const T* v, const int &s, hsize_t *n, const int &max=MAX_ARRAY_DIMENSION) const { for (int i=0; i<max; i++) n[i]=(i<=s?v[i]:0); return n; } hid_t identifyH5Type( const identify_data_type& dataType, const string& v) const { switch (dataType) { case identify_byte_t: return H5T_NATIVE_UCHAR; case identify_char_t: return H5T_NATIVE_CHAR; case identify_string_t: return H5T_C_S1; case identify_short_t: return H5T_NATIVE_SHORT; case identify_int_t: return H5T_NATIVE_INT; case identify_long_t: return H5T_NATIVE_LONG; case identify_float_t: return H5T_NATIVE_FLOAT; case identify_double_t: return H5T_NATIVE_DOUBLE; case identify_unknown_t: default: //cerr << "Unknown type for identifyH5Type with variable " << v << endl; //raise(SIGABRT); return -1; } } /** * Find a list of native data types here: * http://www.hdfgroup.org/HDF5/doc/RM/RM_H5T.html#Datatype-GetNativeType */ identify_data_type H5identifyType( const hid_t h5type, const string& v ) const { if (H5Tequal(h5type, H5T_C_S1)) return identify_string_t; hid_t native_type = H5Tget_native_type(h5type, H5T_DIR_ASCEND); if (H5Tequal(native_type,H5T_NATIVE_UCHAR)) return identify_byte_t; if (H5Tequal(native_type,H5T_NATIVE_SHORT)) return identify_short_t; if (H5Tequal(native_type,H5T_NATIVE_INT)) return identify_int_t; if (H5Tequal(native_type,H5T_NATIVE_LONG)) return identify_long_t; if (H5Tequal(native_type,H5T_NATIVE_FLOAT)) return identify_float_t; if (H5Tequal(native_type,H5T_NATIVE_DOUBLE)) return identify_double_t; //cerr << "Unknown type for H5identifyType with variable " << v << endl; //raise(SIGABRT); return identify_unknown_t; } /** * \brief Check for Hdf5 errors. If a problem is found, push error message(s) to errorStack. * * \note Use ERRORCHECK preprocessor macro to help set Hdf5::errorCheck arguments! * * \param status hdf5 error status flag (should be < 0 denotes error) * \param file Name of source file containing the error * \param line Line number where error occured * \param func Name of function which error occured within. * * \return true if an error was found. */ bool errorCheck(const int &status, const char *file, const int &line, const char *func); hid_t createGroup(const string &groupName); virtual bool open(const string &filename, const hid_t &accessMode ); hid_t fileId, classId, majorErrorId, minorErrorId; void pushError(const string &e, const char *file, const int &line, const char *func); #else int fileId; #endif }; #endif <|endoftext|>
<commit_before>#include "stdafx.h" #include "ResultSummary.h" #include "Simulation.h" namespace sim { ResultSummary::ResultSummary(Simulation *simulation) { this->simulation = simulation; } ResultSummary::~ResultSummary() { } double ResultSummary::getChanceForKnockout(int teamID, int bofRound) { int totalLosses = 0; // go through all different clusters (all types of matches) for (auto &cluster : simulation->clusterMatchResultStatisticsLists) { auto &results = cluster.second; if (results.bofRound != bofRound) continue; // sum up losses of team over all matches in the specified best-of-X round totalLosses += simulation->clusterTeamResults[cluster.first][teamID].getLosses(); } return (double)totalLosses / (double)simulation->numberOfRuns; } int ResultSummary::getParticipationCount(int teamID, int bofRound) { int totalParticipations = 0; // go through all different clusters (all types of matches) for (auto &cluster : simulation->clusterMatchResultStatisticsLists) { auto &results = cluster.second; if (results.bofRound != bofRound) continue; // sum up losses of team over all matches in the specified best-of-X round totalParticipations += simulation->clusterTeamResults[cluster.first][teamID].getMatchCount(); } return totalParticipations; } void ResultSummary::printResults() { struct Results { int teamID; double knockoutGroup; double knockoutLast16; double knockoutQuarters; double knockoutSemi; double runnerUp; double winner; Results() : teamID(-1), knockoutGroup(-1), knockoutLast16(-1), knockoutQuarters(-1), knockoutSemi(-1), runnerUp(-1), winner(-1) { } }; std::vector<Results> resultsList; for (auto &team : simulation->teams) { Results results; results.teamID = team.id; results.winner = (double)simulation->clusterTeamResults["all"][team.id].getPlaceCount(1) / (double)simulation->numberOfRuns; results.runnerUp = (double)simulation->clusterTeamResults["all"][team.id].getPlaceCount(2) / (double)simulation->numberOfRuns; results.knockoutSemi = getChanceForKnockout(team.id, 2); results.knockoutQuarters = getChanceForKnockout(team.id, 4); results.knockoutLast16 = getChanceForKnockout(team.id, 8); // the chance of being knocked out in the group phase is the chance of not participating in the round-of-16 results.knockoutGroup = 1.0 - ((double)getParticipationCount(team.id, 8) / (double)simulation->numberOfRuns); resultsList.push_back(results); } // Finally print results, for that we will need a map with the team names as required by the contest... // Note that the simulation usually does not care about the team names. // This array reflects the team IDs that are found in the input data. std::vector<std::string> teamNames = {"empty", "Brazil", "Croatia", "Mexico", "Cameroon", "Spain", "Netherlands", "Chile", "Australia", "Colombia", "Greece", "Cte dIvoire", "Japan", "Uruguay", "Costa Rica", "England", "Italy", "Switzerland", "Ecuador", "France", "Honduras", "Argentina", "Bosnia-Herzegovina", "Iran", "Nigeria", "Germany", "Portugal", "Ghana", "United States", "Belgium", "Algeria", "Russia", "Korea Republic" }; for (auto &result : resultsList) { std::cout << teamNames[result.teamID] << "\t" << result.knockoutGroup << "\t" << result.knockoutLast16 << "\t" << result.knockoutQuarters << "\t" << result.knockoutSemi << "\t" << result.runnerUp << "\t" << result.winner << "\t" << "\n"; } } } // namespace sim<commit_msg>fixed calculation of summary statistics<commit_after>#include "stdafx.h" #include "ResultSummary.h" #include "Simulation.h" namespace sim { ResultSummary::ResultSummary(Simulation *simulation) { this->simulation = simulation; } ResultSummary::~ResultSummary() { } double ResultSummary::getChanceForKnockout(int teamID, int bofRound) { int totalLosses = 0; // go through all different clusters (all types of matches) for (auto &cluster : simulation->clusterMatchResultStatisticsLists) { auto &results = cluster.second; if (results.bofRound != bofRound || cluster.first == "all") continue; // sum up losses of team over all matches in the specified best-of-X round totalLosses += simulation->clusterTeamResults[cluster.first][teamID].getLosses(); } return (double)totalLosses / (double)simulation->numberOfRuns; } int ResultSummary::getParticipationCount(int teamID, int bofRound) { int totalParticipations = 0; // go through all different clusters (all types of matches) for (auto &cluster : simulation->clusterMatchResultStatisticsLists) { auto &results = cluster.second; if (results.bofRound != bofRound || cluster.first == "all") continue; // sum up losses of team over all matches in the specified best-of-X round totalParticipations += simulation->clusterTeamResults[cluster.first][teamID].getMatchCount(); } return totalParticipations; } void ResultSummary::printResults() { struct Results { int teamID; double knockoutGroup; double knockoutLast16; double knockoutQuarters; double knockoutSemi; double runnerUp; double winner; Results() : teamID(-1), knockoutGroup(-1), knockoutLast16(-1), knockoutQuarters(-1), knockoutSemi(-1), runnerUp(-1), winner(-1) { } }; std::vector<Results> resultsList; for (auto &team : simulation->teams) { Results results; results.teamID = team.id; results.winner = (double)simulation->clusterTeamResults["all"][team.id].getPlaceCount(1) / (double)simulation->numberOfRuns; results.runnerUp = (double)simulation->clusterTeamResults["all"][team.id].getPlaceCount(2) / (double)simulation->numberOfRuns; results.knockoutSemi = getChanceForKnockout(team.id, 2); results.knockoutQuarters = getChanceForKnockout(team.id, 4); results.knockoutLast16 = getChanceForKnockout(team.id, 8); // the chance of being knocked out in the group phase is the chance of not participating in the round-of-16 results.knockoutGroup = 1.0 - ((double)getParticipationCount(team.id, 8) / (double)simulation->numberOfRuns); resultsList.push_back(results); } // Finally print results, for that we will need a map with the team names as required by the contest... // Note that the simulation usually does not care about the team names. // This array reflects the team IDs that are found in the input data. std::vector<std::string> teamNames = {"empty", "Brazil", "Croatia", "Mexico", "Cameroon", "Spain", "Netherlands", "Chile", "Australia", "Colombia", "Greece", "Cte dIvoire", "Japan", "Uruguay", "Costa Rica", "England", "Italy", "Switzerland", "Ecuador", "France", "Honduras", "Argentina", "Bosnia-Herzegovina", "Iran", "Nigeria", "Germany", "Portugal", "Ghana", "United States", "Belgium", "Algeria", "Russia", "Korea Republic" }; for (auto &result : resultsList) { std::cout << teamNames[result.teamID] << "\t" << result.knockoutGroup << "\t" << result.knockoutLast16 << "\t" << result.knockoutQuarters << "\t" << result.knockoutSemi << "\t" << result.runnerUp << "\t" << result.winner << "\t" << "\n"; } } } // namespace sim<|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2014 Alexander Chumakov * * 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 "utils.h" #include <glib.h> #include <QDebug> #include <wbxml.h> #include <string.h> #include <SignOn/Identity> #include <Accounts/Account> #include <Accounts/Manager> #include <QProcessEnvironment> namespace { const QLatin1String SsoMethod("auth/method"); const QLatin1String AsProviderName("activesync"); const QLatin1String AccountCredId("CredentialsId"); const QLatin1String ExchangeServerPort("connection/port"); const QLatin1String ExchangeServerHost("connection/exchange_server"); const QLatin1String NwSecureConnection("connection/secure_connection"); } void Utils::registerAccount() { Accounts::Manager manager; Accounts::Account *account = manager.account(1); if (!account) { account = manager.createAccount(AsProviderName); } account->setEnabled(true); account->setDisplayName("Main AS Account"); const QProcessEnvironment &env = QProcessEnvironment::systemEnvironment(); const QString &userId = env.value("MY_USER", "<user>"); const QString &serverAddress = env.value("MY_ADDR", "exchange-server.com"); const QString &serverPort = env.value("MY_PORT", "443"); account->setValue("default_credentials_username", userId); account->beginGroup("connection"); account->setValue("exchange_server", serverAddress); account->setValue("port", serverPort); account->endGroup(); account->setValue(SsoMethod, "password"); account->setValue(AccountCredId, "1"); account->setValue(NwSecureConnection, true); account->sync(); // SignOn handling const QString &passwd = env.value("MY_PASS", "<password>"); SignOn::IdentityInfo identityInfo; identityInfo.setUserName(userId); identityInfo.setSecret(passwd, true); SignOn::Identity *const identity = SignOn::Identity::newIdentity(identityInfo); if (!identity) { qDebug() << "[Utils::registerAccount] Cannot create 'identity'"; } else { identity->storeCredentials(); } qDebug() << "[Utils::registerAccount]: account, ID: " << account->id(); } void Utils::hexDump(const char *pData) { const int length = strlen (pData); hexDump (reinterpret_cast<const unsigned char *>(pData), length); } void Utils::hexDump(const unsigned char *pData, int length) { char buffer[20]; QDebug debug = qDebug(); debug.nospace(); for (int i = 0; i < length; ++i) { if (!(i % 16)) { snprintf(buffer, 20, "%4.4x: ", i); debug << buffer; } char byte = pData[i]; char lowByte = (0xFU&byte) + '0'; char highByte = (0xFU&(byte>>4)) + '0'; if (lowByte > '9') { // 0x0A => 'A', etc... lowByte += 'A' - ('9' + 1); } if (highByte > '9') { // 0x0A => 'A', etc... highByte += 'A' - ('9' + 1); } if (byte < 32) { byte = '.'; } debug << highByte << lowByte << "(" << byte << ") "; if (i%16 == 15) { debug << "\n"; } } debug << "\n"; debug.space(); } QString Utils::hexTreeNodeType(int treeNodeType) { QString name; switch (treeNodeType) { case WBXML_TREE_ELEMENT_NODE: name = "WBXML_TREE_ELEMENT_NODE"; break; case WBXML_TREE_TEXT_NODE: name = "WBXML_TREE_TEXT_NODE"; break; case WBXML_TREE_CDATA_NODE: name = "WBXML_TREE_CDATA_NODE"; break; case WBXML_TREE_PI_NODE: name = "WBXML_TREE_PI_NODE"; break; case WBXML_TREE_TREE_NODE: name = "WBXML_TREE_TREE_NODE"; break; default: name = "WBXML_TREE_UNDEFINED"; break; } return name; } QDebug Utils::logNodeName(QDebug debug, WBXMLTag *nodeName) { if (!nodeName) return debug; if (WBXML_VALUE_TOKEN == nodeName->type) { debug << "[WBXML_VALUE_TOKEN: "; const WBXMLTagEntry *const token = nodeName->u.token; if (token) { const WB_TINY *const xmlName = token->xmlName; debug << "ENTRY: "; if (xmlName) { debug << "\"" << xmlName << "\", "; } else { debug << "<null>, "; } debug << "PAGE: " << token->wbxmlCodePage << ", TOKEN: " << token->wbxmlToken; } else { debug << "<null>"; } debug << "]"; } else if (WBXML_VALUE_LITERAL == nodeName->type) { debug << "[WBXML_VALUE_LITERAL: \"" << (const char *)wbxml_buffer_get_cstr(nodeName->u.literal) << "\"]"; } else { debug << "[WBXML_VALUE_UNKNOWN]"; } return debug; } QDebug Utils::logNode(QDebug debug, WBXMLTreeNode *node, int level) { // check if the 'node' exists if (!node) return debug; debug.nospace(); for (int i = 0; i < level; ++i) { debug << " "; } const char *content = (const char *)wbxml_buffer_get_cstr(node->content); if (!strlen(content)) { debug << "Tree node type: " << hexTreeNodeType(node->type); } else { debug << "Tree node type: " << hexTreeNodeType(node->type) << ", content: \"" << content << "\""; } if (node->name) { debug << ", name: \""; Utils::logNodeName(debug, node->name); debug << "\""; } debug << "\n"; debug.space(); WBXMLTreeNode *children = node->children; while (children) { logNode(debug, children, level + 1); children = children->next; } return debug; } void Utils::iconvTest() { GIConv conv = g_iconv_open("utf-8", "ISO8859-1"); } <commit_msg>Added code for playing with codepages<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2014 Alexander Chumakov * * 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 "utils.h" #include <glib.h> #include <QDebug> #include <wbxml.h> #include <string.h> #include <SignOn/Identity> #include <Accounts/Account> #include <Accounts/Manager> #include <QProcessEnvironment> namespace { const QLatin1String SsoMethod("auth/method"); const QLatin1String AsProviderName("activesync"); const QLatin1String AccountCredId("CredentialsId"); const QLatin1String ExchangeServerPort("connection/port"); const QLatin1String ExchangeServerHost("connection/exchange_server"); const QLatin1String NwSecureConnection("connection/secure_connection"); } void Utils::registerAccount() { Accounts::Manager manager; Accounts::Account *account = manager.account(1); if (!account) { account = manager.createAccount(AsProviderName); } account->setEnabled(true); account->setDisplayName("Main AS Account"); const QProcessEnvironment &env = QProcessEnvironment::systemEnvironment(); const QString &userId = env.value("MY_USER", "<user>"); const QString &serverAddress = env.value("MY_ADDR", "exchange-server.com"); const QString &serverPort = env.value("MY_PORT", "443"); account->setValue("default_credentials_username", userId); account->beginGroup("connection"); account->setValue("exchange_server", serverAddress); account->setValue("port", serverPort); account->endGroup(); account->setValue(SsoMethod, "password"); account->setValue(AccountCredId, "1"); account->setValue(NwSecureConnection, true); account->sync(); // SignOn handling const QString &passwd = env.value("MY_PASS", "<password>"); SignOn::IdentityInfo identityInfo; identityInfo.setUserName(userId); identityInfo.setSecret(passwd, true); SignOn::Identity *const identity = SignOn::Identity::newIdentity(identityInfo); if (!identity) { qDebug() << "[Utils::registerAccount] Cannot create 'identity'"; } else { identity->storeCredentials(); } qDebug() << "[Utils::registerAccount]: account, ID: " << account->id(); } void Utils::hexDump(const char *pData) { const int length = strlen (pData); hexDump (reinterpret_cast<const unsigned char *>(pData), length); } void Utils::hexDump(const unsigned char *pData, int length) { char buffer[20]; QDebug debug = qDebug(); debug.nospace(); for (int i = 0; i < length; ++i) { if (!(i % 16)) { snprintf(buffer, 20, "%4.4x: ", i); debug << buffer; } char byte = pData[i]; char lowByte = (0xFU&byte) + '0'; char highByte = (0xFU&(byte>>4)) + '0'; if (lowByte > '9') { // 0x0A => 'A', etc... lowByte += 'A' - ('9' + 1); } if (highByte > '9') { // 0x0A => 'A', etc... highByte += 'A' - ('9' + 1); } if (byte < 32) { byte = '.'; } debug << highByte << lowByte << "(" << byte << ") "; if (i%16 == 15) { debug << "\n"; } } debug << "\n"; debug.space(); } QString Utils::hexTreeNodeType(int treeNodeType) { QString name; switch (treeNodeType) { case WBXML_TREE_ELEMENT_NODE: name = "WBXML_TREE_ELEMENT_NODE"; break; case WBXML_TREE_TEXT_NODE: name = "WBXML_TREE_TEXT_NODE"; break; case WBXML_TREE_CDATA_NODE: name = "WBXML_TREE_CDATA_NODE"; break; case WBXML_TREE_PI_NODE: name = "WBXML_TREE_PI_NODE"; break; case WBXML_TREE_TREE_NODE: name = "WBXML_TREE_TREE_NODE"; break; default: name = "WBXML_TREE_UNDEFINED"; break; } return name; } QDebug Utils::logNodeName(QDebug debug, WBXMLTag *nodeName) { if (!nodeName) return debug; if (WBXML_VALUE_TOKEN == nodeName->type) { debug << "[WBXML_VALUE_TOKEN: "; const WBXMLTagEntry *const token = nodeName->u.token; if (token) { const WB_TINY *const xmlName = token->xmlName; debug << "ENTRY: "; if (xmlName) { debug << "\"" << xmlName << "\", "; } else { debug << "<null>, "; } debug << "PAGE: " << token->wbxmlCodePage << ", TOKEN: " << token->wbxmlToken; } else { debug << "<null>"; } debug << "]"; } else if (WBXML_VALUE_LITERAL == nodeName->type) { debug << "[WBXML_VALUE_LITERAL: \"" << (const char *)wbxml_buffer_get_cstr(nodeName->u.literal) << "\"]"; } else { debug << "[WBXML_VALUE_UNKNOWN]"; } return debug; } QDebug Utils::logNode(QDebug debug, WBXMLTreeNode *node, int level) { // check if the 'node' exists if (!node) return debug; debug.nospace(); for (int i = 0; i < level; ++i) { debug << " "; } const char *content = (const char *)wbxml_buffer_get_cstr(node->content); if (!strlen(content)) { debug << "Tree node type: " << hexTreeNodeType(node->type); } else { debug << "Tree node type: " << hexTreeNodeType(node->type) << ", content: \"" << content << "\""; } if (node->name) { debug << ", name: \""; Utils::logNodeName(debug, node->name); debug << "\""; } debug << "\n"; debug.space(); WBXMLTreeNode *children = node->children; while (children) { logNode(debug, children, level + 1); children = children->next; } return debug; } void Utils::iconvTest() { GError *error = NULL; gsize bytes_read = 0; gsize bytes_written = 0; gchar *const result = g_convert( // Data to be converted "Str: \xF4", -1, // TO <= FROM "utf-8", "ISO8859-1", &bytes_read, &bytes_written, &error); QByteArray outBuffer; outBuffer.append(result, bytes_written); const QString &resultString = QString::fromUtf8(outBuffer); qDebug() << "Utils::iconvTest, Result: " << resultString << ", bytes read: " << bytes_read << ", bytes_written: " << bytes_written << ", error: " << error; Utils::hexDump(outBuffer); } <|endoftext|>
<commit_before>namespace ts_mruby { namespace utils { template<typename T, typename... Args> T* mockable_ptr(Args... args) { #ifndef MOCKING return new T(args...); #else // FIXME it needs mutual exclusion and calling delete ... using T_MOCK = typename T::mock_type; static T_MOCK* ptr = nullptr; if (!ptr) { ptr = new T_MOCK(args...); } return ptr; #endif } } // utils namespace } // ts_mruby namespace <commit_msg>Replace ugly macro with SFINAE<commit_after>#include <type_traits> namespace ts_mruby { namespace utils { namespace { extern void *enabler; /* * meta functions check 'type T' has mock_type or not */ struct has_mock_impl { template<typename T> static std::true_type check(typename T::mock_type*); template<typename T> static std::false_type check(...); }; template<typename T> class has_mock : public decltype(has_mock_impl::check<T>(nullptr)) {}; } // anonymous namespace // Allocate non-mocked object template<typename T, typename... Args, typename std::enable_if<!has_mock<T>::value>::type*& = enabler> T* mockable_ptr(Args... args) { return new T(args...); } // Allocate or get mocked object // FIXME it needs mutual exclusion and calling delete ... template<typename T, typename... Args, typename std::enable_if<has_mock<T>::value>::type*& = enabler> T* mockable_ptr(Args... args) { using T_MOCK = typename T::mock_type; static T_MOCK* ptr = nullptr; if (!ptr) { ptr = new T_MOCK(args...); } return ptr; } } // utils namespace } // ts_mruby namespace <|endoftext|>
<commit_before>/******************************************************************************/ /* Copyright 2015 MAC0431-PROJECT */ /* */ /* 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. */ /******************************************************************************/ // Standard headers #include <array> #include <cstdlib> #include <fstream> #include <cstdlib> #include <iostream> // External headers #include <omp.h> // Waves headers #include "waves/Drop.hpp" using namespace waves; // Waves templates #include "waves/Dimension.tcc" double generate_probability() { return static_cast<double>(rand())/RAND_MAX; } std::vector<Drop> generate_drops(unsigned int timestamp, double drop_probability) { std::vector<Drop> drops; for (unsigned int i = 0; i < timestamp; i++) { if (generate_probability() < drop_probability) { drops.emplace_back(i); } } return drops; } int main(int argc, char **argv) { if (argc != 3) { std::cerr << "USAGE: " << argv[0] << " param_file num_procs" << std::endl; return EXIT_FAILURE; } waves::Dimension<2> lake_dimensions; waves::Dimension<2> matrix_dimensions; unsigned int time; double speed; double height_error; unsigned int num_iterations; double drop_probability; unsigned int seed; std::ifstream input(argv[1]); input >> lake_dimensions; input >> matrix_dimensions; input >> time; input >> speed; input >> height_error; input >> num_iterations; input >> drop_probability; input >> seed; omp_set_num_threads(atoi(argv[2])); srand(seed); auto drops = generate_drops(num_iterations, drop_probability/100); for (auto drop : drops) { std::cout << drop.time() << std::endl; } return EXIT_SUCCESS; } <commit_msg>Check initialization of variables<commit_after>/******************************************************************************/ /* Copyright 2015 MAC0431-PROJECT */ /* */ /* 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. */ /******************************************************************************/ // Standard headers #include <array> #include <cstdlib> #include <fstream> #include <cstdlib> #include <iostream> // External headers #include <omp.h> // Waves headers #include "waves/Drop.hpp" using namespace waves; // Waves templates #include "waves/Dimension.tcc" double generate_probability() { return static_cast<double>(rand())/RAND_MAX; } std::vector<Drop> generate_drops(unsigned int timestamp, double drop_probability) { std::vector<Drop> drops; for (unsigned int i = 0; i < timestamp; i++) { if (generate_probability() < drop_probability) { drops.emplace_back(i); } } return drops; } int main(int argc, char **argv) { if (argc != 3) { std::cerr << "USAGE: " << argv[0] << " param_file num_procs" << std::endl; return EXIT_FAILURE; } std::string input_file(argv[1]); int num_threads = (atoi(argv[2])) <= 0 ? atoi(argv[2]) : omp_get_num_threads(); // OpenMP initialization omp_set_num_threads(num_threads); waves::Dimension<2> lake_dimensions; waves::Dimension<2> matrix_dimensions; unsigned int time; double speed; double height_error; unsigned int num_iterations; double drop_probability; unsigned int seed; std::ifstream input(input_file); input >> lake_dimensions; input >> matrix_dimensions; input >> time; input >> speed; input >> height_error; input >> num_iterations; input >> drop_probability; input >> seed; srand(seed); auto drops = generate_drops(num_iterations, drop_probability/100); for (auto drop : drops) { std::cout << drop.time() << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <string> #include <sstream> #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/ostreamwrapper.h> #include <openssl/bn.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/asn1.h> #include <openssl/objects.h> #include "status.h" #include "protocols.h" #include "chat.h" #include "types.h" using std::string; using std::stringstream; Status status; Status::Status() { srand(time(NULL)); rsa = 0; _online = 0; _difficulty = Difficulty::Peaceful; _level = "default"; _debug = true; } Status::~Status() { RSA_free(rsa); } int Status::keygen() { #if OPENSSL_VERSION_NUMBER >= 0x010100000 BIGNUM *e = BN_new(); BN_set_word(e, 65537); rsa = RSA_new(); RSA_generate_key_ex(rsa, 1024, e, NULL); BN_free(e); #else rsa = RSA_generate_key(1024, 65537, NULL, NULL); #endif if (rsa == NULL) return -1; return 0; } int Status::pubkey(BIO *bio) { // TODO: Error checking i2d_RSA_PUBKEY_bio(bio, rsa); return 0; } int Status::decrypt(std::vector<uint8_t> &from, std::vector<uint8_t> &to) { to.resize(RSA_size(rsa)); int ret = RSA_private_decrypt(from.size(), from.data(), to.data(), rsa, RSA_PKCS1_PADDING); if (ret != -1) to.resize(ret); return ret; } string Status::version() const { return Protocol::protocols.versionString(); } int Status::protocol() const { return Protocol::protocols.versionMax(); } int Status::playersMax() const { return 128; } std::string Status::description() const { return "Minecraft custom server (work in progress)"; } string Status::toJson() const { using namespace rapidjson; Document d(kObjectType); auto &a = d.GetAllocator(); Value ver(kObjectType); ver.AddMember("name", StringRef(version().c_str()), a); ver.AddMember("protocol", protocol(), a); d.AddMember("version", ver, a); Value player(kObjectType); player.AddMember("max", playersMax(), a); player.AddMember("online", playersOnline(), a); d.AddMember("players", player, a); Value desc(kObjectType); Chat::Text text(description()); text.addTo(desc, a); d.AddMember("description", desc, a); stringstream ss; OStreamWrapper osw(ss); Writer<OStreamWrapper> writer(osw); d.Accept(writer); return ss.str(); } <commit_msg>Check for RSA generation success<commit_after>#include <string> #include <sstream> #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/ostreamwrapper.h> #include <openssl/bn.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/asn1.h> #include <openssl/objects.h> #include "status.h" #include "protocols.h" #include "chat.h" #include "types.h" using std::string; using std::stringstream; Status status; Status::Status() { srand(time(NULL)); rsa = 0; _online = 0; _difficulty = Difficulty::Peaceful; _level = "default"; _debug = true; } Status::~Status() { RSA_free(rsa); } int Status::keygen() { #if OPENSSL_VERSION_NUMBER >= 0x010100000 BIGNUM *e = BN_new(); BN_set_word(e, 65537); rsa = RSA_new(); int ret = RSA_generate_key_ex(rsa, 1024, e, NULL); BN_free(e); if (!ret) return -1; #else rsa = RSA_generate_key(1024, 65537, NULL, NULL); if (rsa == NULL) return -1; #endif return 0; } int Status::pubkey(BIO *bio) { // TODO: Error checking i2d_RSA_PUBKEY_bio(bio, rsa); return 0; } int Status::decrypt(std::vector<uint8_t> &from, std::vector<uint8_t> &to) { to.resize(RSA_size(rsa)); int ret = RSA_private_decrypt(from.size(), from.data(), to.data(), rsa, RSA_PKCS1_PADDING); if (ret != -1) to.resize(ret); return ret; } string Status::version() const { return Protocol::protocols.versionString(); } int Status::protocol() const { return Protocol::protocols.versionMax(); } int Status::playersMax() const { return 128; } std::string Status::description() const { return "Minecraft custom server (work in progress)"; } string Status::toJson() const { using namespace rapidjson; Document d(kObjectType); auto &a = d.GetAllocator(); Value ver(kObjectType); ver.AddMember("name", StringRef(version().c_str()), a); ver.AddMember("protocol", protocol(), a); d.AddMember("version", ver, a); Value player(kObjectType); player.AddMember("max", playersMax(), a); player.AddMember("online", playersOnline(), a); d.AddMember("players", player, a); Value desc(kObjectType); Chat::Text text(description()); text.addTo(desc, a); d.AddMember("description", desc, a); stringstream ss; OStreamWrapper osw(ss); Writer<OStreamWrapper> writer(osw); d.Accept(writer); return ss.str(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkShepardMethod.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Paul A, Hsieh for bug fixes Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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 "vtkShepardMethod.h" #include "vtkMath.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkShepardMethod* vtkShepardMethod::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkShepardMethod"); if(ret) { return (vtkShepardMethod*)ret; } // If the factory was unable to create the object, then create it here. return new vtkShepardMethod; } // Construct with sample dimensions=(50,50,50) and so that model bounds are // automatically computed from input. Null value for each unvisited output // point is 0.0. Maximum distance is 0.25. vtkShepardMethod::vtkShepardMethod() { this->MaximumDistance = 0.25; this->ModelBounds[0] = 0.0; this->ModelBounds[1] = 0.0; this->ModelBounds[2] = 0.0; this->ModelBounds[3] = 0.0; this->ModelBounds[4] = 0.0; this->ModelBounds[5] = 0.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; this->NullValue = 0.0; } // Compute ModelBounds from input geometry. float vtkShepardMethod::ComputeModelBounds(float origin[3], float spacing[3]) { float *bounds, maxDist; int i, adjustBounds=0; // compute model bounds if not set previously if ( this->ModelBounds[0] >= this->ModelBounds[1] || this->ModelBounds[2] >= this->ModelBounds[3] || this->ModelBounds[4] >= this->ModelBounds[5] ) { adjustBounds = 1; bounds = this->GetInput()->GetBounds(); } else { bounds = this->ModelBounds; } for (maxDist=0.0, i=0; i<3; i++) { if ( (bounds[2*i+1] - bounds[2*i]) > maxDist ) { maxDist = bounds[2*i+1] - bounds[2*i]; } } maxDist *= this->MaximumDistance; // adjust bounds so model fits strictly inside (only if not set previously) if ( adjustBounds ) { for (i=0; i<3; i++) { this->ModelBounds[2*i] = bounds[2*i] - maxDist; this->ModelBounds[2*i+1] = bounds[2*i+1] + maxDist; } } // Set volume origin and data spacing for (i=0; i<3; i++) { origin[i] = this->ModelBounds[2*i]; spacing[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } this->GetOutput()->SetOrigin(origin); this->GetOutput()->SetSpacing(spacing); return maxDist; } void vtkShepardMethod::Execute() { int ptId, i, j, k; float *px, x[3], s, *sum, spacing[3], origin[3]; float maxDistance, distance2, inScalar; vtkScalars *inScalars; vtkScalars *newScalars; int numPts, numNewPts, idx; int min[3], max[3]; int jkFactor; vtkDataSet *input = this->GetInput(); vtkStructuredPoints *output = this->GetOutput(); vtkDebugMacro(<< "Executing Shepard method"); // // Check input // if ( (numPts=input->GetNumberOfPoints()) < 1 ) { vtkErrorMacro(<<"Points must be defined!"); return; } if ( (inScalars = input->GetPointData()->GetScalars()) == NULL ) { vtkErrorMacro(<<"Scalars must be defined!"); return; } // // Allocate // numNewPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2]; newScalars = vtkScalars::New(); newScalars->SetNumberOfScalars(numNewPts); sum = new float[numNewPts]; for (i=0; i<numNewPts; i++) { newScalars->SetScalar(i,0.0); sum[i] = 0.0; } output->SetDimensions(this->GetSampleDimensions()); maxDistance = this->ComputeModelBounds(origin,spacing); // // Traverse all input points. // Each input point affects voxels within maxDistance. // for (ptId=0; ptId < numPts; ptId++) { px = input->GetPoint(ptId); inScalar = inScalars->GetScalar(ptId); for (i=0; i<3; i++) //compute dimensional bounds in data set { float amin = (float)((px[i] - maxDistance) - origin[i]) / spacing[i]; float amax = (float)((px[i] + maxDistance) - origin[i]) / spacing[i]; min[i] = (int) amin; max[i] = (int) amax; if (min[i] < amin) { min[i]++; // round upward to nearest integer to get min[i] } if (max[i] > amax) { max[i]--; // round downward to nearest integer to get max[i] } if (min[i] < 0) { min[i] = 0; // valid range check } if (max[i] >= this->SampleDimensions[i]) { max[i] = this->SampleDimensions[i] - 1; } } for (i=0; i<3; i++) //compute dimensional bounds in data set { min[i] = (int) ((float)((px[i] - maxDistance) - origin[i]) / spacing[i]); max[i] = (int) ((float)((px[i] + maxDistance) - origin[i]) / spacing[i]); if (min[i] < 0) { min[i] = 0; } if (max[i] >= this->SampleDimensions[i]) { max[i] = this->SampleDimensions[i] - 1; } } jkFactor = this->SampleDimensions[0]*this->SampleDimensions[1]; for (k = min[2]; k <= max[2]; k++) { x[2] = spacing[2] * k + origin[2]; for (j = min[1]; j <= max[1]; j++) { x[1] = spacing[1] * j + origin[1]; for (i = min[0]; i <= max[0]; i++) { x[0] = spacing[0] * i + origin[0]; idx = jkFactor*k + this->SampleDimensions[0]*j + i; distance2 = vtkMath::Distance2BetweenPoints(x,px); if ( distance2 == 0.0 ) { sum[idx] = VTK_LARGE_FLOAT; newScalars->SetScalar(idx,VTK_LARGE_FLOAT); } else { s = newScalars->GetScalar(idx); sum[idx] += 1.0 / distance2; newScalars->SetScalar(idx,s+(inScalar/distance2)); } } } } } // // Run through scalars and compute final values // for (ptId=0; ptId<numNewPts; ptId++) { s = newScalars->GetScalar(ptId); if ( sum[ptId] != 0.0 ) { newScalars->SetScalar(ptId,s/sum[ptId]); } else { newScalars->SetScalar(ptId,this->NullValue); } } // // Update self // delete [] sum; output->GetPointData()->SetScalars(newScalars); newScalars->Delete(); } // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int dim[3]) { int dataDim, i; vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != this->SampleDimensions[1] || dim[2] != this->SampleDimensions[2] ) { if ( dim[0]<1 || dim[1]<1 || dim[2]<1 ) { vtkErrorMacro (<< "Bad Sample Dimensions, retaining previous values"); return; } for (dataDim=0, i=0; i<3 ; i++) { if (dim[i] > 1) { dataDim++; } } if ( dataDim < 3 ) { vtkErrorMacro(<<"Sample dimensions must define a volume!"); return; } for ( i=0; i<3; i++) { this->SampleDimensions[i] = dim[i]; } this->Modified(); } } void vtkShepardMethod::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToStructuredPointsFilter::PrintSelf(os,indent); os << indent << "Maximum Distance: " << this->MaximumDistance << "\n"; os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "Null Value: " << this->NullValue << "\n"; } <commit_msg>ENH:Added support for Abort flag, ProgressMethod<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkShepardMethod.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Paul A, Hsieh for bug fixes Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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 "vtkShepardMethod.h" #include "vtkMath.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------- vtkShepardMethod* vtkShepardMethod::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkShepardMethod"); if(ret) { return (vtkShepardMethod*)ret; } // If the factory was unable to create the object, then create it here. return new vtkShepardMethod; } // Construct with sample dimensions=(50,50,50) and so that model bounds are // automatically computed from input. Null value for each unvisited output // point is 0.0. Maximum distance is 0.25. vtkShepardMethod::vtkShepardMethod() { this->MaximumDistance = 0.25; this->ModelBounds[0] = 0.0; this->ModelBounds[1] = 0.0; this->ModelBounds[2] = 0.0; this->ModelBounds[3] = 0.0; this->ModelBounds[4] = 0.0; this->ModelBounds[5] = 0.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; this->NullValue = 0.0; } // Compute ModelBounds from input geometry. float vtkShepardMethod::ComputeModelBounds(float origin[3], float spacing[3]) { float *bounds, maxDist; int i, adjustBounds=0; // compute model bounds if not set previously if ( this->ModelBounds[0] >= this->ModelBounds[1] || this->ModelBounds[2] >= this->ModelBounds[3] || this->ModelBounds[4] >= this->ModelBounds[5] ) { adjustBounds = 1; bounds = this->GetInput()->GetBounds(); } else { bounds = this->ModelBounds; } for (maxDist=0.0, i=0; i<3; i++) { if ( (bounds[2*i+1] - bounds[2*i]) > maxDist ) { maxDist = bounds[2*i+1] - bounds[2*i]; } } maxDist *= this->MaximumDistance; // adjust bounds so model fits strictly inside (only if not set previously) if ( adjustBounds ) { for (i=0; i<3; i++) { this->ModelBounds[2*i] = bounds[2*i] - maxDist; this->ModelBounds[2*i+1] = bounds[2*i+1] + maxDist; } } // Set volume origin and data spacing for (i=0; i<3; i++) { origin[i] = this->ModelBounds[2*i]; spacing[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } this->GetOutput()->SetOrigin(origin); this->GetOutput()->SetSpacing(spacing); return maxDist; } void vtkShepardMethod::Execute() { int ptId, i, j, k; float *px, x[3], s, *sum, spacing[3], origin[3]; float maxDistance, distance2, inScalar; vtkScalars *inScalars; vtkScalars *newScalars; int numPts, numNewPts, idx; int min[3], max[3]; int jkFactor; vtkDataSet *input = this->GetInput(); vtkStructuredPoints *output = this->GetOutput(); vtkDebugMacro(<< "Executing Shepard method"); // Check input // if ( (numPts=input->GetNumberOfPoints()) < 1 ) { vtkErrorMacro(<<"Points must be defined!"); return; } if ( (inScalars = input->GetPointData()->GetScalars()) == NULL ) { vtkErrorMacro(<<"Scalars must be defined!"); return; } // Allocate // numNewPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2]; newScalars = vtkScalars::New(); newScalars->SetNumberOfScalars(numNewPts); sum = new float[numNewPts]; for (i=0; i<numNewPts; i++) { newScalars->SetScalar(i,0.0); sum[i] = 0.0; } output->SetDimensions(this->GetSampleDimensions()); maxDistance = this->ComputeModelBounds(origin,spacing); // Traverse all input points. // Each input point affects voxels within maxDistance. // int abortExecute=0; for (ptId=0; ptId < numPts && !abortExecute; ptId++) { if ( ! (ptId % 1000) ) { vtkDebugMacro(<<"Inserting point #" << ptId); this->UpdateProgress (ptId/numPts); if (this->GetAbortExecute()) { abortExecute = 1; break; } } px = input->GetPoint(ptId); inScalar = inScalars->GetScalar(ptId); for (i=0; i<3; i++) //compute dimensional bounds in data set { float amin = (float)((px[i] - maxDistance) - origin[i]) / spacing[i]; float amax = (float)((px[i] + maxDistance) - origin[i]) / spacing[i]; min[i] = (int) amin; max[i] = (int) amax; if (min[i] < amin) { min[i]++; // round upward to nearest integer to get min[i] } if (max[i] > amax) { max[i]--; // round downward to nearest integer to get max[i] } if (min[i] < 0) { min[i] = 0; // valid range check } if (max[i] >= this->SampleDimensions[i]) { max[i] = this->SampleDimensions[i] - 1; } } for (i=0; i<3; i++) //compute dimensional bounds in data set { min[i] = (int) ((float)((px[i] - maxDistance) - origin[i]) / spacing[i]); max[i] = (int) ((float)((px[i] + maxDistance) - origin[i]) / spacing[i]); if (min[i] < 0) { min[i] = 0; } if (max[i] >= this->SampleDimensions[i]) { max[i] = this->SampleDimensions[i] - 1; } } jkFactor = this->SampleDimensions[0]*this->SampleDimensions[1]; for (k = min[2]; k <= max[2]; k++) { x[2] = spacing[2] * k + origin[2]; for (j = min[1]; j <= max[1]; j++) { x[1] = spacing[1] * j + origin[1]; for (i = min[0]; i <= max[0]; i++) { x[0] = spacing[0] * i + origin[0]; idx = jkFactor*k + this->SampleDimensions[0]*j + i; distance2 = vtkMath::Distance2BetweenPoints(x,px); if ( distance2 == 0.0 ) { sum[idx] = VTK_LARGE_FLOAT; newScalars->SetScalar(idx,VTK_LARGE_FLOAT); } else { s = newScalars->GetScalar(idx); sum[idx] += 1.0 / distance2; newScalars->SetScalar(idx,s+(inScalar/distance2)); } } } } } // Run through scalars and compute final values // for (ptId=0; ptId<numNewPts; ptId++) { s = newScalars->GetScalar(ptId); if ( sum[ptId] != 0.0 ) { newScalars->SetScalar(ptId,s/sum[ptId]); } else { newScalars->SetScalar(ptId,this->NullValue); } } // Update self // delete [] sum; output->GetPointData()->SetScalars(newScalars); newScalars->Delete(); } // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int dim[3]) { int dataDim, i; vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != this->SampleDimensions[1] || dim[2] != this->SampleDimensions[2] ) { if ( dim[0]<1 || dim[1]<1 || dim[2]<1 ) { vtkErrorMacro (<< "Bad Sample Dimensions, retaining previous values"); return; } for (dataDim=0, i=0; i<3 ; i++) { if (dim[i] > 1) { dataDim++; } } if ( dataDim < 3 ) { vtkErrorMacro(<<"Sample dimensions must define a volume!"); return; } for ( i=0; i<3; i++) { this->SampleDimensions[i] = dim[i]; } this->Modified(); } } void vtkShepardMethod::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToStructuredPointsFilter::PrintSelf(os,indent); os << indent << "Maximum Distance: " << this->MaximumDistance << "\n"; os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "Null Value: " << this->NullValue << "\n"; } <|endoftext|>
<commit_before>/* * split≈ * External object for Jamoma AudioGraph * Copyright © 2008 by Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "maxAudioGraph.h" int TTCLASSWRAPPERMAX_EXPORT main(void) { /*MaxAudioGraphWrappedClassOptionsPtr options = new MaxAudioGraphWrappedClassOptions; TTValue value(0); TTAudioGraphInit(); options->append(TT("nonadapting"), value); // don't change the number of out-channels in response to changes in the number of in-channels options->append(TT("argumentDefinesNumInlets"), value); options->append(TT("argumentDefinesNumOutlets"), value); wrapAsMaxAudioGraph(TT("audio.pick"), "jcom.pick≈", NULL, options); return wrapAsMaxAudioGraph(TT("audio.pick"), "pick≈", NULL, options);*/ TTAudioGraphInit(); wrapAsMaxAudioGraph(TT("audio.pick"), "jcom.pick≈", NULL); wrapAsMaxAudioGraph(TT("audio.pick"), "pick≈", NULL); return 0; } <commit_msg>using 'nonadaptive' and 'userCanSetNumChannels' ClassOptions to prevent that number of outputs is the same than number of inputs<commit_after>/* * split≈ * External object for Jamoma AudioGraph * Copyright © 2008 by Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "maxAudioGraph.h" int TTCLASSWRAPPERMAX_EXPORT main(void) { MaxAudioGraphWrappedClassOptionsPtr options = new MaxAudioGraphWrappedClassOptions; TTValue value(0); TTAudioGraphInit(); options->append(TT("nonadapting"), value); // don't change the number of out-channels in response to changes in the number of in-channels options->append(TT("userCanSetNumChannels"), kTTBoolNo); wrapAsMaxAudioGraph(TT("audio.pick"), "jcom.pick≈", NULL, options); return wrapAsMaxAudioGraph(TT("audio.pick"), "pick≈", NULL, options); //TTAudioGraphInit(); //wrapAsMaxAudioGraph(TT("audio.pick"), "jcom.pick≈", NULL); //wrapAsMaxAudioGraph(TT("audio.pick"), "pick≈", NULL); //return 0; } <|endoftext|>
<commit_before>// Copyright Benoit Blanchon 2014 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson #pragma once #include "JsonBuffer.hpp" namespace ArduinoJson { // Implements a JsonBuffer with dynamic memory allocation. // You are strongly encouraged to consider using StaticJsonBuffer which is much // more suitable for embedded systems. class DynamicJsonBuffer : public JsonBuffer { public: DynamicJsonBuffer() : _next(NULL), _size(0) {} ~DynamicJsonBuffer() { delete _next; } size_t size() const { return _size + (_next ? _next->size() : 0); } size_t blockCount() const { return 1 + (_next ? _next->blockCount() : 0); } static const size_t BLOCK_CAPACITY = 32; protected: virtual void* alloc(size_t bytes) { if (canAllocInThisBlock(bytes)) return allocInThisBlock(bytes); else if (canAllocInOtherBlocks(bytes)) return allocInOtherBlocks(bytes); else return NULL; } private: bool canAllocInThisBlock(size_t bytes) const { return _size + bytes <= BLOCK_CAPACITY; } void* allocInThisBlock(size_t bytes) { void* p = _buffer + _size; _size += bytes; return p; } bool canAllocInOtherBlocks(size_t bytes) const { // by design a DynamicJsonBuffer can't alloc a block bigger than // BLOCK_CAPACITY return bytes <= BLOCK_CAPACITY; } void* allocInOtherBlocks(size_t bytes) { if (!_next) { _next = new (std::nothrow) DynamicJsonBuffer(); if (!_next) return NULL; } return _next->alloc(bytes); } size_t _size; uint8_t _buffer[BLOCK_CAPACITY]; DynamicJsonBuffer* _next; }; } <commit_msg>Removed std::nothrow because it's not supported in Arduino<commit_after>// Copyright Benoit Blanchon 2014 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson #pragma once #include "JsonBuffer.hpp" namespace ArduinoJson { // Implements a JsonBuffer with dynamic memory allocation. // You are strongly encouraged to consider using StaticJsonBuffer which is much // more suitable for embedded systems. class DynamicJsonBuffer : public JsonBuffer { public: DynamicJsonBuffer() : _next(NULL), _size(0) {} ~DynamicJsonBuffer() { delete _next; } size_t size() const { return _size + (_next ? _next->size() : 0); } size_t blockCount() const { return 1 + (_next ? _next->blockCount() : 0); } static const size_t BLOCK_CAPACITY = 32; protected: virtual void* alloc(size_t bytes) { if (canAllocInThisBlock(bytes)) return allocInThisBlock(bytes); else if (canAllocInOtherBlocks(bytes)) return allocInOtherBlocks(bytes); else return NULL; } private: bool canAllocInThisBlock(size_t bytes) const { return _size + bytes <= BLOCK_CAPACITY; } void* allocInThisBlock(size_t bytes) { void* p = _buffer + _size; _size += bytes; return p; } bool canAllocInOtherBlocks(size_t bytes) const { // by design a DynamicJsonBuffer can't alloc a block bigger than // BLOCK_CAPACITY return bytes <= BLOCK_CAPACITY; } void* allocInOtherBlocks(size_t bytes) { if (!_next) { _next = new DynamicJsonBuffer(); if (!_next) return NULL; } return _next->alloc(bytes); } size_t _size; uint8_t _buffer[BLOCK_CAPACITY]; DynamicJsonBuffer* _next; }; } <|endoftext|>
<commit_before>/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_ALGORITHMS_HISTOGRAM_MATCHING_HPP #define PIC_ALGORITHMS_HISTOGRAM_MATCHING_HPP #include "../base.hpp" #include "../image.hpp" #include "../image_vec.hpp" #include "../histogram.hpp" #include "../util/std_util.hpp" namespace pic { class HistogramMatching { protected: int nBin; bool bClipping; float clip_value; /** * @brief computeHistograms * @param img_s * @param img_t * @param hist_s * @param hist_t * @param lut */ void computeHistograms(Image *img_s, Image *img_t, Histogram *hist_s, Histogram *hist_t, std::vector<int *> &lut) { if(img_s == NULL) { return; } uint clip_value_ui = uint(clip_value * float(img_s->nPixels() / nBin)); int channels = img_s->channels; for(int i = 0; i < channels; i++) { hist_s[i].calculate(img_s, VS_LIN, nBin, NULL, i); if(img_t != NULL) { hist_t[i].calculate(img_t, VS_LIN, nBin, NULL, i); } else { uint value = MAX(img_s->nPixels() / nBin, 1); hist_t[i].uniform(hist_s[i].getfMin(), hist_s[i].getfMax(), value, VS_LIN, nBin); } if(bClipping) { hist_s[i].clip(clip_value_ui); hist_t[i].clip(clip_value_ui); } hist_s[i].cumulativef(true); hist_t[i].cumulativef(true); float *c_s = hist_s[i].getCumulativef(); float *c_t = hist_t[i].getCumulativef(); int *tmp_lut = new int[nBin]; for(int j = 0; j < nBin; j++) { float x = c_s[j]; float *ptr = std::upper_bound(c_t, c_t + nBin, x); tmp_lut[j] = MAX((int)(ptr - c_t), 0); } lut.push_back(tmp_lut); } } public: /** * @brief HistogramMatching */ HistogramMatching() { update(256, -1.0f); } /** * @brief update * @param nBin * @param clip_value */ void update(int nBin, float clip_value = 1.0f) { this->nBin = nBin > 1 ? nBin : 256; this->clip_value = clip_value; bClipping = clip_value > 0.0f; } /** * @brief Process * @param imgIn * @param imgOut * @return */ Image *Process(ImageVec imgIn, Image *imgOut = NULL) { Image *img_source = NULL; //imgIn[0] Image *img_target = NULL; //imgIn[1] int count = 0; if(ImageVecCheck(imgIn, 1)) { img_source = imgIn[0]; count = 1; } if(ImageVecCheck(imgIn, 2)) { img_target = imgIn[1]; if(imgIn[0]->channels != imgIn[1]->channels) { return imgOut; } count = 2; } if(count == 0) { return imgOut; } count--; if(imgOut == NULL) { imgOut = imgIn[count]->clone(); } else { if(!imgOut->isSimilarType(imgIn[count])) { imgOut = imgIn[count]->allocateSimilarOne(); } } int channels = img_source->channels; Histogram *h_source = new Histogram[channels]; Histogram *h_target = new Histogram[channels]; std::vector<int *> lut; computeHistograms(img_source, img_target, h_source, h_target, lut); for(int i = 0; i < imgOut->size(); i += channels) { for(int j = 0; j < channels; j++) { int k = i + j; int ind_source = h_source[j].project(img_source->data[k]); int ind_target = lut[j][ind_source]; imgOut->data[k] = h_target[j].unproject(ind_target); } } delete[] h_source; delete[] h_target; stdVectorArrayClear(lut); return imgOut; } /** * @brief execute * @param img_source * @param img_target * @param imgOut * @return */ static Image* execute(Image *img_source, Image *img_target, Image *imgOut = NULL) { HistogramMatching hm; imgOut = hm.Process(Double(img_source, img_target), imgOut); return imgOut; } /** * @brief executeEqualization * @param img * @param imgOut * @param clip_value * @return */ static Image* executeEqualization(Image *img, Image *imgOut = NULL, float clip_value = 0.9f) { HistogramMatching hm; hm.update(256, clip_value); imgOut = hm.Process(Double(img, NULL), imgOut); return imgOut; } }; } // end namespace pic #endif /* PIC_ALGORITHMS_HISTOGRAM_MATCHING_HPP */ <commit_msg>Update histogram_matching.hpp<commit_after>/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_ALGORITHMS_HISTOGRAM_MATCHING_HPP #define PIC_ALGORITHMS_HISTOGRAM_MATCHING_HPP #include "../base.hpp" #include "../image.hpp" #include "../image_vec.hpp" #include "../histogram.hpp" #include "../util/std_util.hpp" namespace pic { class HistogramMatching { protected: int nBin; bool bClipping; float clip_value; /** * @brief computeHistograms * @param img_s * @param img_t * @param hist_s * @param hist_t */ void computeHistograms(Image *img_s, Image *img_t, Histogram *hist_s, Histogram *hist_t) { if(img_s == NULL) { return; } int channels = img_s->channels; uint clip_value_ui = uint(clip_value * float(img_s->nPixels() / nBin)); for(int i = 0; i < channels; i++) { hist_s[i].calculate(img_s, VS_LIN, nBin, NULL, i); if(img_t != NULL) { hist_t[i].calculate(img_t, VS_LIN, nBin, NULL, i); } else { uint value = MAX(img_s->nPixels() / nBin, 1); hist_t[i].uniform(hist_s[i].getfMin(), hist_s[i].getfMax(), value, VS_LIN, nBin); } if(bClipping) { hist_s[i].clip(clip_value_ui); hist_t[i].clip(clip_value_ui); } } } /** * @brief computeLUT * @param hist_s * @param hist_t * @param lut * @param channels */ void computeLUT(Histogram *hist_s, Histogram *hist_t, std::vector<int *> &lut, int channels) { for(int i = 0 ; i < channels; i++) { hist_s[i].cumulativef(true); hist_t[i].cumulativef(true); float *c_s = hist_s[i].getCumulativef(); float *c_t = hist_t[i].getCumulativef(); int *tmp_lut = new int[nBin]; for(int j = 0; j < nBin; j++) { float x = c_s[j]; float *ptr = std::upper_bound(c_t, c_t + nBin, x); tmp_lut[j] = MAX((int)(ptr - c_t), 0); } lut.push_back(tmp_lut); } } public: /** * @brief HistogramMatching */ HistogramMatching() { update(256, -1.0f); } /** * @brief update * @param nBin * @param clip_value */ void update(int nBin, float clip_value = 1.0f) { this->nBin = nBin > 1 ? nBin : 256; this->clip_value = clip_value; bClipping = clip_value > 0.0f; } /** * @brief Process * @param imgIn * @param imgOut * @return */ Image *Process(ImageVec imgIn, Image *imgOut = NULL) { Image *img_source = NULL; //imgIn[0] Image *img_target = NULL; //imgIn[1] int count = 0; if(ImageVecCheck(imgIn, 1)) { img_source = imgIn[0]; count = 1; } if(ImageVecCheck(imgIn, 2)) { img_target = imgIn[1]; if(imgIn[0]->channels != imgIn[1]->channels) { return imgOut; } count = 2; } if(count == 0) { return imgOut; } count--; if(imgOut == NULL) { imgOut = imgIn[count]->clone(); } else { if(!imgOut->isSimilarType(imgIn[count])) { imgOut = imgIn[count]->allocateSimilarOne(); } } int channels = img_source->channels; Histogram *h_source = new Histogram[channels]; Histogram *h_target = new Histogram[channels]; computeHistograms(img_source, img_target, h_source, h_target); std::vector<int *> lut; computeLUT(h_source, h_target, channels, lut) for(int i = 0; i < imgOut->size(); i += channels) { for(int j = 0; j < channels; j++) { int k = i + j; int ind_source = h_source[j].project(img_source->data[k]); int ind_target = lut[j][ind_source]; imgOut->data[k] = h_target[j].unproject(ind_target); } } delete[] h_source; delete[] h_target; stdVectorArrayClear(lut); return imgOut; } /** * @brief execute * @param img_source * @param img_target * @param imgOut * @return */ static Image* execute(Image *img_source, Image *img_target, Image *imgOut = NULL) { HistogramMatching hm; imgOut = hm.Process(Double(img_source, img_target), imgOut); return imgOut; } /** * @brief executeEqualization * @param img * @param imgOut * @param clip_value * @return */ static Image* executeEqualization(Image *img, Image *imgOut = NULL, float clip_value = 0.9f) { HistogramMatching hm; hm.update(256, clip_value); imgOut = hm.Process(Double(img, NULL), imgOut); return imgOut; } }; } // end namespace pic #endif /* PIC_ALGORITHMS_HISTOGRAM_MATCHING_HPP */ <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "OgreRenderingModule.h" #include "Renderer.h" #include "EC_OgrePlaceable.h" #include <Ogre.h> #include "XMLUtilities.h" #include <QDomDocument> using namespace RexTypes; namespace OgreRenderer { EC_OgrePlaceable::EC_OgrePlaceable(Foundation::ModuleInterface* module) : renderer_(checked_static_cast<OgreRenderingModule*>(module)->GetRenderer()), scene_node_(0), link_scene_node_(0), attached_(false), select_priority_(0) { RendererPtr renderer = renderer_.lock(); Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); link_scene_node_ = scene_mgr->createSceneNode(); scene_node_ = scene_mgr->createSceneNode(); link_scene_node_->addChild(scene_node_); // In case the placeable is used for camera control, set fixed yaw axis link_scene_node_->setFixedYawAxis(true, Ogre::Vector3::UNIT_Z); } EC_OgrePlaceable::~EC_OgrePlaceable() { if (renderer_.expired()) return; RendererPtr renderer = renderer_.lock(); Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); if (scene_node_ && link_scene_node_) { link_scene_node_->removeChild(scene_node_); } if (scene_node_) { scene_mgr->destroySceneNode(scene_node_); scene_node_ = 0; } if (link_scene_node_) { DetachNode(); scene_mgr->destroySceneNode(link_scene_node_); link_scene_node_ = 0; } } void EC_OgrePlaceable::SetParent(Foundation::ComponentPtr placeable) { if ((placeable.get() != 0) && (!dynamic_cast<EC_OgrePlaceable*>(placeable.get()))) { OgreRenderingModule::LogError("Attempted to set parent placeable which is not " + TypeNameStatic()); return; } DetachNode(); parent_ = placeable; AttachNode(); } Vector3df EC_OgrePlaceable::GetPosition() const { const Ogre::Vector3& pos = link_scene_node_->getPosition(); return Vector3df(pos.x, pos.y, pos.z); } Quaternion EC_OgrePlaceable::GetOrientation() const { const Ogre::Quaternion& orientation = link_scene_node_->getOrientation(); return Quaternion(orientation.x, orientation.y, orientation.z, orientation.w); } Vector3df EC_OgrePlaceable::GetScale() const { const Ogre::Vector3& scale = scene_node_->getScale(); return Vector3df(scale.x, scale.y, scale.z); } Vector3df EC_OgrePlaceable::GetLocalXAxis() const { const Ogre::Vector3& xaxis = link_scene_node_->getOrientation().xAxis(); return Vector3df(xaxis.x, xaxis.y, xaxis.z); } QVector3D EC_OgrePlaceable::GetQLocalXAxis() const { Vector3df xaxis= GetLocalXAxis(); return QVector3D(xaxis.x, xaxis.y, xaxis.z); } Vector3df EC_OgrePlaceable::GetLocalYAxis() const { const Ogre::Vector3& yaxis = link_scene_node_->getOrientation().yAxis(); return Vector3df(yaxis.x, yaxis.y, yaxis.z); } QVector3D EC_OgrePlaceable::GetQLocalYAxis() const { Vector3df yaxis= GetLocalYAxis(); return QVector3D(yaxis.x, yaxis.y, yaxis.z); } Vector3df EC_OgrePlaceable::GetLocalZAxis() const { const Ogre::Vector3& zaxis = link_scene_node_->getOrientation().zAxis(); return Vector3df(zaxis.x, zaxis.y, zaxis.z); } QVector3D EC_OgrePlaceable::GetQLocalZAxis() const { Vector3df zaxis= GetLocalZAxis(); return QVector3D(zaxis.x, zaxis.y, zaxis.z); } void EC_OgrePlaceable::SetPosition(const Vector3df& position) { link_scene_node_->setPosition(Ogre::Vector3(position.x, position.y, position.z)); AttachNode(); // Nodes become visible only after having their position set at least once } void EC_OgrePlaceable::SetOrientation(const Quaternion& orientation) { link_scene_node_->setOrientation(Ogre::Quaternion(orientation.w, orientation.x, orientation.y, orientation.z)); } void EC_OgrePlaceable::LookAt(const Vector3df& look_at) { // Don't rely on the stability of the lookat (since it uses previous orientation), // so start in identity transform link_scene_node_->setOrientation(Ogre::Quaternion::IDENTITY); link_scene_node_->lookAt(Ogre::Vector3(look_at.x, look_at.y, look_at.z), Ogre::Node::TS_WORLD); } void EC_OgrePlaceable::SetYaw(Real radians) { link_scene_node_->yaw(Ogre::Radian(radians), Ogre::Node::TS_WORLD); } void EC_OgrePlaceable::SetPitch(Real radians) { link_scene_node_->pitch(Ogre::Radian(radians)); } void EC_OgrePlaceable::SetRoll(Real radians) { link_scene_node_->roll(Ogre::Radian(radians)); } float EC_OgrePlaceable::GetYaw() const { const Ogre::Quaternion& orientation = link_scene_node_->getOrientation(); return orientation.getYaw().valueRadians(); } float EC_OgrePlaceable::GetPitch() const { const Ogre::Quaternion& orientation = link_scene_node_->getOrientation(); return orientation.getPitch().valueRadians(); } float EC_OgrePlaceable::GetRoll() const { const Ogre::Quaternion& orientation = link_scene_node_->getOrientation(); return orientation.getRoll().valueRadians(); } void EC_OgrePlaceable::SetScale(const Vector3df& scale) { scene_node_->setScale(Ogre::Vector3(scale.x, scale.y, scale.z)); } void EC_OgrePlaceable::AttachNode() { if (renderer_.expired()) return; RendererPtr renderer = renderer_.lock(); if (attached_) return; Ogre::SceneNode* parent_node; if (!parent_) { Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); parent_node = scene_mgr->getRootSceneNode(); } else { EC_OgrePlaceable* parent = checked_static_cast<EC_OgrePlaceable*>(parent_.get()); parent_node = parent->GetLinkSceneNode(); } parent_node->addChild(link_scene_node_); attached_ = true; } void EC_OgrePlaceable::DetachNode() { if (renderer_.expired()) return; RendererPtr renderer = renderer_.lock(); if (!attached_) return; Ogre::SceneNode* parent_node; if (!parent_) { Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); parent_node = scene_mgr->getRootSceneNode(); } else { EC_OgrePlaceable* parent = checked_static_cast<EC_OgrePlaceable*>(parent_.get()); parent_node = parent->GetLinkSceneNode(); } parent_node->removeChild(link_scene_node_); attached_ = false; } //experimental QVector3D acessors QVector3D EC_OgrePlaceable::GetQPosition() const { //conversions, conversions, all around //.. if this works, and QVector3D is good, we should consider porting Vector3df for that Vector3df rexpos = GetPosition(); return QVector3D(rexpos.x, rexpos.y, rexpos.z); } void EC_OgrePlaceable::SetQPosition(const QVector3D newpos) { SetPosition(Vector3df(newpos.x(), newpos.y(), newpos.z())); } QQuaternion EC_OgrePlaceable::GetQOrientation() const { Quaternion rexort = GetOrientation(); return QQuaternion(rexort.w, rexort.x, rexort.y, rexort.z); } void EC_OgrePlaceable::SetQOrientation(const QQuaternion newort) { SetOrientation(Quaternion(newort.x(), newort.y(), newort.z(), newort.scalar())); } QVector3D EC_OgrePlaceable::GetQScale() const { Vector3df rexscale = GetScale(); return QVector3D(rexscale.x, rexscale.y, rexscale.z); } void EC_OgrePlaceable::SetQScale(const QVector3D newscale) { SetScale(Vector3df(newscale.x(), newscale.y(), newscale.z())); } QVector3D EC_OgrePlaceable::translate(int axis, float amount) { Ogre::Matrix3 m; Ogre::Vector3 v; Real x, y, z; x = y = z = 0.0; m.SetColumn(0, link_scene_node_->getOrientation().xAxis()); m.SetColumn(1, link_scene_node_->getOrientation().yAxis()); m.SetColumn(2, link_scene_node_->getOrientation().zAxis()); switch(axis) { case 0: x = amount; break; case 1: y = amount; break; case 2: z = amount; break; default: // nothing, don't translate break; } link_scene_node_->translate(m, Ogre::Vector3(x, y, z), Ogre::Node::TS_LOCAL); const Ogre::Vector3 newpos = link_scene_node_->getPosition(); return QVector3D(newpos.x, newpos.y, newpos.z); } } <commit_msg>Remove unnecessary includes and namespace usage.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "OgreRenderingModule.h" #include "Renderer.h" #include "EC_OgrePlaceable.h" #include <Ogre.h> namespace OgreRenderer { EC_OgrePlaceable::EC_OgrePlaceable(Foundation::ModuleInterface* module) : renderer_(checked_static_cast<OgreRenderingModule*>(module)->GetRenderer()), scene_node_(0), link_scene_node_(0), attached_(false), select_priority_(0) { RendererPtr renderer = renderer_.lock(); Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); link_scene_node_ = scene_mgr->createSceneNode(); scene_node_ = scene_mgr->createSceneNode(); link_scene_node_->addChild(scene_node_); // In case the placeable is used for camera control, set fixed yaw axis link_scene_node_->setFixedYawAxis(true, Ogre::Vector3::UNIT_Z); } EC_OgrePlaceable::~EC_OgrePlaceable() { if (renderer_.expired()) return; RendererPtr renderer = renderer_.lock(); Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); if (scene_node_ && link_scene_node_) { link_scene_node_->removeChild(scene_node_); } if (scene_node_) { scene_mgr->destroySceneNode(scene_node_); scene_node_ = 0; } if (link_scene_node_) { DetachNode(); scene_mgr->destroySceneNode(link_scene_node_); link_scene_node_ = 0; } } void EC_OgrePlaceable::SetParent(Foundation::ComponentPtr placeable) { if ((placeable.get() != 0) && (!dynamic_cast<EC_OgrePlaceable*>(placeable.get()))) { OgreRenderingModule::LogError("Attempted to set parent placeable which is not " + TypeNameStatic()); return; } DetachNode(); parent_ = placeable; AttachNode(); } Vector3df EC_OgrePlaceable::GetPosition() const { const Ogre::Vector3& pos = link_scene_node_->getPosition(); return Vector3df(pos.x, pos.y, pos.z); } Quaternion EC_OgrePlaceable::GetOrientation() const { const Ogre::Quaternion& orientation = link_scene_node_->getOrientation(); return Quaternion(orientation.x, orientation.y, orientation.z, orientation.w); } Vector3df EC_OgrePlaceable::GetScale() const { const Ogre::Vector3& scale = scene_node_->getScale(); return Vector3df(scale.x, scale.y, scale.z); } Vector3df EC_OgrePlaceable::GetLocalXAxis() const { const Ogre::Vector3& xaxis = link_scene_node_->getOrientation().xAxis(); return Vector3df(xaxis.x, xaxis.y, xaxis.z); } QVector3D EC_OgrePlaceable::GetQLocalXAxis() const { Vector3df xaxis= GetLocalXAxis(); return QVector3D(xaxis.x, xaxis.y, xaxis.z); } Vector3df EC_OgrePlaceable::GetLocalYAxis() const { const Ogre::Vector3& yaxis = link_scene_node_->getOrientation().yAxis(); return Vector3df(yaxis.x, yaxis.y, yaxis.z); } QVector3D EC_OgrePlaceable::GetQLocalYAxis() const { Vector3df yaxis= GetLocalYAxis(); return QVector3D(yaxis.x, yaxis.y, yaxis.z); } Vector3df EC_OgrePlaceable::GetLocalZAxis() const { const Ogre::Vector3& zaxis = link_scene_node_->getOrientation().zAxis(); return Vector3df(zaxis.x, zaxis.y, zaxis.z); } QVector3D EC_OgrePlaceable::GetQLocalZAxis() const { Vector3df zaxis= GetLocalZAxis(); return QVector3D(zaxis.x, zaxis.y, zaxis.z); } void EC_OgrePlaceable::SetPosition(const Vector3df& position) { link_scene_node_->setPosition(Ogre::Vector3(position.x, position.y, position.z)); AttachNode(); // Nodes become visible only after having their position set at least once } void EC_OgrePlaceable::SetOrientation(const Quaternion& orientation) { link_scene_node_->setOrientation(Ogre::Quaternion(orientation.w, orientation.x, orientation.y, orientation.z)); } void EC_OgrePlaceable::LookAt(const Vector3df& look_at) { // Don't rely on the stability of the lookat (since it uses previous orientation), // so start in identity transform link_scene_node_->setOrientation(Ogre::Quaternion::IDENTITY); link_scene_node_->lookAt(Ogre::Vector3(look_at.x, look_at.y, look_at.z), Ogre::Node::TS_WORLD); } void EC_OgrePlaceable::SetYaw(Real radians) { link_scene_node_->yaw(Ogre::Radian(radians), Ogre::Node::TS_WORLD); } void EC_OgrePlaceable::SetPitch(Real radians) { link_scene_node_->pitch(Ogre::Radian(radians)); } void EC_OgrePlaceable::SetRoll(Real radians) { link_scene_node_->roll(Ogre::Radian(radians)); } float EC_OgrePlaceable::GetYaw() const { const Ogre::Quaternion& orientation = link_scene_node_->getOrientation(); return orientation.getYaw().valueRadians(); } float EC_OgrePlaceable::GetPitch() const { const Ogre::Quaternion& orientation = link_scene_node_->getOrientation(); return orientation.getPitch().valueRadians(); } float EC_OgrePlaceable::GetRoll() const { const Ogre::Quaternion& orientation = link_scene_node_->getOrientation(); return orientation.getRoll().valueRadians(); } void EC_OgrePlaceable::SetScale(const Vector3df& scale) { scene_node_->setScale(Ogre::Vector3(scale.x, scale.y, scale.z)); } void EC_OgrePlaceable::AttachNode() { if (renderer_.expired()) return; RendererPtr renderer = renderer_.lock(); if (attached_) return; Ogre::SceneNode* parent_node; if (!parent_) { Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); parent_node = scene_mgr->getRootSceneNode(); } else { EC_OgrePlaceable* parent = checked_static_cast<EC_OgrePlaceable*>(parent_.get()); parent_node = parent->GetLinkSceneNode(); } parent_node->addChild(link_scene_node_); attached_ = true; } void EC_OgrePlaceable::DetachNode() { if (renderer_.expired()) return; RendererPtr renderer = renderer_.lock(); if (!attached_) return; Ogre::SceneNode* parent_node; if (!parent_) { Ogre::SceneManager* scene_mgr = renderer->GetSceneManager(); parent_node = scene_mgr->getRootSceneNode(); } else { EC_OgrePlaceable* parent = checked_static_cast<EC_OgrePlaceable*>(parent_.get()); parent_node = parent->GetLinkSceneNode(); } parent_node->removeChild(link_scene_node_); attached_ = false; } //experimental QVector3D acessors QVector3D EC_OgrePlaceable::GetQPosition() const { //conversions, conversions, all around //.. if this works, and QVector3D is good, we should consider porting Vector3df for that Vector3df rexpos = GetPosition(); return QVector3D(rexpos.x, rexpos.y, rexpos.z); } void EC_OgrePlaceable::SetQPosition(const QVector3D newpos) { SetPosition(Vector3df(newpos.x(), newpos.y(), newpos.z())); } QQuaternion EC_OgrePlaceable::GetQOrientation() const { Quaternion rexort = GetOrientation(); return QQuaternion(rexort.w, rexort.x, rexort.y, rexort.z); } void EC_OgrePlaceable::SetQOrientation(const QQuaternion newort) { SetOrientation(Quaternion(newort.x(), newort.y(), newort.z(), newort.scalar())); } QVector3D EC_OgrePlaceable::GetQScale() const { Vector3df rexscale = GetScale(); return QVector3D(rexscale.x, rexscale.y, rexscale.z); } void EC_OgrePlaceable::SetQScale(const QVector3D newscale) { SetScale(Vector3df(newscale.x(), newscale.y(), newscale.z())); } QVector3D EC_OgrePlaceable::translate(int axis, float amount) { Ogre::Matrix3 m; Ogre::Vector3 v; Real x, y, z; x = y = z = 0.0; m.SetColumn(0, link_scene_node_->getOrientation().xAxis()); m.SetColumn(1, link_scene_node_->getOrientation().yAxis()); m.SetColumn(2, link_scene_node_->getOrientation().zAxis()); switch(axis) { case 0: x = amount; break; case 1: y = amount; break; case 2: z = amount; break; default: // nothing, don't translate break; } link_scene_node_->translate(m, Ogre::Vector3(x, y, z), Ogre::Node::TS_LOCAL); const Ogre::Vector3 newpos = link_scene_node_->getPosition(); return QVector3D(newpos.x, newpos.y, newpos.z); } } <|endoftext|>
<commit_before>/******************************************************************************* * * Generic implementation of non-relational domains. * * Author: Arnaud J. Venet ([email protected]) * * Notices: * * Copyright (c) 2011 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Disclaimers: * * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS * RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." * * Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL * AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW. * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, * UNILATERAL TERMINATION OF THIS AGREEMENT. * ******************************************************************************/ #pragma once #include <crab/common/types.hpp> #include <crab/domains/patricia_trees.hpp> #include <boost/optional.hpp> namespace ikos { template <typename Key, typename Value> class separate_domain { private: typedef patricia_tree<Key, Value> patricia_tree_t; typedef typename patricia_tree_t::unary_op_t unary_op_t; typedef typename patricia_tree_t::binary_op_t binary_op_t; typedef typename patricia_tree_t::partial_order_t partial_order_t; public: typedef separate_domain<Key, Value> separate_domain_t; typedef typename patricia_tree_t::iterator iterator; typedef Key key_type; typedef Value value_type; private: bool _is_bottom; patricia_tree_t _tree; public: class join_op: public binary_op_t { std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.operator|(y); if (z.is_top()) { return {false, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return true; } }; // class join_op class widening_op: public binary_op_t { std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.operator||(y); if (z.is_top()) { return {false, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return true; } }; // class widening_op template <typename Thresholds> class widening_thresholds_op: public binary_op_t { const Thresholds& m_ts; public: widening_thresholds_op (const Thresholds& ts): m_ts (ts) { } std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.widening_thresholds(y, m_ts); if (z.is_top()) { return {false, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return true; } }; // class widening_thresholds_op class meet_op: public binary_op_t { std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.operator&(y); if (z.is_bottom()) { return {true, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return false; } }; // class meet_op class narrowing_op: public binary_op_t { std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.operator&&(y); if (z.is_bottom()) { return {true, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return false; } }; // class narrowing_op class domain_po: public partial_order_t { bool leq(Value x, Value y) { return x.operator<=(y); } bool default_is_top() { return true; } }; // class domain_po public: static separate_domain_t top() { return separate_domain_t(); } static separate_domain_t bottom() { return separate_domain_t(false); } private: static patricia_tree_t apply_operation(binary_op_t& o, patricia_tree_t t1, patricia_tree_t t2, bool& is_bottom) { is_bottom = t1.merge_with(t2, o); return t1; } separate_domain(patricia_tree_t t): _is_bottom(false), _tree(t) { } separate_domain(bool b): _is_bottom(!b) { } public: separate_domain(): _is_bottom(false) { } separate_domain(const separate_domain_t& e): _is_bottom(e._is_bottom), _tree(e._tree) { } separate_domain(const separate_domain_t&& e): _is_bottom(e._is_bottom), _tree(std::move(e._tree)) { } separate_domain_t& operator=(separate_domain_t e) { this->_is_bottom = e._is_bottom; this->_tree = e._tree; return *this; } iterator begin() const { if (this->is_bottom()) { CRAB_ERROR("Separate domain: trying to invoke iterator on bottom"); } else { return this->_tree.begin(); } } iterator end() const { if (this->is_bottom()) { CRAB_ERROR("Separate domain: trying to invoke iterator on bottom"); } else { return this->_tree.end(); } } bool is_bottom() const { return this->_is_bottom; } bool is_top() const { return (!this->is_bottom() && this->_tree.size() == 0); } bool operator<=(separate_domain_t e) { if (this->is_bottom()) { return true; } else if (e.is_bottom()) { return false; } else { domain_po po; return this->_tree.leq(e._tree, po); } } bool operator==(separate_domain_t e) { return (this->operator<=(e) && e.operator<=(*this)); } // Join separate_domain_t operator|(separate_domain_t e) { if (this->is_bottom()) { return e; } else if(e.is_bottom()) { return *this; } else { join_op o; bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); return separate_domain_t(std::move(res)); } } // Meet separate_domain_t operator&(separate_domain_t e) { if (this->is_bottom() || e.is_bottom()) { return this->bottom(); } else { meet_op o; bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); if (is_bottom) { return this->bottom(); } else { return separate_domain_t(std::move(res)); } } } // Widening separate_domain_t operator||(separate_domain_t e) { if (this->is_bottom()) { return e; } else if(e.is_bottom()) { return *this; } else { widening_op o; bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); return separate_domain_t(std::move(res)); } } // Widening with thresholds template<typename Thresholds> separate_domain_t widening_thresholds(separate_domain_t e, const Thresholds& ts) { if (this->is_bottom()) { return e; } else if(e.is_bottom()) { return *this; } else { widening_thresholds_op<Thresholds> o(ts); bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); return separate_domain_t(std::move(res)); } } // Narrowing separate_domain_t operator&&(separate_domain_t e) { if (this->is_bottom() || e.is_bottom()) { return separate_domain_t(false); } else { narrowing_op o; bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); if (is_bottom) { return this->bottom(); } else { return separate_domain_t(std::move(res)); } } } void set(Key k, Value v) { if (!this->is_bottom()) { if (v.is_bottom()) { this->_is_bottom = true; this->_tree = patricia_tree_t(); } else if (v.is_top()) { this->_tree.remove(k); } else { this->_tree.insert(k, v); } } } void set_to_bottom() { this->_is_bottom = true; this->_tree = patricia_tree_t(); } separate_domain_t& operator-=(Key k) { if (!this->is_bottom()) { this->_tree.remove(k); } return *this; } Value operator[](Key k) const { if (this->is_bottom()) { return Value::bottom(); } else { boost::optional<Value> v = this->_tree.lookup(k); if (v) { return *v; } else { return Value::top(); } } } std::size_t size() const { if (is_bottom()) { return 0; } else if (is_top()) { CRAB_ERROR("separate_domains::size() is undefined if top"); } else { return this->_tree.size(); } } void write(crab::crab_os& o) const { if (this->is_bottom()) { o << "_|_"; } else { o << "{"; for (typename patricia_tree_t::iterator it = this->_tree.begin(); it != this->_tree.end(); ) { Key k = it->first; k.write(o); o << " -> "; Value v = it->second; v.write(o); ++it; if (it != this->_tree.end()) { o << "; "; } } o << "}"; } } friend crab::crab_os& operator<<(crab::crab_os&o, const separate_domain<Key,Value>& d) { d.write(o); return o; } }; // class separate_domain } // namespace ikos <commit_msg>Add const to key parameter in separate_domains.hpp<commit_after>/******************************************************************************* * * Generic implementation of non-relational domains. * * Author: Arnaud J. Venet ([email protected]) * * Notices: * * Copyright (c) 2011 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Disclaimers: * * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS * RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." * * Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL * AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW. * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, * UNILATERAL TERMINATION OF THIS AGREEMENT. * ******************************************************************************/ #pragma once #include <crab/common/types.hpp> #include <crab/domains/patricia_trees.hpp> #include <boost/optional.hpp> namespace ikos { template <typename Key, typename Value> class separate_domain { private: typedef patricia_tree<Key, Value> patricia_tree_t; typedef typename patricia_tree_t::unary_op_t unary_op_t; typedef typename patricia_tree_t::binary_op_t binary_op_t; typedef typename patricia_tree_t::partial_order_t partial_order_t; public: typedef separate_domain<Key, Value> separate_domain_t; typedef typename patricia_tree_t::iterator iterator; typedef Key key_type; typedef Value value_type; private: bool _is_bottom; patricia_tree_t _tree; public: class join_op: public binary_op_t { std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.operator|(y); if (z.is_top()) { return {false, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return true; } }; // class join_op class widening_op: public binary_op_t { std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.operator||(y); if (z.is_top()) { return {false, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return true; } }; // class widening_op template <typename Thresholds> class widening_thresholds_op: public binary_op_t { const Thresholds& m_ts; public: widening_thresholds_op (const Thresholds& ts): m_ts (ts) { } std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.widening_thresholds(y, m_ts); if (z.is_top()) { return {false, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return true; } }; // class widening_thresholds_op class meet_op: public binary_op_t { std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.operator&(y); if (z.is_bottom()) { return {true, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return false; } }; // class meet_op class narrowing_op: public binary_op_t { std::pair<bool, boost::optional<Value>> apply(Value x, Value y) { Value z = x.operator&&(y); if (z.is_bottom()) { return {true, boost::optional<Value>()}; } else { return {false, boost::optional<Value>(z)}; } }; bool default_is_absorbing() { return false; } }; // class narrowing_op class domain_po: public partial_order_t { bool leq(Value x, Value y) { return x.operator<=(y); } bool default_is_top() { return true; } }; // class domain_po public: static separate_domain_t top() { return separate_domain_t(); } static separate_domain_t bottom() { return separate_domain_t(false); } private: static patricia_tree_t apply_operation(binary_op_t& o, patricia_tree_t t1, patricia_tree_t t2, bool& is_bottom) { is_bottom = t1.merge_with(t2, o); return t1; } separate_domain(patricia_tree_t t): _is_bottom(false), _tree(t) { } separate_domain(bool b): _is_bottom(!b) { } public: separate_domain(): _is_bottom(false) { } separate_domain(const separate_domain_t& e): _is_bottom(e._is_bottom), _tree(e._tree) { } separate_domain(const separate_domain_t&& e): _is_bottom(e._is_bottom), _tree(std::move(e._tree)) { } separate_domain_t& operator=(separate_domain_t e) { this->_is_bottom = e._is_bottom; this->_tree = e._tree; return *this; } iterator begin() const { if (this->is_bottom()) { CRAB_ERROR("Separate domain: trying to invoke iterator on bottom"); } else { return this->_tree.begin(); } } iterator end() const { if (this->is_bottom()) { CRAB_ERROR("Separate domain: trying to invoke iterator on bottom"); } else { return this->_tree.end(); } } bool is_bottom() const { return this->_is_bottom; } bool is_top() const { return (!this->is_bottom() && this->_tree.size() == 0); } bool operator<=(separate_domain_t e) { if (this->is_bottom()) { return true; } else if (e.is_bottom()) { return false; } else { domain_po po; return this->_tree.leq(e._tree, po); } } bool operator==(separate_domain_t e) { return (this->operator<=(e) && e.operator<=(*this)); } // Join separate_domain_t operator|(separate_domain_t e) { if (this->is_bottom()) { return e; } else if(e.is_bottom()) { return *this; } else { join_op o; bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); return separate_domain_t(std::move(res)); } } // Meet separate_domain_t operator&(separate_domain_t e) { if (this->is_bottom() || e.is_bottom()) { return this->bottom(); } else { meet_op o; bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); if (is_bottom) { return this->bottom(); } else { return separate_domain_t(std::move(res)); } } } // Widening separate_domain_t operator||(separate_domain_t e) { if (this->is_bottom()) { return e; } else if(e.is_bottom()) { return *this; } else { widening_op o; bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); return separate_domain_t(std::move(res)); } } // Widening with thresholds template<typename Thresholds> separate_domain_t widening_thresholds(separate_domain_t e, const Thresholds& ts) { if (this->is_bottom()) { return e; } else if(e.is_bottom()) { return *this; } else { widening_thresholds_op<Thresholds> o(ts); bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); return separate_domain_t(std::move(res)); } } // Narrowing separate_domain_t operator&&(separate_domain_t e) { if (this->is_bottom() || e.is_bottom()) { return separate_domain_t(false); } else { narrowing_op o; bool is_bottom; patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom); if (is_bottom) { return this->bottom(); } else { return separate_domain_t(std::move(res)); } } } void set(Key k, Value v) { if (!this->is_bottom()) { if (v.is_bottom()) { this->_is_bottom = true; this->_tree = patricia_tree_t(); } else if (v.is_top()) { this->_tree.remove(k); } else { this->_tree.insert(k, v); } } } void set_to_bottom() { this->_is_bottom = true; this->_tree = patricia_tree_t(); } separate_domain_t& operator-=(const Key &k) { if (!this->is_bottom()) { this->_tree.remove(k); } return *this; } Value operator[](const Key& k) const { if (this->is_bottom()) { return Value::bottom(); } else { boost::optional<Value> v = this->_tree.lookup(k); if (v) { return *v; } else { return Value::top(); } } } std::size_t size() const { if (is_bottom()) { return 0; } else if (is_top()) { CRAB_ERROR("separate_domains::size() is undefined if top"); } else { return this->_tree.size(); } } void write(crab::crab_os& o) const { if (this->is_bottom()) { o << "_|_"; } else { o << "{"; for (typename patricia_tree_t::iterator it = this->_tree.begin(); it != this->_tree.end(); ) { Key k = it->first; k.write(o); o << " -> "; Value v = it->second; v.write(o); ++it; if (it != this->_tree.end()) { o << "; "; } } o << "}"; } } friend crab::crab_os& operator<<(crab::crab_os&o, const separate_domain<Key,Value>& d) { d.write(o); return o; } }; // class separate_domain } // namespace ikos <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scrwnd.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2007-06-06 14:21:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <math.h> #include <limits.h> #ifndef _TOOLS_TIME_HXX #include <tools/time.hxx> #endif #include <tools/debug.hxx> #ifndef _SV_SVIDS_HRC #include <svids.hrc> #endif #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _VCL_TIMER_HXX #include <timer.hxx> #endif #ifndef _VCL_EVENT_HXX #include <event.hxx> #endif #ifndef _VCL_SCRWND_HXX #include <scrwnd.hxx> #endif // ----------- // - Defines - // ----------- #define WHEEL_WIDTH 25 #define WHEEL_RADIUS ((WHEEL_WIDTH) >> 1 ) #define MAX_TIME 300 #define MIN_TIME 20 #define DEF_TIMEOUT 50 // ------------------- // - ImplWheelWindow - // ------------------- ImplWheelWindow::ImplWheelWindow( Window* pParent ) : FloatingWindow ( pParent, 0 ), mnRepaintTime ( 1UL ), mnTimeout ( DEF_TIMEOUT ), mnWheelMode ( WHEELMODE_NONE ), mnActDist ( 0UL ), mnActDeltaX ( 0L ), mnActDeltaY ( 0L ) { // we need a parent DBG_ASSERT( pParent, "ImplWheelWindow::ImplWheelWindow(): Parent not set!" ); const Size aSize( pParent->GetOutputSizePixel() ); const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; // calculate maximum speed distance mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) ); // create wheel window SetTitleType( FLOATWIN_TITLE_NONE ); ImplCreateImageList(); ResMgr* pResMgr = ImplGetResMgr(); Bitmap aBmp; if( pResMgr ) aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, *pResMgr ) ); ImplSetRegion( aBmp ); // set wheel mode if( bHorz && bVert ) ImplSetWheelMode( WHEELMODE_VH ); else if( bHorz ) ImplSetWheelMode( WHEELMODE_H ); else ImplSetWheelMode( WHEELMODE_V ); // init timer mpTimer = new Timer; mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) ); mpTimer->SetTimeout( mnTimeout ); mpTimer->Start(); CaptureMouse(); } // ------------------------------------------------------------------------ ImplWheelWindow::~ImplWheelWindow() { ImplStop(); delete mpTimer; } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplStop() { ReleaseMouse(); mpTimer->Stop(); Show(FALSE); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp ) { Point aPos( GetPointerPosPixel() ); const Size aSize( rRegionBmp.GetSizePixel() ); Point aPoint; const Rectangle aRect( aPoint, aSize ); maCenter = maLastMousePos = aPos; aPos.X() -= aSize.Width() >> 1; aPos.Y() -= aSize.Height() >> 1; SetPosSizePixel( aPos, aSize ); SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplCreateImageList() { ResMgr* pResMgr = ImplGetResMgr(); if( pResMgr ) maImgList.InsertFromHorizontalBitmap ( ResId( SV_RESID_BITMAP_SCROLLBMP, *pResMgr ), 6, NULL ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode ) { if( nWheelMode != mnWheelMode ) { mnWheelMode = nWheelMode; if( WHEELMODE_NONE == mnWheelMode ) { if( IsVisible() ) Hide(); } else { if( !IsVisible() ) Show(); ImplDrawWheel(); } } } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplDrawWheel() { USHORT nId; switch( mnWheelMode ) { case( WHEELMODE_VH ): nId = 1; break; case( WHEELMODE_V ): nId = 2; break; case( WHEELMODE_H ): nId = 3; break; case( WHEELMODE_SCROLL_VH ):nId = 4; break; case( WHEELMODE_SCROLL_V ): nId = 5; break; case( WHEELMODE_SCROLL_H ): nId = 6; break; default: nId = 0; break; } if( nId ) DrawImage( Point(), maImgList.GetImage( nId ) ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplRecalcScrollValues() { if( mnActDist < WHEEL_RADIUS ) { mnActDeltaX = mnActDeltaY = 0L; mnTimeout = DEF_TIMEOUT; } else { ULONG nCurTime; // calc current time if( mnMaxWidth ) { const double fExp = ( (double) mnActDist / mnMaxWidth ) * log10( (double) MAX_TIME / MIN_TIME ); nCurTime = (ULONG) ( MAX_TIME / pow( 10., fExp ) ); } else nCurTime = MAX_TIME; if( !nCurTime ) nCurTime = 1UL; if( mnRepaintTime <= nCurTime ) mnTimeout = nCurTime - mnRepaintTime; else { long nMult = mnRepaintTime / nCurTime; if( !( mnRepaintTime % nCurTime ) ) mnTimeout = 0UL; else mnTimeout = ++nMult * nCurTime - mnRepaintTime; double fValX = (double) mnActDeltaX * nMult; double fValY = (double) mnActDeltaY * nMult; if( fValX > LONG_MAX ) mnActDeltaX = LONG_MAX; else if( fValX < LONG_MIN ) mnActDeltaX = LONG_MIN; else mnActDeltaX = (long) fValX; if( fValY > LONG_MAX ) mnActDeltaY = LONG_MAX; else if( fValY < LONG_MIN ) mnActDeltaY = LONG_MIN; else mnActDeltaY = (long) fValY; } } } // ------------------------------------------------------------------------ PointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY ) { PointerStyle eStyle; const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; if( bHorz || bVert ) { if( mnActDist < WHEEL_RADIUS ) { if( bHorz && bVert ) eStyle = POINTER_AUTOSCROLL_NSWE; else if( bHorz ) eStyle = POINTER_AUTOSCROLL_WE; else eStyle = POINTER_AUTOSCROLL_NS; } else { double fAngle = atan2( (double) -nDistY, nDistX ) / F_PI180; if( fAngle < 0.0 ) fAngle += 360.; if( bHorz && bVert ) { if( fAngle >= 22.5 && fAngle <= 67.5 ) eStyle = POINTER_AUTOSCROLL_NE; else if( fAngle >= 67.5 && fAngle <= 112.5 ) eStyle = POINTER_AUTOSCROLL_N; else if( fAngle >= 112.5 && fAngle <= 157.5 ) eStyle = POINTER_AUTOSCROLL_NW; else if( fAngle >= 157.5 && fAngle <= 202.5 ) eStyle = POINTER_AUTOSCROLL_W; else if( fAngle >= 202.5 && fAngle <= 247.5 ) eStyle = POINTER_AUTOSCROLL_SW; else if( fAngle >= 247.5 && fAngle <= 292.5 ) eStyle = POINTER_AUTOSCROLL_S; else if( fAngle >= 292.5 && fAngle <= 337.5 ) eStyle = POINTER_AUTOSCROLL_SE; else eStyle = POINTER_AUTOSCROLL_E; } else if( bHorz ) { if( fAngle >= 270. || fAngle <= 90. ) eStyle = POINTER_AUTOSCROLL_E; else eStyle = POINTER_AUTOSCROLL_W; } else { if( fAngle >= 0. && fAngle <= 180. ) eStyle = POINTER_AUTOSCROLL_N; else eStyle = POINTER_AUTOSCROLL_S; } } } else eStyle = POINTER_ARROW; return eStyle; } // ------------------------------------------------------------------------ void ImplWheelWindow::Paint( const Rectangle& ) { ImplDrawWheel(); } // ------------------------------------------------------------------------ void ImplWheelWindow::MouseMove( const MouseEvent& rMEvt ) { FloatingWindow::MouseMove( rMEvt ); const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) ); const long nDistX = aMousePos.X() - maCenter.X(); const long nDistY = aMousePos.Y() - maCenter.Y(); mnActDist = (ULONG) hypot( (double) nDistX, nDistY ); const PointerStyle eActStyle = ImplGetMousePointer( nDistX, nDistY ); const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; const BOOL bOuter = mnActDist > WHEEL_RADIUS; if( bOuter && ( maLastMousePos != aMousePos ) ) { switch( eActStyle ) { case( POINTER_AUTOSCROLL_N ): mnActDeltaX = +0L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_S ): mnActDeltaX = +0L, mnActDeltaY = -1L; break; case( POINTER_AUTOSCROLL_W ): mnActDeltaX = +1L, mnActDeltaY = +0L; break; case( POINTER_AUTOSCROLL_E ): mnActDeltaX = -1L, mnActDeltaY = +0L; break; case( POINTER_AUTOSCROLL_NW ): mnActDeltaX = +1L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_NE ): mnActDeltaX = -1L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_SW ): mnActDeltaX = +1L, mnActDeltaY = -1L; break; case( POINTER_AUTOSCROLL_SE ): mnActDeltaX = -1L, mnActDeltaY = -1L; break; default: break; } } ImplRecalcScrollValues(); maLastMousePos = aMousePos; SetPointer( eActStyle ); if( bHorz && bVert ) ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH ); else if( bHorz ) ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H ); else ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V ); } // ------------------------------------------------------------------------ void ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt ) { if( mnActDist > WHEEL_RADIUS ) GetParent()->EndAutoScroll(); else FloatingWindow::MouseButtonUp( rMEvt ); } // ------------------------------------------------------------------------ IMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG ) { if ( mnActDeltaX || mnActDeltaY ) { Window* pWindow = GetParent(); const Point aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) ); Point aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) ); CommandScrollData aScrollData( mnActDeltaX, mnActDeltaY ); CommandEvent aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData ); NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt ); if ( !ImplCallPreNotify( aNCmdEvt ) ) { const ULONG nTime = Time::GetSystemTicks(); ImplDelData aDel( this ); pWindow->Command( aCEvt ); if( aDel.IsDead() ) return 0; mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL ); ImplRecalcScrollValues(); } } if ( mnTimeout != mpTimer->GetTimeout() ) mpTimer->SetTimeout( mnTimeout ); mpTimer->Start(); return 0L; } <commit_msg>INTEGRATION: CWS vgbugs07 (1.10.38); FILE MERGED 2007/06/04 13:29:48 vg 1.10.38.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scrwnd.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2007-06-27 20:32:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <math.h> #include <limits.h> #ifndef _TOOLS_TIME_HXX #include <tools/time.hxx> #endif #include <tools/debug.hxx> #ifndef _SV_SVIDS_HRC #include <svids.hrc> #endif #ifndef _SV_SVDATA_HXX #include <vcl/svdata.hxx> #endif #ifndef _VCL_TIMER_HXX #include <vcl/timer.hxx> #endif #ifndef _VCL_EVENT_HXX #include <vcl/event.hxx> #endif #ifndef _VCL_SCRWND_HXX #include <scrwnd.hxx> #endif // ----------- // - Defines - // ----------- #define WHEEL_WIDTH 25 #define WHEEL_RADIUS ((WHEEL_WIDTH) >> 1 ) #define MAX_TIME 300 #define MIN_TIME 20 #define DEF_TIMEOUT 50 // ------------------- // - ImplWheelWindow - // ------------------- ImplWheelWindow::ImplWheelWindow( Window* pParent ) : FloatingWindow ( pParent, 0 ), mnRepaintTime ( 1UL ), mnTimeout ( DEF_TIMEOUT ), mnWheelMode ( WHEELMODE_NONE ), mnActDist ( 0UL ), mnActDeltaX ( 0L ), mnActDeltaY ( 0L ) { // we need a parent DBG_ASSERT( pParent, "ImplWheelWindow::ImplWheelWindow(): Parent not set!" ); const Size aSize( pParent->GetOutputSizePixel() ); const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; // calculate maximum speed distance mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) ); // create wheel window SetTitleType( FLOATWIN_TITLE_NONE ); ImplCreateImageList(); ResMgr* pResMgr = ImplGetResMgr(); Bitmap aBmp; if( pResMgr ) aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, *pResMgr ) ); ImplSetRegion( aBmp ); // set wheel mode if( bHorz && bVert ) ImplSetWheelMode( WHEELMODE_VH ); else if( bHorz ) ImplSetWheelMode( WHEELMODE_H ); else ImplSetWheelMode( WHEELMODE_V ); // init timer mpTimer = new Timer; mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) ); mpTimer->SetTimeout( mnTimeout ); mpTimer->Start(); CaptureMouse(); } // ------------------------------------------------------------------------ ImplWheelWindow::~ImplWheelWindow() { ImplStop(); delete mpTimer; } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplStop() { ReleaseMouse(); mpTimer->Stop(); Show(FALSE); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp ) { Point aPos( GetPointerPosPixel() ); const Size aSize( rRegionBmp.GetSizePixel() ); Point aPoint; const Rectangle aRect( aPoint, aSize ); maCenter = maLastMousePos = aPos; aPos.X() -= aSize.Width() >> 1; aPos.Y() -= aSize.Height() >> 1; SetPosSizePixel( aPos, aSize ); SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplCreateImageList() { ResMgr* pResMgr = ImplGetResMgr(); if( pResMgr ) maImgList.InsertFromHorizontalBitmap ( ResId( SV_RESID_BITMAP_SCROLLBMP, *pResMgr ), 6, NULL ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode ) { if( nWheelMode != mnWheelMode ) { mnWheelMode = nWheelMode; if( WHEELMODE_NONE == mnWheelMode ) { if( IsVisible() ) Hide(); } else { if( !IsVisible() ) Show(); ImplDrawWheel(); } } } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplDrawWheel() { USHORT nId; switch( mnWheelMode ) { case( WHEELMODE_VH ): nId = 1; break; case( WHEELMODE_V ): nId = 2; break; case( WHEELMODE_H ): nId = 3; break; case( WHEELMODE_SCROLL_VH ):nId = 4; break; case( WHEELMODE_SCROLL_V ): nId = 5; break; case( WHEELMODE_SCROLL_H ): nId = 6; break; default: nId = 0; break; } if( nId ) DrawImage( Point(), maImgList.GetImage( nId ) ); } // ------------------------------------------------------------------------ void ImplWheelWindow::ImplRecalcScrollValues() { if( mnActDist < WHEEL_RADIUS ) { mnActDeltaX = mnActDeltaY = 0L; mnTimeout = DEF_TIMEOUT; } else { ULONG nCurTime; // calc current time if( mnMaxWidth ) { const double fExp = ( (double) mnActDist / mnMaxWidth ) * log10( (double) MAX_TIME / MIN_TIME ); nCurTime = (ULONG) ( MAX_TIME / pow( 10., fExp ) ); } else nCurTime = MAX_TIME; if( !nCurTime ) nCurTime = 1UL; if( mnRepaintTime <= nCurTime ) mnTimeout = nCurTime - mnRepaintTime; else { long nMult = mnRepaintTime / nCurTime; if( !( mnRepaintTime % nCurTime ) ) mnTimeout = 0UL; else mnTimeout = ++nMult * nCurTime - mnRepaintTime; double fValX = (double) mnActDeltaX * nMult; double fValY = (double) mnActDeltaY * nMult; if( fValX > LONG_MAX ) mnActDeltaX = LONG_MAX; else if( fValX < LONG_MIN ) mnActDeltaX = LONG_MIN; else mnActDeltaX = (long) fValX; if( fValY > LONG_MAX ) mnActDeltaY = LONG_MAX; else if( fValY < LONG_MIN ) mnActDeltaY = LONG_MIN; else mnActDeltaY = (long) fValY; } } } // ------------------------------------------------------------------------ PointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY ) { PointerStyle eStyle; const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; if( bHorz || bVert ) { if( mnActDist < WHEEL_RADIUS ) { if( bHorz && bVert ) eStyle = POINTER_AUTOSCROLL_NSWE; else if( bHorz ) eStyle = POINTER_AUTOSCROLL_WE; else eStyle = POINTER_AUTOSCROLL_NS; } else { double fAngle = atan2( (double) -nDistY, nDistX ) / F_PI180; if( fAngle < 0.0 ) fAngle += 360.; if( bHorz && bVert ) { if( fAngle >= 22.5 && fAngle <= 67.5 ) eStyle = POINTER_AUTOSCROLL_NE; else if( fAngle >= 67.5 && fAngle <= 112.5 ) eStyle = POINTER_AUTOSCROLL_N; else if( fAngle >= 112.5 && fAngle <= 157.5 ) eStyle = POINTER_AUTOSCROLL_NW; else if( fAngle >= 157.5 && fAngle <= 202.5 ) eStyle = POINTER_AUTOSCROLL_W; else if( fAngle >= 202.5 && fAngle <= 247.5 ) eStyle = POINTER_AUTOSCROLL_SW; else if( fAngle >= 247.5 && fAngle <= 292.5 ) eStyle = POINTER_AUTOSCROLL_S; else if( fAngle >= 292.5 && fAngle <= 337.5 ) eStyle = POINTER_AUTOSCROLL_SE; else eStyle = POINTER_AUTOSCROLL_E; } else if( bHorz ) { if( fAngle >= 270. || fAngle <= 90. ) eStyle = POINTER_AUTOSCROLL_E; else eStyle = POINTER_AUTOSCROLL_W; } else { if( fAngle >= 0. && fAngle <= 180. ) eStyle = POINTER_AUTOSCROLL_N; else eStyle = POINTER_AUTOSCROLL_S; } } } else eStyle = POINTER_ARROW; return eStyle; } // ------------------------------------------------------------------------ void ImplWheelWindow::Paint( const Rectangle& ) { ImplDrawWheel(); } // ------------------------------------------------------------------------ void ImplWheelWindow::MouseMove( const MouseEvent& rMEvt ) { FloatingWindow::MouseMove( rMEvt ); const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) ); const long nDistX = aMousePos.X() - maCenter.X(); const long nDistY = aMousePos.Y() - maCenter.Y(); mnActDist = (ULONG) hypot( (double) nDistX, nDistY ); const PointerStyle eActStyle = ImplGetMousePointer( nDistX, nDistY ); const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags; const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0; const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0; const BOOL bOuter = mnActDist > WHEEL_RADIUS; if( bOuter && ( maLastMousePos != aMousePos ) ) { switch( eActStyle ) { case( POINTER_AUTOSCROLL_N ): mnActDeltaX = +0L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_S ): mnActDeltaX = +0L, mnActDeltaY = -1L; break; case( POINTER_AUTOSCROLL_W ): mnActDeltaX = +1L, mnActDeltaY = +0L; break; case( POINTER_AUTOSCROLL_E ): mnActDeltaX = -1L, mnActDeltaY = +0L; break; case( POINTER_AUTOSCROLL_NW ): mnActDeltaX = +1L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_NE ): mnActDeltaX = -1L, mnActDeltaY = +1L; break; case( POINTER_AUTOSCROLL_SW ): mnActDeltaX = +1L, mnActDeltaY = -1L; break; case( POINTER_AUTOSCROLL_SE ): mnActDeltaX = -1L, mnActDeltaY = -1L; break; default: break; } } ImplRecalcScrollValues(); maLastMousePos = aMousePos; SetPointer( eActStyle ); if( bHorz && bVert ) ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH ); else if( bHorz ) ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H ); else ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V ); } // ------------------------------------------------------------------------ void ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt ) { if( mnActDist > WHEEL_RADIUS ) GetParent()->EndAutoScroll(); else FloatingWindow::MouseButtonUp( rMEvt ); } // ------------------------------------------------------------------------ IMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG ) { if ( mnActDeltaX || mnActDeltaY ) { Window* pWindow = GetParent(); const Point aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) ); Point aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) ); CommandScrollData aScrollData( mnActDeltaX, mnActDeltaY ); CommandEvent aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData ); NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt ); if ( !ImplCallPreNotify( aNCmdEvt ) ) { const ULONG nTime = Time::GetSystemTicks(); ImplDelData aDel( this ); pWindow->Command( aCEvt ); if( aDel.IsDead() ) return 0; mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL ); ImplRecalcScrollValues(); } } if ( mnTimeout != mpTimer->GetTimeout() ) mpTimer->SetTimeout( mnTimeout ); mpTimer->Start(); return 0L; } <|endoftext|>
<commit_before>/** @file @brief Produces a distortion polynomial and partial display description from a table of display locations to angle inputs. @date 2019 @author Russ Taylor working through ReliaSolve.com for ValitXR. */ // Copyright 2019 ValityXR. // // 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. // Standard includes #include <string> #include <iostream> #include <iomanip> #include <fstream> #include <cmath> #include <vector> #include <stdlib.h> // For exit() // Local includes #include "types.h" // Global constants and variables static bool g_verbose = false; static double MY_PI = (4.0*atan(1.0)); // Forward declarations static int testAlgorithms(); static void writePolynomial(std::ostream &s, std::vector<double> const &poly) { s << "["; for (size_t i = 0; i < poly.size(); i++) { if (i == 0) { s << " "; } else { s << ","; } s << std::setprecision(4) << poly[i]; } } /// @brief Evaluate the coefficients with both radius and vector in meters. /// @return Angle in Radians associated with radial point. static double evaluateAngleRadians(double r, std::vector<double> const &coefs) { double ret = 0; for (size_t i = 0; i < coefs.size(); i++) { ret += coefs[i] * pow(r, 1 + 2 * i); } return atan(ret); } /// @brief Determine the OSVR equivalent FOV for an axis. /// @param left Left side of the display (or Bottom) (at depth) /// @param right Right side of the display (or Top) (at depth) /// @param depth Perpendicular distance to the screen static double computeFOVDegrees(double left, double right, double depth) { // Find half of the width of the axis, because we need to compute // the FOV as if we were centered. double halfWidth = fabs((right - left) / 2); // Find twice the angle to that point at the specified depth double rad = 2 * atan2(halfWidth, depth); // Convert to Radians return 180 / MY_PI * rad; } void Usage(std::string name) { std::cerr << "Usage: " << name << " [-eye right|left] (default is right)" << " [-depth_meters D] (default is 2.0)" << " [-verbose] (default is not)" << " display_size" << " C1 [C3 [C5 [...]]" << std::endl << " This program solves for the polynomial distortion correction that will correct for" << std::endl << "the screen-to-angle mapping described in the coefficients. The first-order term C1" << std::endl << "must be specified, and other higher odd-numbered terms may also be specified (C3, C5, ...)" << std::endl << "The coefficents are from the equation tan(theta) = C1*r + C3*r^3 + C5*r^5 + ..." << std::endl << " The input r for the mapping is in millimeters." << std::endl << " The output of the mapping is the tangent of the angle towards the visible point" << std::endl << " The size of the display is specified in millimeters and must be the." << std::endl << "same for both width and height until the code is generalized." << std::endl << std::endl; exit(1); } int main(int argc, char *argv[]) { // Parse the command line std::vector<std::string> inputFileNames; bool useRightEye = true; double left, right, bottom, top; std::vector<double> coeffs; double depth = 2.0; int realParams = 0; for (int i = 1; i < argc; i++) { if (std::string("-verbose") == argv[i]) { g_verbose = true; } else if (std::string("-depth_meters") == argv[i]) { if (++i >= argc) { Usage(argv[0]); } depth = atof(argv[i]); } else if (std::string("-eye") == argv[i]) { if (++i >= argc) { Usage(argv[0]); } std::string eye = argv[i]; if (eye == "left") { useRightEye = false; } else if (eye == "right") { useRightEye = true; } else { std::cerr << "Bad value for -eye: " << eye << ", expected left or right" << std::endl; Usage(argv[0]); } } else if ((argv[i][0] == '-') && (atof(argv[i]) == 0.0)) { Usage(argv[0]); } else switch (++realParams) { case 1: right = top = atof(argv[i])/2; left = bottom = -right; break; default: // We got another coefficient, so put it onto the list after scaling it. coeffs.push_back(atof(argv[i])); } } if (realParams < 5) { Usage(argv[0]); } //==================================================================== // Ensure that our parameters are not more general than we can handle. //==================================================================== // Run our algorithm test to make sure things are working properly. int ret; if ((ret = testAlgorithms()) != 0) { std::cerr << "Error testing basic algorithms, code " << ret << std::endl; return 100; } //==================================================================== // The output screens and polynomial. ScreenDescription leftScreen, rightScreen; std::vector<double> polynomial; //==================================================================== // Compute left and right screen boundaries that are mirror images // of each other. // Compute the boundaries of the screen based on the depth and the maximum // angles in +/- X and Y projected to that distance. These need to be // projected from the display space into the distance that the screen // lies at. double leftAngle = evaluateAngleRadians(left, coeffs); double rightAngle = evaluateAngleRadians(right, coeffs); double topAngle = evaluateAngleRadians(top, coeffs); double bottomAngle = evaluateAngleRadians(bottom, coeffs); if (g_verbose) { std::cout << "leftAngle (degrees): " << leftAngle * 180 / MY_PI << std::endl; std::cout << "rightAngle (degrees): " << rightAngle * 180 / MY_PI << std::endl; std::cout << "bottomAngle (degrees): " << bottomAngle * 180 / MY_PI << std::endl; std::cout << "topAngle (degrees): " << topAngle * 180 / MY_PI << std::endl; } double leftScreenLeft, leftScreenRight, leftScreenBottom, leftScreenTop; double rightScreenLeft, rightScreenRight, rightScreenBottom, rightScreenTop; rightScreenBottom = leftScreenBottom = depth * tan(bottomAngle); rightScreenTop = leftScreenTop = depth * tan(topAngle); if (useRightEye) { rightScreenLeft = depth * tan(leftAngle); rightScreenRight = depth * tan(rightAngle); leftScreenLeft = -depth * tan(rightAngle); leftScreenRight = -depth * tan(leftAngle); } else { leftScreenLeft = depth * tan(leftAngle); leftScreenRight = depth * tan(rightAngle); rightScreenLeft = -depth * tan(rightAngle); rightScreenRight = -depth * tan(leftAngle); } if (g_verbose) { std::cout << "rightScreenLeft: " << rightScreenLeft << std::endl; std::cout << "rightScreenRight: " << rightScreenRight << std::endl; std::cout << "rightScreenBottom: " << rightScreenBottom << std::endl; std::cout << "rightScreenTop: " << rightScreenTop << std::endl; } //==================================================================== // Convert the screen boundaries into the OSVR description format. leftScreen.xCOP = (0 - leftScreenLeft) / (leftScreenRight - leftScreenLeft); leftScreen.yCOP = (0 - leftScreenBottom) / (leftScreenTop - leftScreenBottom); leftScreen.overlapPercent = 100; /// @todo Consider generalizing leftScreen.hFOVDegrees = computeFOVDegrees(leftScreenLeft, leftScreenRight, depth); leftScreen.vFOVDegrees = computeFOVDegrees(leftScreenBottom, leftScreenTop, depth); rightScreen.xCOP = (0 - rightScreenLeft) / (rightScreenRight - rightScreenLeft); rightScreen.yCOP = (0 - rightScreenBottom) / (rightScreenTop - rightScreenBottom); rightScreen.overlapPercent = 100; /// @todo Consider generalizing rightScreen.hFOVDegrees = computeFOVDegrees(rightScreenLeft, rightScreenRight, depth); rightScreen.vFOVDegrees = computeFOVDegrees(rightScreenBottom, rightScreenTop, depth); if (g_verbose) { std::cout << "hFOV (degrees): " << rightScreen.hFOVDegrees << std::endl; std::cout << "vFOV (degrees): " << rightScreen.vFOVDegrees << std::endl; } //==================================================================== // Compute a polynomial that will map from the linear, rendered canonical // image to the correct location that matches that viewing angle when seen // through HMD lens. It will leave points at the center of projection // at the same location and should map a point at the furthest location on // the same vertical or horizontal screen to the same location (if the // screen is centered, this will be points on the horizontal and vertical // centers of the edges). // The coefficients provide a mapping from radial distance in millimeters // away from the center of projection to the tangent of the angle at which // the point will appear. OSVR wants a polynomial that moves points from // an initial location in a space to an offset location in that same space. // The tangent space is scaled differently than the pixel space, so we // need to transform the coefficients so that they are not. // We are free to choose either space (or another one entirely), so long // as the distance metrics match. // We choose to scale the input space to match the output tangent space // in a manner that will map the furthest input pixel to the furthest tangent, // which means that we need to convert the input units to tangent space by // multiplying them by tangent_range/mm_range. // This basically means that we need to scale the polynomial coefficients // by this inverse of this factor raised to the power that they are applying // so that they will do the conversion for us. double units = (left - right) / (tan(leftAngle) - tan(rightAngle)); // This means that the coefficients are providing us the correct mapping, // but we need to convert them into the appropriate distance scale an put // them into the appropriate coefficients. The appropriate coefficients // are the 1st, 3rd, and so forth. We skip all even coefficients. // Always push back 0 for the 0th-order term. polynomial.push_back(0); for (size_t i = 0; i < coeffs.size(); i++) { // Zero all even terms. We already zeroed the 0th-order term if (i > 0) { polynomial.push_back(0); } // Scale by the units conversion. polynomial.push_back(coeffs[i] * pow(units,1 + 2 * i)); } // Set the distance units to twice the distance from the center of // the display to the farthest direction so that the point at the center // of the furthest edge will map to itself. This is in the tangent // space. // (For the square case, this is just twice the right edge.) double distance_scale = 2*tan(rightAngle); /// @todo Generalize for non-square, non-centered displays. In that // case, we want the farthest edge from the center to map to itself and // the other edges will overfill to some extent. // Determine the longest distance from the center of projection to an // edge in millimeters. /* double maxEdge = fabs(left); maxEdge = std::max(maxEdge, fabs(right)); maxEdge = std::max(maxEdge, fabs(bottom)); maxEdge = std::max(maxEdge, fabs(top)); */ //==================================================================== // Construct Json screen description. // We do this by hand rather than using JsonCPP because we want // to control the printed precision of the numbers to avoid making // a huge file. std::cout << "{" << std::endl; std::cout << " \"display\": {" << std::endl; std::cout << " \"hmd\": {" << std::endl; std::cout << " \"field_of_view\": {" << std::endl; std::cout << " \"monocular_horizontal\": " << rightScreen.hFOVDegrees << "," << std::endl; std::cout << " \"monocular_vertical\": " << rightScreen.vFOVDegrees << "," << std::endl; std::cout << " \"overlap_percent\": " << rightScreen.overlapPercent << "," << std::endl; std::cout << " \"pitch_tilt\": 0" << std::endl; std::cout << " }," << std::endl; // field_of_view std::cout << " \"distortion\": {" << std::endl; std::cout << " \"distance_scale_x\": " << distance_scale << "," << std::endl; std::cout << " \"distance_scale_y\": " << distance_scale << "," << std::endl; std::cout << " \"polynomial_coeffs_red\": "; writePolynomial(std::cout, polynomial); std::cout << " ]," << std::endl; std::cout << " \"polynomial_coeffs_green\": "; writePolynomial(std::cout, polynomial); std::cout << " ]," << std::endl; std::cout << " \"polynomial_coeffs_blue\": "; writePolynomial(std::cout, polynomial); std::cout << " ]" << std::endl; std::cout << " }," << std::endl; // distortion std::cout << " \"eyes\": [" << std::endl; std::cout << " {" << std::endl; std::cout << " \"center_proj_x\": " << leftScreen.xCOP << "," << std::endl; std::cout << " \"center_proj_y\": " << leftScreen.yCOP << "," << std::endl; std::cout << " \"rotate_180\": 0" << std::endl; std::cout << " }," << std::endl; std::cout << " {" << std::endl; std::cout << " \"center_proj_x\": " << rightScreen.xCOP << "," << std::endl; std::cout << " \"center_proj_y\": " << rightScreen.yCOP << "," << std::endl; std::cout << " \"rotate_180\": 0" << std::endl; std::cout << " }" << std::endl; std::cout << " ]" << std::endl; // eyes std::cout << " }" << std::endl; // hmd std::cout << " }" << std::endl; // display std::cout << "}" << std::endl; // Closes outer object return 0; } static bool small(double d) { return fabs(d) <= 1e-5; } static int testAlgorithms() { if (g_verbose) { std::cerr << "=================== Starting testAlgorithms()" << std::endl; } // @todo std::cerr << "Warning: Test not yet implemented" << std::endl; if (g_verbose) { std::cerr << "=================== Successfully finished testAlgorithms()" << std::endl; } return 0; } <commit_msg>Making function emit closing brace along with opening brace.<commit_after>/** @file @brief Produces a distortion polynomial and partial display description from a table of display locations to angle inputs. @date 2019 @author Russ Taylor working through ReliaSolve.com for ValitXR. */ // Copyright 2019 ValityXR. // // 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. // Standard includes #include <string> #include <iostream> #include <iomanip> #include <fstream> #include <cmath> #include <vector> #include <stdlib.h> // For exit() // Local includes #include "types.h" // Global constants and variables static bool g_verbose = false; static double MY_PI = (4.0*atan(1.0)); // Forward declarations static int testAlgorithms(); static void writePolynomial(std::ostream &s, std::vector<double> const &poly) { s << "["; for (size_t i = 0; i < poly.size(); i++) { if (i == 0) { s << " "; } else { s << ","; } s << std::setprecision(4) << poly[i]; } std::cout << " ]"; } /// @brief Evaluate the coefficients with both radius and vector in meters. /// @return Angle in Radians associated with radial point. static double evaluateAngleRadians(double r, std::vector<double> const &coefs) { double ret = 0; for (size_t i = 0; i < coefs.size(); i++) { ret += coefs[i] * pow(r, 1 + 2 * i); } return atan(ret); } /// @brief Determine the OSVR equivalent FOV for an axis. /// @param left Left side of the display (or Bottom) (at depth) /// @param right Right side of the display (or Top) (at depth) /// @param depth Perpendicular distance to the screen static double computeFOVDegrees(double left, double right, double depth) { // Find half of the width of the axis, because we need to compute // the FOV as if we were centered. double halfWidth = fabs((right - left) / 2); // Find twice the angle to that point at the specified depth double rad = 2 * atan2(halfWidth, depth); // Convert to Radians return 180 / MY_PI * rad; } void Usage(std::string name) { std::cerr << "Usage: " << name << " [-eye right|left] (default is right)" << " [-depth_meters D] (default is 2.0)" << " [-verbose] (default is not)" << " display_size" << " C1 [C3 [C5 [...]]" << std::endl << " This program solves for the polynomial distortion correction that will correct for" << std::endl << "the screen-to-angle mapping described in the coefficients. The first-order term C1" << std::endl << "must be specified, and other higher odd-numbered terms may also be specified (C3, C5, ...)" << std::endl << "The coefficents are from the equation tan(theta) = C1*r + C3*r^3 + C5*r^5 + ..." << std::endl << " The input r for the mapping is in millimeters." << std::endl << " The output of the mapping is the tangent of the angle towards the visible point" << std::endl << " The size of the display is specified in millimeters and must be the." << std::endl << "same for both width and height until the code is generalized." << std::endl << std::endl; exit(1); } int main(int argc, char *argv[]) { // Parse the command line std::vector<std::string> inputFileNames; bool useRightEye = true; double left, right, bottom, top; std::vector<double> coeffs; double depth = 2.0; int realParams = 0; for (int i = 1; i < argc; i++) { if (std::string("-verbose") == argv[i]) { g_verbose = true; } else if (std::string("-depth_meters") == argv[i]) { if (++i >= argc) { Usage(argv[0]); } depth = atof(argv[i]); } else if (std::string("-eye") == argv[i]) { if (++i >= argc) { Usage(argv[0]); } std::string eye = argv[i]; if (eye == "left") { useRightEye = false; } else if (eye == "right") { useRightEye = true; } else { std::cerr << "Bad value for -eye: " << eye << ", expected left or right" << std::endl; Usage(argv[0]); } } else if ((argv[i][0] == '-') && (atof(argv[i]) == 0.0)) { Usage(argv[0]); } else switch (++realParams) { case 1: right = top = atof(argv[i])/2; left = bottom = -right; break; default: // We got another coefficient, so put it onto the list after scaling it. coeffs.push_back(atof(argv[i])); } } if (realParams < 5) { Usage(argv[0]); } //==================================================================== // Ensure that our parameters are not more general than we can handle. //==================================================================== // Run our algorithm test to make sure things are working properly. int ret; if ((ret = testAlgorithms()) != 0) { std::cerr << "Error testing basic algorithms, code " << ret << std::endl; return 100; } //==================================================================== // The output screens and polynomial. ScreenDescription leftScreen, rightScreen; std::vector<double> polynomial; //==================================================================== // Compute left and right screen boundaries that are mirror images // of each other. // Compute the boundaries of the screen based on the depth and the maximum // angles in +/- X and Y projected to that distance. These need to be // projected from the display space into the distance that the screen // lies at. double leftAngle = evaluateAngleRadians(left, coeffs); double rightAngle = evaluateAngleRadians(right, coeffs); double topAngle = evaluateAngleRadians(top, coeffs); double bottomAngle = evaluateAngleRadians(bottom, coeffs); if (g_verbose) { std::cout << "leftAngle (degrees): " << leftAngle * 180 / MY_PI << std::endl; std::cout << "rightAngle (degrees): " << rightAngle * 180 / MY_PI << std::endl; std::cout << "bottomAngle (degrees): " << bottomAngle * 180 / MY_PI << std::endl; std::cout << "topAngle (degrees): " << topAngle * 180 / MY_PI << std::endl; } double leftScreenLeft, leftScreenRight, leftScreenBottom, leftScreenTop; double rightScreenLeft, rightScreenRight, rightScreenBottom, rightScreenTop; rightScreenBottom = leftScreenBottom = depth * tan(bottomAngle); rightScreenTop = leftScreenTop = depth * tan(topAngle); if (useRightEye) { rightScreenLeft = depth * tan(leftAngle); rightScreenRight = depth * tan(rightAngle); leftScreenLeft = -depth * tan(rightAngle); leftScreenRight = -depth * tan(leftAngle); } else { leftScreenLeft = depth * tan(leftAngle); leftScreenRight = depth * tan(rightAngle); rightScreenLeft = -depth * tan(rightAngle); rightScreenRight = -depth * tan(leftAngle); } if (g_verbose) { std::cout << "rightScreenLeft: " << rightScreenLeft << std::endl; std::cout << "rightScreenRight: " << rightScreenRight << std::endl; std::cout << "rightScreenBottom: " << rightScreenBottom << std::endl; std::cout << "rightScreenTop: " << rightScreenTop << std::endl; } //==================================================================== // Convert the screen boundaries into the OSVR description format. leftScreen.xCOP = (0 - leftScreenLeft) / (leftScreenRight - leftScreenLeft); leftScreen.yCOP = (0 - leftScreenBottom) / (leftScreenTop - leftScreenBottom); leftScreen.overlapPercent = 100; /// @todo Consider generalizing leftScreen.hFOVDegrees = computeFOVDegrees(leftScreenLeft, leftScreenRight, depth); leftScreen.vFOVDegrees = computeFOVDegrees(leftScreenBottom, leftScreenTop, depth); rightScreen.xCOP = (0 - rightScreenLeft) / (rightScreenRight - rightScreenLeft); rightScreen.yCOP = (0 - rightScreenBottom) / (rightScreenTop - rightScreenBottom); rightScreen.overlapPercent = 100; /// @todo Consider generalizing rightScreen.hFOVDegrees = computeFOVDegrees(rightScreenLeft, rightScreenRight, depth); rightScreen.vFOVDegrees = computeFOVDegrees(rightScreenBottom, rightScreenTop, depth); if (g_verbose) { std::cout << "hFOV (degrees): " << rightScreen.hFOVDegrees << std::endl; std::cout << "vFOV (degrees): " << rightScreen.vFOVDegrees << std::endl; } //==================================================================== // Compute a polynomial that will map from the linear, rendered canonical // image to the correct location that matches that viewing angle when seen // through HMD lens. It will leave points at the center of projection // at the same location and should map a point at the furthest location on // the same vertical or horizontal screen to the same location (if the // screen is centered, this will be points on the horizontal and vertical // centers of the edges). // The coefficients provide a mapping from radial distance in millimeters // away from the center of projection to the tangent of the angle at which // the point will appear. OSVR wants a polynomial that moves points from // an initial location in a space to an offset location in that same space. // The tangent space is scaled differently than the pixel space, so we // need to transform the coefficients so that they are not. // We are free to choose either space (or another one entirely), so long // as the distance metrics match. // We choose to scale the input space to match the output tangent space // in a manner that will map the furthest input pixel to the furthest tangent, // which means that we need to convert the input units to tangent space by // multiplying them by tangent_range/mm_range. // This basically means that we need to scale the polynomial coefficients // by this inverse of this factor raised to the power that they are applying // so that they will do the conversion for us. double units = (left - right) / (tan(leftAngle) - tan(rightAngle)); // This means that the coefficients are providing us the correct mapping, // but we need to convert them into the appropriate distance scale an put // them into the appropriate coefficients. The appropriate coefficients // are the 1st, 3rd, and so forth. We skip all even coefficients. // Always push back 0 for the 0th-order term. polynomial.push_back(0); for (size_t i = 0; i < coeffs.size(); i++) { // Zero all even terms. We already zeroed the 0th-order term if (i > 0) { polynomial.push_back(0); } // Scale by the units conversion. polynomial.push_back(coeffs[i] * pow(units,1 + 2 * i)); } // Set the distance units to twice the distance from the center of // the display to the farthest direction so that the point at the center // of the furthest edge will map to itself. This is in the tangent // space. // (For the square case, this is just twice the right edge.) double distance_scale = 2*tan(rightAngle); /// @todo Generalize for non-square, non-centered displays. In that // case, we want the farthest edge from the center to map to itself and // the other edges will overfill to some extent. // Determine the longest distance from the center of projection to an // edge in millimeters. /* double maxEdge = fabs(left); maxEdge = std::max(maxEdge, fabs(right)); maxEdge = std::max(maxEdge, fabs(bottom)); maxEdge = std::max(maxEdge, fabs(top)); */ //==================================================================== // Construct Json screen description. // We do this by hand rather than using JsonCPP because we want // to control the printed precision of the numbers to avoid making // a huge file. std::cout << "{" << std::endl; std::cout << " \"display\": {" << std::endl; std::cout << " \"hmd\": {" << std::endl; std::cout << " \"field_of_view\": {" << std::endl; std::cout << " \"monocular_horizontal\": " << rightScreen.hFOVDegrees << "," << std::endl; std::cout << " \"monocular_vertical\": " << rightScreen.vFOVDegrees << "," << std::endl; std::cout << " \"overlap_percent\": " << rightScreen.overlapPercent << "," << std::endl; std::cout << " \"pitch_tilt\": 0" << std::endl; std::cout << " }," << std::endl; // field_of_view std::cout << " \"distortion\": {" << std::endl; std::cout << " \"distance_scale_x\": " << distance_scale << "," << std::endl; std::cout << " \"distance_scale_y\": " << distance_scale << "," << std::endl; std::cout << " \"polynomial_coeffs_red\": "; writePolynomial(std::cout, polynomial); std::cout << "," << std::endl; std::cout << " \"polynomial_coeffs_green\": "; writePolynomial(std::cout, polynomial); std::cout << "," << std::endl; std::cout << " \"polynomial_coeffs_blue\": "; writePolynomial(std::cout, polynomial); std::cout << std::endl; std::cout << " }," << std::endl; // distortion std::cout << " \"eyes\": [" << std::endl; std::cout << " {" << std::endl; std::cout << " \"center_proj_x\": " << leftScreen.xCOP << "," << std::endl; std::cout << " \"center_proj_y\": " << leftScreen.yCOP << "," << std::endl; std::cout << " \"rotate_180\": 0" << std::endl; std::cout << " }," << std::endl; std::cout << " {" << std::endl; std::cout << " \"center_proj_x\": " << rightScreen.xCOP << "," << std::endl; std::cout << " \"center_proj_y\": " << rightScreen.yCOP << "," << std::endl; std::cout << " \"rotate_180\": 0" << std::endl; std::cout << " }" << std::endl; std::cout << " ]" << std::endl; // eyes std::cout << " }" << std::endl; // hmd std::cout << " }" << std::endl; // display std::cout << "}" << std::endl; // Closes outer object return 0; } static bool small(double d) { return fabs(d) <= 1e-5; } static int testAlgorithms() { if (g_verbose) { std::cerr << "=================== Starting testAlgorithms()" << std::endl; } // @todo std::cerr << "Warning: Test not yet implemented" << std::endl; if (g_verbose) { std::cerr << "=================== Successfully finished testAlgorithms()" << std::endl; } return 0; } <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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. */ #ifndef FLUSSPFERD_NATIVE_OBJECT_BASE_HPP #define FLUSSPFERD_NATIVE_OBJECT_BASE_HPP #include "object.hpp" #include "convert.hpp" #include "function_adapter.hpp" #include <boost/scoped_ptr.hpp> #include <boost/noncopyable.hpp> #include <boost/function.hpp> #include <boost/type_traits/is_base_of.hpp> #include <boost/type_traits/is_member_function_pointer.hpp> #include <boost/any.hpp> #include <memory> #include <functional> namespace flusspferd { #ifndef IN_DOXYGEN struct call_context; class tracer; namespace detail { object create_native_object(object const &proto); object create_native_enumerable_object(object const &proto); } #endif /** * Native object base. * * @ingroup classes */ class native_object_base : public object, private boost::noncopyable { public: /// Destructor. virtual ~native_object_base() = 0; /** * Explicitly return the associated object. * * @return The associated object. */ object get_object() { return *static_cast<object*>(this); } /** * Get the native object associated with a Javascript object. * * @return A reference to the object. */ static native_object_base &get_native(object const &o); public: /** * Associate with an object if there is no association yet. * * Do not use directly. * * @param o The object to associate with. */ void load_into(object const &o); protected: /** * Constructor. * * Immediately associates with object @p o. * * Do not use with arbitrary objects. * * @param o The object to associate with. */ native_object_base(object const &o); protected: /** * Virtual method invoked whenever the object is called as if it were a * function. * * Default implementation: throw an exception. * * @param x The call context. */ virtual void self_call(call_context &x); /** * Virtual method invoked whenever the object has to be traced. * * Default implementation: stub. * * For each value that is an otherwise unreachable member of the object and * that should be protected from garbage collection, call @c trc("x", x). * The string "x" does not need to be unique, it's used for debugging * purposes only. * * @code flusspferd::value v; ... void trace(flusspferd::tracer &trc) { trc("v", v); } @endcode * * @param trc The tracer to be used. * * @see @ref gc */ virtual void trace(tracer &trc); protected: /** * Possible property access methods. Can be combined by bitwise or. */ enum property_access { /** * The property access uses the @c . or @c [] operator: * @c obj.id or @c obj[id], not @c id. */ property_qualified = 1, /** * The property appears on the left-hand side of an assignment. */ property_assigning = 2, /** * The property is being used in code like "<code>if (o.p) ...</code>", * or a similar idiom where the apparent purpose of the property access is * to detect whether the property exists. */ property_detecting = 4, /** * The property is being declared in a var, const, or function declaration. */ property_declaring = 8, /** * class name used when constructing. (???) */ property_classname = 16 }; /** * Virtual method invoked when a property is <em>not</em> found on an object. * * Default implementation: stub that returns @c false. * * It can be used to implement lazy properties. * * If possible, @p id will be an integer, or a string otherwise. * * @param id The property name / index. * @param access Information about the kind of property access. A combination * of #property_access values. */ virtual bool property_resolve(value const &id, unsigned access); /** * Virtual method invoked to start enumerating properties. * * Will be called only if class_info::custom_enumerate is activated. * * Default implementation: return boost::any(). * * @param[out] num_properties The number of properties, if that can be * computed in advance. Otherwise should be set to zero. * Pre-initialized to zero. * @return An opaque iterator for use by #enumerate_next. */ virtual boost::any enumerate_start(int &num_properties); /** * Virtual method invoked to advance the enumeration and pull out the next * property name / index. * * Default implementation: return @c value(). * * Should return @c value() (@c undefined) to stop the enumeration. * * @param[in,out] iter The opaque iterator. * @return The next property name / index. */ virtual value enumerate_next(boost::any &iter); /** * Possible modes for native_object_base::property_op. */ enum property_mode { /** * Used just before a new property is added to an object. */ property_add = 0, /** * Used during most property deletions, even when the object has no property * with the given name / index. * * Will <em>not</em> be used for permanent properties. */ property_delete = -1, /** * Used as the default getter for new properties or for non-existing * properties. */ property_get = 1, /** * Used as the default setter for new properties. */ property_set = 2 }; /** * Virtual method invoked for property addition, deletion, read access and * write access. * * Default implementation: stub. * * @param mode The reason for invocation. * @param id The property name / index. * @param[in,out] data The old/new value of the property. * * @see property_mode */ virtual void property_op(property_mode mode, value const &id, value &data); private: #ifndef IN_DOXYGEN static object do_create_object(object const &proto); static object do_create_enumerable_object(object const &proto); friend object detail::create_native_object(object const &proto); friend object detail::create_native_enumerable_object(object const &proto); private: class impl; boost::scoped_ptr<impl> p; friend class impl; #endif }; template<typename T> T &cast_to_derived(native_object_base &o) { T *ptr = dynamic_cast<T*>(&o); if (!ptr) throw exception("Could not convert native object to derived type"); return *ptr; } template<typename T> T &get_native(object const &o) { return cast_to_derived<T>(native_object_base::get_native(o)); } template<typename T> bool is_derived(native_object_base &o) { return dynamic_cast<T*>(&o); } /** * Checks if @p o is a @p T. * * @param o object to check * @see get_native * @ingroup classes */ template<typename T> bool is_native(object const &o) { return is_derived<T>(native_object_base::get_native(o)); } template<typename T> struct detail::convert_ptr<T, native_object_base> { struct to_value { value perform(T *ptr) { if (!ptr) return object(); return *static_cast<object const *>(ptr); } }; struct from_value { T *perform(value const &v) { if (!v.is_object()) throw exception("Value is no object"); return &native_object_base::get_native(v.get_object()); } }; }; namespace detail { template<typename T, typename O> struct convert_ptr< T, O, typename boost::enable_if< typename boost::is_base_of<native_object_base, O>::type >::type > { typedef typename convert_ptr<T, native_object_base>::to_value to_value; struct from_value { typename convert_ptr<native_object_base>::from_value base; T *perform(value const &v) { return &dynamic_cast<T&>(*base.perform(v)); } }; }; } } #endif <commit_msg>docs: Example usage of is_native<T>(o)<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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. */ #ifndef FLUSSPFERD_NATIVE_OBJECT_BASE_HPP #define FLUSSPFERD_NATIVE_OBJECT_BASE_HPP #include "object.hpp" #include "convert.hpp" #include "function_adapter.hpp" #include <boost/scoped_ptr.hpp> #include <boost/noncopyable.hpp> #include <boost/function.hpp> #include <boost/type_traits/is_base_of.hpp> #include <boost/type_traits/is_member_function_pointer.hpp> #include <boost/any.hpp> #include <memory> #include <functional> namespace flusspferd { #ifndef IN_DOXYGEN struct call_context; class tracer; namespace detail { object create_native_object(object const &proto); object create_native_enumerable_object(object const &proto); } #endif /** * Native object base. * * @ingroup classes */ class native_object_base : public object, private boost::noncopyable { public: /// Destructor. virtual ~native_object_base() = 0; /** * Explicitly return the associated object. * * @return The associated object. */ object get_object() { return *static_cast<object*>(this); } /** * Get the native object associated with a Javascript object. * * @return A reference to the object. */ static native_object_base &get_native(object const &o); public: /** * Associate with an object if there is no association yet. * * Do not use directly. * * @param o The object to associate with. */ void load_into(object const &o); protected: /** * Constructor. * * Immediately associates with object @p o. * * Do not use with arbitrary objects. * * @param o The object to associate with. */ native_object_base(object const &o); protected: /** * Virtual method invoked whenever the object is called as if it were a * function. * * Default implementation: throw an exception. * * @param x The call context. */ virtual void self_call(call_context &x); /** * Virtual method invoked whenever the object has to be traced. * * Default implementation: stub. * * For each value that is an otherwise unreachable member of the object and * that should be protected from garbage collection, call @c trc("x", x). * The string "x" does not need to be unique, it's used for debugging * purposes only. * * @code flusspferd::value v; ... void trace(flusspferd::tracer &trc) { trc("v", v); } @endcode * * @param trc The tracer to be used. * * @see @ref gc */ virtual void trace(tracer &trc); protected: /** * Possible property access methods. Can be combined by bitwise or. */ enum property_access { /** * The property access uses the @c . or @c [] operator: * @c obj.id or @c obj[id], not @c id. */ property_qualified = 1, /** * The property appears on the left-hand side of an assignment. */ property_assigning = 2, /** * The property is being used in code like "<code>if (o.p) ...</code>", * or a similar idiom where the apparent purpose of the property access is * to detect whether the property exists. */ property_detecting = 4, /** * The property is being declared in a var, const, or function declaration. */ property_declaring = 8, /** * class name used when constructing. (???) */ property_classname = 16 }; /** * Virtual method invoked when a property is <em>not</em> found on an object. * * Default implementation: stub that returns @c false. * * It can be used to implement lazy properties. * * If possible, @p id will be an integer, or a string otherwise. * * @param id The property name / index. * @param access Information about the kind of property access. A combination * of #property_access values. */ virtual bool property_resolve(value const &id, unsigned access); /** * Virtual method invoked to start enumerating properties. * * Will be called only if class_info::custom_enumerate is activated. * * Default implementation: return boost::any(). * * @param[out] num_properties The number of properties, if that can be * computed in advance. Otherwise should be set to zero. * Pre-initialized to zero. * @return An opaque iterator for use by #enumerate_next. */ virtual boost::any enumerate_start(int &num_properties); /** * Virtual method invoked to advance the enumeration and pull out the next * property name / index. * * Default implementation: return @c value(). * * Should return @c value() (@c undefined) to stop the enumeration. * * @param[in,out] iter The opaque iterator. * @return The next property name / index. */ virtual value enumerate_next(boost::any &iter); /** * Possible modes for native_object_base::property_op. */ enum property_mode { /** * Used just before a new property is added to an object. */ property_add = 0, /** * Used during most property deletions, even when the object has no property * with the given name / index. * * Will <em>not</em> be used for permanent properties. */ property_delete = -1, /** * Used as the default getter for new properties or for non-existing * properties. */ property_get = 1, /** * Used as the default setter for new properties. */ property_set = 2 }; /** * Virtual method invoked for property addition, deletion, read access and * write access. * * Default implementation: stub. * * @param mode The reason for invocation. * @param id The property name / index. * @param[in,out] data The old/new value of the property. * * @see property_mode */ virtual void property_op(property_mode mode, value const &id, value &data); private: #ifndef IN_DOXYGEN static object do_create_object(object const &proto); static object do_create_enumerable_object(object const &proto); friend object detail::create_native_object(object const &proto); friend object detail::create_native_enumerable_object(object const &proto); private: class impl; boost::scoped_ptr<impl> p; friend class impl; #endif }; template<typename T> T &cast_to_derived(native_object_base &o) { T *ptr = dynamic_cast<T*>(&o); if (!ptr) throw exception("Could not convert native object to derived type"); return *ptr; } template<typename T> T &get_native(object const &o) { return cast_to_derived<T>(native_object_base::get_native(o)); } template<typename T> bool is_derived(native_object_base &o) { return dynamic_cast<T*>(&o); } /** * Checks if @p o is a native object of class @p T. * * @code flusspferd::object o = v.get_object(); if (flusspferd::is_native<flusspferd::binary>(o) { flusspferd::binary b = flusspferd::get_native<flusspferd::binary>(o); } @endcode * * @param o object to check * @see get_native * @ingroup classes */ template<typename T> bool is_native(object const &o) { return is_derived<T>(native_object_base::get_native(o)); } template<typename T> struct detail::convert_ptr<T, native_object_base> { struct to_value { value perform(T *ptr) { if (!ptr) return object(); return *static_cast<object const *>(ptr); } }; struct from_value { T *perform(value const &v) { if (!v.is_object()) throw exception("Value is no object"); return &native_object_base::get_native(v.get_object()); } }; }; namespace detail { template<typename T, typename O> struct convert_ptr< T, O, typename boost::enable_if< typename boost::is_base_of<native_object_base, O>::type >::type > { typedef typename convert_ptr<T, native_object_base>::to_value to_value; struct from_value { typename convert_ptr<native_object_base>::from_value base; T *perform(value const &v) { return &dynamic_cast<T&>(*base.perform(v)); } }; }; } } #endif <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelGLMapper2D.h" #include "mitkBaseRenderer.h" #include "mitkPlaneGeometry.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkContourModel.h" #include "mitkContourModelSubDivisionFilter.h" #include <vtkLinearTransform.h> #include "mitkGL.h" mitk::ContourModelGLMapper2D::ContourModelGLMapper2D() { } mitk::ContourModelGLMapper2D::~ContourModelGLMapper2D() { } void mitk::ContourModelGLMapper2D::Paint(mitk::BaseRenderer * renderer) { BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if ( !visible ) return; bool updateNeccesary=true; int timestep = renderer->GetTimeStep(); mitk::ContourModel::Pointer input = const_cast<mitk::ContourModel*>(this->GetInput()); mitk::ContourModel::Pointer renderingContour = input; bool subdivision = false; this->GetDataNode()->GetBoolProperty( "subdivision curve", subdivision, renderer ); if (subdivision) { mitk::ContourModel::Pointer subdivContour = mitk::ContourModel::New(); mitk::ContourModelSubDivisionFilter::Pointer subdivFilter = mitk::ContourModelSubDivisionFilter::New(); subdivFilter->SetInput(input); subdivFilter->Update(); subdivContour = subdivFilter->GetOutput(); if(subdivContour->GetNumberOfVertices() == 0 ) { subdivContour = input; } renderingContour = subdivContour; } renderingContour->UpdateOutputInformation(); if( renderingContour->GetMTime() < ls->GetLastGenerateDataTime() ) updateNeccesary = false; if(renderingContour->GetNumberOfVertices(timestep) < 1) updateNeccesary = false; if (updateNeccesary) { // ok, das ist aus GenerateData kopiert mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry(); assert(displayGeometry.IsNotNull()); //apply color and opacity read from the PropertyList ApplyProperties(renderer); bool isEditing = false; GetDataNode()->GetBoolProperty("contour.editing", isEditing); mitk::ColorProperty::Pointer colorprop; if (isEditing) colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("contour.editing.color", renderer)); else colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("contour.color", renderer)); if(colorprop) { //set the color of the contour double red = colorprop->GetColor().GetRed(); double green = colorprop->GetColor().GetGreen(); double blue = colorprop->GetColor().GetBlue(); glColor4f(red,green,blue,0.5); } mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("points.color", renderer)); if(!selectedcolor) { selectedcolor = mitk::ColorProperty::New(1.0,0.0,0.1); } vtkLinearTransform* transform = GetDataNode()->GetVtkTransform(); // ContourModel::OutputType point; mitk::Point3D point; mitk::Point3D p, projected_p; float vtkp[3]; float lineWidth = 3.0; bool isHovering = false; this->GetDataNode()->GetBoolProperty("contour.hovering", isHovering); if (isHovering) this->GetDataNode()->GetFloatProperty("contour.hovering.width", lineWidth); else this->GetDataNode()->GetFloatProperty("contour.width", lineWidth); bool drawit=false; mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep); Point2D pt2d; // projected_p in display coordinates Point2D lastPt2d; while ( pointsIt != renderingContour->IteratorEnd(timestep) ) { lastPt2d = pt2d; point = (*pointsIt)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); Vector3D diff=p-projected_p; ScalarType scalardiff = diff.GetNorm(); //draw lines bool projectmode=false; GetDataNode()->GetVisibility(projectmode, renderer, "contour.project-onto-plane"); if(projectmode) { drawit=true; } else if(scalardiff<0.25) { drawit=true; } if(drawit) { //lastPt2d is not valid in first step if( !(pointsIt == renderingContour->IteratorBegin(timestep)) ) { glLineWidth(lineWidth); glBegin (GL_LINES); glVertex2f(pt2d[0], pt2d[1]); glVertex2f(lastPt2d[0], lastPt2d[1]); glEnd(); } //draw active points if ((*pointsIt)->IsControlPoint) { float pointsize = 4; Point2D tmp; Vector2D horz,vert; horz[1]=0; vert[0]=0; horz[0]=pointsize; vert[1]=pointsize; glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen()); glLineWidth(1); //a rectangle around the point with the selected color glBegin (GL_LINE_LOOP); tmp=pt2d-horz; glVertex2fv(&tmp[0]); tmp=pt2d+vert; glVertex2fv(&tmp[0]); tmp=pt2d+horz; glVertex2fv(&tmp[0]); tmp=pt2d-vert; glVertex2fv(&tmp[0]); glEnd(); glLineWidth(1); //the actual point in the specified color to see the usual color of the point glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue()); glPointSize(1); glBegin (GL_POINTS); tmp=pt2d; glVertex2fv(&tmp[0]); glEnd (); } } pointsIt++; }//end while iterate over controlpoints // make sure the line is set back to default value glLineWidth(1); //close contour if necessary if(renderingContour->IsClosed(timestep) && drawit) { lastPt2d = pt2d; point = renderingContour->GetVertexAt(0,timestep)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); glBegin (GL_LINES); glVertex2f(lastPt2d[0], lastPt2d[1]); glVertex2f( pt2d[0], pt2d[1] ); glEnd(); } //draw selected vertex if exists if(renderingContour->GetSelectedVertex()) { //transform selected vertex point = renderingContour->GetSelectedVertex()->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); Vector3D diff=p-projected_p; ScalarType scalardiff = diff.GetNorm(); //---------------------------------- //draw point if close to plane if(scalardiff<0.25) { float pointsize = 3.2; Point2D tmp; glColor3f(0.0, 1.0, 0.0); glLineWidth(1); //a diamond around the point glBegin (GL_LINE_LOOP); //begin from upper left corner and paint clockwise tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2fv(&tmp[0]); tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2fv(&tmp[0]); tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2fv(&tmp[0]); tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2fv(&tmp[0]); glEnd (); } //------------------------------------ } } } const mitk::ContourModel* mitk::ContourModelGLMapper2D::GetInput(void) { return static_cast<const mitk::ContourModel * > ( GetDataNode()->GetData() ); } void mitk::ContourModelGLMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { node->AddProperty( "contour.color", ColorProperty::New(0.9, 1.0, 0.1), renderer, overwrite ); node->AddProperty( "contour.editing", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "contour.editing.color", ColorProperty::New(0.1, 0.9, 0.1), renderer, overwrite ); node->AddProperty( "points.color", ColorProperty::New(1.0, 0.0, 0.1), renderer, overwrite ); node->AddProperty( "contour.width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite ); node->AddProperty( "contour.hovering.width", mitk::FloatProperty::New( 3.0 ), renderer, overwrite ); node->AddProperty( "contour.hovering", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "subdivision curve", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "contour.project-onto-plane", mitk::BoolProperty::New( false ), renderer, overwrite ); Superclass::SetDefaultProperties(node, renderer, overwrite); } <commit_msg>- fixed closing contour. - set a bigger box for selected vertex<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelGLMapper2D.h" #include "mitkBaseRenderer.h" #include "mitkPlaneGeometry.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkContourModel.h" #include "mitkContourModelSubDivisionFilter.h" #include <vtkLinearTransform.h> #include "mitkGL.h" mitk::ContourModelGLMapper2D::ContourModelGLMapper2D() { } mitk::ContourModelGLMapper2D::~ContourModelGLMapper2D() { } void mitk::ContourModelGLMapper2D::Paint(mitk::BaseRenderer * renderer) { BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if ( !visible ) return; bool updateNeccesary=true; int timestep = renderer->GetTimeStep(); mitk::ContourModel::Pointer input = const_cast<mitk::ContourModel*>(this->GetInput()); mitk::ContourModel::Pointer renderingContour = input; bool subdivision = false; this->GetDataNode()->GetBoolProperty( "subdivision curve", subdivision, renderer ); if (subdivision) { mitk::ContourModel::Pointer subdivContour = mitk::ContourModel::New(); mitk::ContourModelSubDivisionFilter::Pointer subdivFilter = mitk::ContourModelSubDivisionFilter::New(); subdivFilter->SetInput(input); subdivFilter->Update(); subdivContour = subdivFilter->GetOutput(); if(subdivContour->GetNumberOfVertices() == 0 ) { subdivContour = input; } renderingContour = subdivContour; } renderingContour->UpdateOutputInformation(); if( renderingContour->GetMTime() < ls->GetLastGenerateDataTime() ) updateNeccesary = false; if(renderingContour->GetNumberOfVertices(timestep) < 1) updateNeccesary = false; if (updateNeccesary) { // ok, das ist aus GenerateData kopiert mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry(); assert(displayGeometry.IsNotNull()); //apply color and opacity read from the PropertyList ApplyProperties(renderer); bool isEditing = false; GetDataNode()->GetBoolProperty("contour.editing", isEditing); mitk::ColorProperty::Pointer colorprop; if (isEditing) colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("contour.editing.color", renderer)); else colorprop = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("contour.color", renderer)); if(colorprop) { //set the color of the contour double red = colorprop->GetColor().GetRed(); double green = colorprop->GetColor().GetGreen(); double blue = colorprop->GetColor().GetBlue(); glColor4f(red,green,blue,0.5); } mitk::ColorProperty::Pointer selectedcolor = dynamic_cast<mitk::ColorProperty*>(GetDataNode()->GetProperty("points.color", renderer)); if(!selectedcolor) { selectedcolor = mitk::ColorProperty::New(1.0,0.0,0.1); } vtkLinearTransform* transform = GetDataNode()->GetVtkTransform(); // ContourModel::OutputType point; mitk::Point3D point; mitk::Point3D p, projected_p; float vtkp[3]; float lineWidth = 3.0; bool isHovering = false; this->GetDataNode()->GetBoolProperty("contour.hovering", isHovering); if (isHovering) this->GetDataNode()->GetFloatProperty("contour.hovering.width", lineWidth); else this->GetDataNode()->GetFloatProperty("contour.width", lineWidth); bool drawit=false; mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep); Point2D pt2d; // projected_p in display coordinates Point2D lastPt2d; while ( pointsIt != renderingContour->IteratorEnd(timestep) ) { lastPt2d = pt2d; point = (*pointsIt)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); Vector3D diff=p-projected_p; ScalarType scalardiff = diff.GetNorm(); //draw lines bool projectmode=false; GetDataNode()->GetVisibility(projectmode, renderer, "contour.project-onto-plane"); if(projectmode) { drawit=true; } else if(scalardiff<0.25) { drawit=true; } if(drawit) { //lastPt2d is not valid in first step if( !(pointsIt == renderingContour->IteratorBegin(timestep)) ) { glLineWidth(lineWidth); glBegin (GL_LINES); glVertex2f(pt2d[0], pt2d[1]); glVertex2f(lastPt2d[0], lastPt2d[1]); glEnd(); glLineWidth(1); } //draw active points if ((*pointsIt)->IsControlPoint) { float pointsize = 4; Point2D tmp; Vector2D horz,vert; horz[1]=0; vert[0]=0; horz[0]=pointsize; vert[1]=pointsize; glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen()); glLineWidth(1); //a rectangle around the point with the selected color glBegin (GL_LINE_LOOP); tmp=pt2d-horz; glVertex2fv(&tmp[0]); tmp=pt2d+vert; glVertex2fv(&tmp[0]); tmp=pt2d+horz; glVertex2fv(&tmp[0]); tmp=pt2d-vert; glVertex2fv(&tmp[0]); glEnd(); glLineWidth(1); //the actual point in the specified color to see the usual color of the point glColor3f(colorprop->GetColor().GetRed(),colorprop->GetColor().GetGreen(),colorprop->GetColor().GetBlue()); glPointSize(1); glBegin (GL_POINTS); tmp=pt2d; glVertex2fv(&tmp[0]); glEnd (); } } pointsIt++; }//end while iterate over controlpoints //close contour if necessary if(renderingContour->IsClosed(timestep) && drawit) { lastPt2d = pt2d; point = renderingContour->GetVertexAt(0,timestep)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); glLineWidth(lineWidth); glBegin (GL_LINES); glVertex2f(lastPt2d[0], lastPt2d[1]); glVertex2f( pt2d[0], pt2d[1] ); glEnd(); glLineWidth(1); } //draw selected vertex if exists if(renderingContour->GetSelectedVertex()) { //transform selected vertex point = renderingContour->GetSelectedVertex()->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp,p); displayGeometry->Project(p, projected_p); displayGeometry->Map(projected_p, pt2d); displayGeometry->WorldToDisplay(pt2d, pt2d); Vector3D diff=p-projected_p; ScalarType scalardiff = diff.GetNorm(); //---------------------------------- //draw point if close to plane if(scalardiff<0.25) { float pointsize = 5; Point2D tmp; glColor3f(0.0, 1.0, 0.0); glLineWidth(1); //a diamond around the point glBegin (GL_LINE_LOOP); //begin from upper left corner and paint clockwise tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2fv(&tmp[0]); tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]+pointsize; glVertex2fv(&tmp[0]); tmp[0]=pt2d[0]+pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2fv(&tmp[0]); tmp[0]=pt2d[0]-pointsize; tmp[1]=pt2d[1]-pointsize; glVertex2fv(&tmp[0]); glEnd (); } //------------------------------------ } } } const mitk::ContourModel* mitk::ContourModelGLMapper2D::GetInput(void) { return static_cast<const mitk::ContourModel * > ( GetDataNode()->GetData() ); } void mitk::ContourModelGLMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { node->AddProperty( "contour.color", ColorProperty::New(0.9, 1.0, 0.1), renderer, overwrite ); node->AddProperty( "contour.editing", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "contour.editing.color", ColorProperty::New(0.1, 0.9, 0.1), renderer, overwrite ); node->AddProperty( "points.color", ColorProperty::New(1.0, 0.0, 0.1), renderer, overwrite ); node->AddProperty( "contour.width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite ); node->AddProperty( "contour.hovering.width", mitk::FloatProperty::New( 3.0 ), renderer, overwrite ); node->AddProperty( "contour.hovering", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "subdivision curve", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "contour.project-onto-plane", mitk::BoolProperty::New( false ), renderer, overwrite ); Superclass::SetDefaultProperties(node, renderer, overwrite); } <|endoftext|>
<commit_before>#include <iostream> #include <time.h> #include <sys/time.h> #include <string> //#define FUNCTION_TIME(x) gmtime(x) #define FUNCTION_TIME(x) localtime(x) using namespace std; int main (int argc, char *argv[]) { time_t ltime; //int timestamp = 1246962445; int timestamp = 10; struct tm *Tm; /* time: Get the current time (number of seconds from the epoch) from the system clock. Stores that value in timer. If timer is null, the value is not stored, but it is still returned by the function. */ ltime=time(NULL); cout << "ltime --> " << ltime << endl; /* localtime: Convert a time_t time value to a tm structure as local time. This structure is statically allocated and shared by gmtime, localtime and ctime functions. Each time one of these functions is called the content of the structure is overwritten. */ Tm=localtime(&ltime); //Tm=localtime((const time_t*) &timestamp); cout << endl << Tm->tm_wday << " " << Tm->tm_mday << "/" << Tm->tm_mon+1 << "/" << Tm->tm_year+1900 << " "; cout << Tm->tm_hour << ":" << Tm->tm_min << ":" << Tm->tm_sec << endl; Tm=gmtime((const time_t*) &timestamp); cout << endl << Tm->tm_wday << " " << Tm->tm_mday << "/" << Tm->tm_mon+1 << "/" << Tm->tm_year+1900 << " "; cout << Tm->tm_hour << ":" << Tm->tm_min << ":" << Tm->tm_sec << endl; /* printf("[%d] %d %d %d, %d:%d:%d", Tm->tm_wday, // Mon - Sun Tm->tm_mday, Tm->tm_mon+1, Tm->tm_year+1900, Tm->tm_hour, Tm->tm_min, Tm->tm_sec); */ struct timeval detail_time; gettimeofday(&detail_time,NULL); printf("%d %d", detail_time.tv_usec /1000, /* milliseconds */ detail_time.tv_usec); /* microseconds */ } <commit_msg>fix core dump<commit_after>#include <iostream> #include <time.h> #include <sys/time.h> #include <string> //#define FUNCTION_TIME(x) gmtime(x) #define FUNCTION_TIME(x) localtime(x) using namespace std; int main (int argc, char *argv[]) { time_t ltime; //int timestamp = 1246962445; const time_t timestamp = 10; struct tm *Tm; /* time: Get the current time (number of seconds from the epoch) from the system clock. Stores that value in timer. If timer is null, the value is not stored, but it is still returned by the function. */ ltime=time(NULL); cout << "ltime --> " << ltime << endl; /* localtime: Convert a time_t time value to a tm structure as local time. This structure is statically allocated and shared by gmtime, localtime and ctime functions. Each time one of these functions is called the content of the structure is overwritten. */ Tm=localtime(&ltime); //Tm=localtime((const time_t*) &timestamp); cout << endl << Tm->tm_wday << " " << Tm->tm_mday << "/" << Tm->tm_mon+1 << "/" << Tm->tm_year+1900 << " "; cout << Tm->tm_hour << ":" << Tm->tm_min << ":" << Tm->tm_sec << endl; Tm=gmtime(&timestamp); cout << endl << Tm->tm_wday << " " << Tm->tm_mday << "/" << Tm->tm_mon+1 << "/" << Tm->tm_year+1900 << " "; cout << Tm->tm_hour << ":" << Tm->tm_min << ":" << Tm->tm_sec << endl; /* printf("[%d] %d %d %d, %d:%d:%d", Tm->tm_wday, // Mon - Sun Tm->tm_mday, Tm->tm_mon+1, Tm->tm_year+1900, Tm->tm_hour, Tm->tm_min, Tm->tm_sec); */ struct timeval detail_time; gettimeofday(&detail_time,NULL); printf("%li %li \n", detail_time.tv_usec /1000, /* milliseconds */ detail_time.tv_usec); /* microseconds */ } <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <math.h> #include "norad.h" #include "norad_in.h" /* Example code to add BSTAR data using Ted Molczan's method. It just reads in TLEs, computes BSTAR if possible, then writes out the resulting modified TLE. Add the '-v' (verbose) switch, and it also writes out the orbital period and perigee/apogee distances. Eventually, I'll probably set it up to dump other data that are not immediately obvious just by looking at the TLEs... */ int main( const int argc, const char **argv) { FILE *ifile; const char *filename; char line1[100], line2[100]; int i, verbose = 0; const char *norad = NULL, *intl = NULL; bool legend_shown = false; for( i = 2; i < argc; i++) if( argv[i][0] == '-') switch( argv[i][1]) { case 'v': verbose = 1; break; case 'n': norad = argv[i] + 2; if( !*norad && i < argc - 1) norad = argv[++i]; printf( "Looking for NORAD %s\n", norad); break; case 'i': intl = argv[i] + 2; if( !*intl && i < argc - 1) intl = argv[++i]; printf( "Looking for international ID %s\n", intl); break; default: printf( "'%s': unrecognized option\n", argv[i]); return( -1); break; } filename = (argc == 1 ? "all_tle.txt" : argv[1]); ifile = fopen( filename, "rb"); if( !ifile) { fprintf( stderr, "Couldn't open '%s': ", filename); perror( ""); return( -1); } while( fgets( line1, sizeof( line1), ifile)) if( *line1 == '1' && (!norad || !memcmp( line1 + 2, norad, 5)) && (!intl || !memcmp( line1 + 9, intl, 5)) && fgets( line2, sizeof( line2), ifile) && *line2 == '2') { tle_t tle; if( parse_elements( line1, line2, &tle) >= 0) { char obuff[200]; double params[N_SGP4_PARAMS], c2; if( verbose && !legend_shown) { legend_shown = true; printf( "1 NoradU COSPAR Epoch.epoch dn/dt/2 d2n/dt2/6 BSTAR T El# C\n" "2 NoradU Inclina RAAscNode Eccent ArgPeri MeanAno MeanMotion Rev# C\n"); } SGP4_init( params, &tle); c2 = params[0]; if( c2 && tle.xno) tle.bstar = tle.xndt2o / (tle.xno * c2 * 1.5); write_elements_in_tle_format( obuff, &tle); printf( "%s", obuff); if( verbose) { const double a1 = pow(xke / tle.xno, two_thirds); /* in Earth radii */ printf( " Perigee: %.4f km\n", (a1 * (1. - tle.eo) - 1.) * earth_radius_in_km); printf( " Apogee: %.4f km\n", (a1 * (1. + tle.eo) - 1.) * earth_radius_in_km); printf( " Orbital period: %.4f min\n", 2. * pi / tle.xno); printf( " Epoch: JD %.5f\n", tle.epoch); } } } else if( !norad && !intl) printf( "%s", line1); fclose( ifile); return( 0); } <commit_msg>Display the 'line 0' (object name, sometimes brightness and size) data<commit_after>#include <stdio.h> #include <string.h> #include <math.h> #include "norad.h" #include "norad_in.h" /* Example code to add BSTAR data using Ted Molczan's method. It just reads in TLEs, computes BSTAR if possible, then writes out the resulting modified TLE. Add the '-v' (verbose) switch, and it also writes out the orbital period and perigee/apogee distances. Eventually, I'll probably set it up to dump other data that are not immediately obvious just by looking at the TLEs... */ int main( const int argc, const char **argv) { FILE *ifile; const char *filename; char line0[100], line1[100], line2[100]; int i, verbose = 0; const char *norad = NULL, *intl = NULL; bool legend_shown = false; for( i = 2; i < argc; i++) if( argv[i][0] == '-') switch( argv[i][1]) { case 'v': verbose = 1; break; case 'n': norad = argv[i] + 2; if( !*norad && i < argc - 1) norad = argv[++i]; printf( "Looking for NORAD %s\n", norad); break; case 'i': intl = argv[i] + 2; if( !*intl && i < argc - 1) intl = argv[++i]; printf( "Looking for international ID %s\n", intl); break; default: printf( "'%s': unrecognized option\n", argv[i]); return( -1); break; } filename = (argc == 1 ? "all_tle.txt" : argv[1]); ifile = fopen( filename, "rb"); if( !ifile) { fprintf( stderr, "Couldn't open '%s': ", filename); perror( ""); return( -1); } if( !fgets( line0, sizeof( line0), ifile) || !fgets( line1, sizeof( line1), ifile)) perror( "Couldn't read from input file"); while( fgets( line2, sizeof( line2), ifile)) { if( *line1 == '1' && (!norad || !memcmp( line1 + 2, norad, 5)) && (!intl || !memcmp( line1 + 9, intl, 5)) && *line2 == '2') { tle_t tle; if( parse_elements( line1, line2, &tle) >= 0) { char obuff[200]; double params[N_SGP4_PARAMS], c2; if( verbose && !legend_shown) { legend_shown = true; printf( "1 NoradU COSPAR Epoch.epoch dn/dt/2 d2n/dt2/6 BSTAR T El# C\n" "2 NoradU Inclina RAAscNode Eccent ArgPeri MeanAno MeanMotion Rev# C\n"); } SGP4_init( params, &tle); c2 = params[0]; if( c2 && tle.xno) tle.bstar = tle.xndt2o / (tle.xno * c2 * 1.5); write_elements_in_tle_format( obuff, &tle); if( strlen( line0) < 60) printf( "%s", line0); printf( "%s", obuff); if( verbose) { const double a1 = pow(xke / tle.xno, two_thirds); /* in Earth radii */ printf( " Perigee: %.4f km\n", (a1 * (1. - tle.eo) - 1.) * earth_radius_in_km); printf( " Apogee: %.4f km\n", (a1 * (1. + tle.eo) - 1.) * earth_radius_in_km); printf( " Orbital period: %.4f min\n", 2. * pi / tle.xno); printf( " Epoch: JD %.5f\n", tle.epoch); } } } strcpy( line0, line1); strcpy( line1, line2); } fclose( ifile); return( 0); } <|endoftext|>
<commit_before>// @(#)root/reflex:$Name: $:$Id: ScopeName.cxx,v 1.9 2006/03/13 15:49:51 roiser Exp $ // Author: Stefan Roiser 2004 // Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. #ifndef REFLEX_BUILD #define REFLEX_BUILD #endif #include "Reflex/ScopeName.h" #include "Reflex/Scope.h" #include "Reflex/ScopeBase.h" #include "Reflex/Tools.h" #include "stl_hash.h" #include <vector> //------------------------------------------------------------------------------- typedef __gnu_cxx::hash_map < const char *, ROOT::Reflex::ScopeName * > Name2Scope_t; typedef std::vector< ROOT::Reflex::Scope > ScopeVec_t; //------------------------------------------------------------------------------- static Name2Scope_t & sScopes() { //------------------------------------------------------------------------------- static Name2Scope_t m; return m; } //------------------------------------------------------------------------------- static ScopeVec_t & sScopeVec() { //------------------------------------------------------------------------------- static ScopeVec_t m; return m; } //------------------------------------------------------------------------------- ROOT::Reflex::ScopeName::ScopeName( const char * name, ScopeBase * scopeBase ) : fName(name), fScopeBase(scopeBase) { //------------------------------------------------------------------------------- sScopes() [ fName.c_str() ] = this; sScopeVec().push_back(Scope(this)); //---Build recursively the declaring scopeNames if( fName != "@N@I@R@V@A@N@A@" ) { std::string decl_name = Tools::GetScopeName(fName); if ( ! Scope::ByName( decl_name ).Id() ) new ScopeName( decl_name.c_str(), 0 ); } } //------------------------------------------------------------------------------- ROOT::Reflex::ScopeName::~ScopeName() { //------------------------------------------------------------------------------- } //------------------------------------------------------------------------------- ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ByName( const std::string & name ) { //------------------------------------------------------------------------------- size_t pos = name.substr(0,2) == "::" ? 2 : 0; Name2Scope_t::iterator it = sScopes().find(name.substr(pos).c_str()); if (it != sScopes().end() ) return Scope( it->second ); else return Scope(); } //------------------------------------------------------------------------------- ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ThisScope() const { //------------------------------------------------------------------------------- return Scope( this ); } //------------------------------------------------------------------------------- ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ScopeAt( size_t nth ) { //------------------------------------------------------------------------------- if ( nth < sScopeVec().size()) return sScopeVec()[nth]; return Scope(); } //------------------------------------------------------------------------------- size_t ROOT::Reflex::ScopeName::ScopeSize() { //------------------------------------------------------------------------------- return sScopeVec().size(); } //------------------------------------------------------------------------------- ROOT::Reflex::Scope_Iterator ROOT::Reflex::ScopeName::Scope_Begin() { //------------------------------------------------------------------------------- return sScopeVec().begin(); } //------------------------------------------------------------------------------- ROOT::Reflex::Scope_Iterator ROOT::Reflex::ScopeName::Scope_End() { //------------------------------------------------------------------------------- return sScopeVec().end(); } //------------------------------------------------------------------------------- ROOT::Reflex::Reverse_Scope_Iterator ROOT::Reflex::ScopeName::Scope_RBegin() { //------------------------------------------------------------------------------- return sScopeVec().rbegin(); } //------------------------------------------------------------------------------- ROOT::Reflex::Reverse_Scope_Iterator ROOT::Reflex::ScopeName::Scope_REnd() { //------------------------------------------------------------------------------- return sScopeVec().rend(); } <commit_msg>Ugly hack to workaround typedefs to Scopes. This has to be undone ASAP.<commit_after>// @(#)root/reflex:$Name: $:$Id: ScopeName.cxx,v 1.10 2006/03/20 09:46:18 roiser Exp $ // Author: Stefan Roiser 2004 // Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. #ifndef REFLEX_BUILD #define REFLEX_BUILD #endif #include "Reflex/ScopeName.h" #include "Reflex/Scope.h" #include "Reflex/ScopeBase.h" #include "Reflex/Tools.h" #include "stl_hash.h" #include <vector> //------------------------------------------------------------------------------- typedef __gnu_cxx::hash_map < const char *, ROOT::Reflex::ScopeName * > Name2Scope_t; typedef std::vector< ROOT::Reflex::Scope > ScopeVec_t; //------------------------------------------------------------------------------- static Name2Scope_t & sScopes() { //------------------------------------------------------------------------------- static Name2Scope_t m; return m; } //------------------------------------------------------------------------------- static ScopeVec_t & sScopeVec() { //------------------------------------------------------------------------------- static ScopeVec_t m; return m; } //------------------------------------------------------------------------------- ROOT::Reflex::ScopeName::ScopeName( const char * name, ScopeBase * scopeBase ) : fName(name), fScopeBase(scopeBase) { //------------------------------------------------------------------------------- sScopes() [ fName.c_str() ] = this; sScopeVec().push_back(Scope(this)); //---Build recursively the declaring scopeNames if( fName != "@N@I@R@V@A@N@A@" ) { std::string decl_name = Tools::GetScopeName(fName); if ( ! Scope::ByName( decl_name ).Id() ) new ScopeName( decl_name.c_str(), 0 ); } } //------------------------------------------------------------------------------- ROOT::Reflex::ScopeName::~ScopeName() { //------------------------------------------------------------------------------- } //------------------------------------------------------------------------------- ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ByName( const std::string & name ) { //------------------------------------------------------------------------------- size_t pos = name.substr(0,2) == "::" ? 2 : 0; Name2Scope_t::iterator it = sScopes().find(name.substr(pos).c_str()); if (it != sScopes().end() ) return Scope( it->second ); //else return Scope(); // HERE STARTS AN UGLY HACK WHICH HAS TO BE UNDONE ASAP Type t = Type::ByName("name"); if ( t && t.IsTypedef()) { while ( t.IsTypedef()) t = t.ToType(); if ( t.IsClass() || t.IsEnum() || t.IsUnion() ) return (Scope)t; } return Scope(); // END OF UGLY HACK } //------------------------------------------------------------------------------- ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ThisScope() const { //------------------------------------------------------------------------------- return Scope( this ); } //------------------------------------------------------------------------------- ROOT::Reflex::Scope ROOT::Reflex::ScopeName::ScopeAt( size_t nth ) { //------------------------------------------------------------------------------- if ( nth < sScopeVec().size()) return sScopeVec()[nth]; return Scope(); } //------------------------------------------------------------------------------- size_t ROOT::Reflex::ScopeName::ScopeSize() { //------------------------------------------------------------------------------- return sScopeVec().size(); } //------------------------------------------------------------------------------- ROOT::Reflex::Scope_Iterator ROOT::Reflex::ScopeName::Scope_Begin() { //------------------------------------------------------------------------------- return sScopeVec().begin(); } //------------------------------------------------------------------------------- ROOT::Reflex::Scope_Iterator ROOT::Reflex::ScopeName::Scope_End() { //------------------------------------------------------------------------------- return sScopeVec().end(); } //------------------------------------------------------------------------------- ROOT::Reflex::Reverse_Scope_Iterator ROOT::Reflex::ScopeName::Scope_RBegin() { //------------------------------------------------------------------------------- return sScopeVec().rbegin(); } //------------------------------------------------------------------------------- ROOT::Reflex::Reverse_Scope_Iterator ROOT::Reflex::ScopeName::Scope_REnd() { //------------------------------------------------------------------------------- return sScopeVec().rend(); } <|endoftext|>
<commit_before>#include "tree.h" Tree::Tree() { root = NULL; } // Copies a tree Tree::Tree(const Tree &tree){ // If we are not empty clear then rebuild if(root!=NULL) this->clear(); this->build(tree.commands); this->commands = tree.commands; } // Assignment operator Tree & Tree::operator= (const Tree& tree){ // If we are not empty clear then rebuild if(root!=NULL) this->clear(); this->build(tree.commands); this->commands = tree.commands; return *this; } // Returns whether the tree is empty bool Tree::isEmpty() { if (root == NULL) return true; return false; } void Tree::build(std::vector< std::vector<std::string> > vIn) { if ((vIn.size() % 2) != 0) { root = new Command(vIn.at(0)); if (vIn.size() > 1) { int i = 1; while (i < (((int) vIn.size()) - 1)) { if (vIn.at(i).at(0) == "&") { root = new And_Connector(root, new Command(vIn.at(i + 1))); } else if (vIn.at(i).at(0) == "|") { root = new Or_Connector(root, new Command(vIn.at(i + 1))); } else if (vIn.at(i).at(0) == ";") { root = new Semicolon_Connector(root, new Command(vIn.at(i + 1))); } i += 2; } } } } // Empty the tree void Tree::clear(){ if (root != NULL) { delete root; root = NULL; // Point it to NULL so we don't get garbage accessing it later } } // Executes the tree commands int Tree::execute(){ return root->execute(); } <commit_msg>updated Tree's build to create exit_commands<commit_after>#include "tree.h" Tree::Tree() { root = NULL; } // Copies a tree Tree::Tree(const Tree &tree){ // If we are not empty clear then rebuild if(root!=NULL) this->clear(); this->build(tree.commands); this->commands = tree.commands; } // Assignment operator Tree & Tree::operator= (const Tree& tree){ // If we are not empty clear then rebuild if(root!=NULL) this->clear(); this->build(tree.commands); this->commands = tree.commands; return *this; } // Returns whether the tree is empty bool Tree::isEmpty() { if (root == NULL) return true; return false; } void Tree::build(std::vector< std::vector<std::string> > vIn) { if ((vIn.size() % 2) != 0) { root = new Command(vIn.at(0)); if (vIn.size() > 1) { int i = 1; Base* command; while (i < (((int) vIn.size()) - 1)) { if (vIn.at(i + 1).at(0) == "exit") { command = new Exit_Command(); } else { command = new Command(vIn.at(i + 1)); } if (vIn.at(i).at(0) == "&") { root = new And_Connector(root, command); } else if (vIn.at(i).at(0) == "|") { root = new Or_Connector(root, command); } else if (vIn.at(i).at(0) == ";") { root = new Semicolon_Connector(root, command); } i += 2; } } } } // Empty the tree void Tree::clear(){ if (root != NULL) { delete root; root = NULL; // Point it to NULL so we don't get garbage accessing it later } } // Executes the tree commands int Tree::execute(){ return root->execute(); } <|endoftext|>
<commit_before>/** * @file GameInfo.cpp * * @author <a href="mailto:[email protected]">Mellmann, Heinrich</a> * @breief the game information in RoboCup */ #include <iostream> #include "GameData.h" using namespace naoth; using namespace std; GameData::GameData() : valid(false), playersPerTeam(0), competitionPhase(roundrobin), competitionType(competition_normal), gamePhase(normal), gameState(unknown_game_state), setPlay(set_none), firstHalf(true), kickingTeam(0), dropInTeam(0), dropInTime(0), secsRemaining(0), secondaryTime(0), // HACK: for more info see declaration newPlayerNumber(0) { } #define RETURN_VALUE_TO_STR(v) case v: return #v std::string GameData::toString(TeamColor value) { switch (value) { RETURN_VALUE_TO_STR(blue); RETURN_VALUE_TO_STR(red); RETURN_VALUE_TO_STR(yellow); RETURN_VALUE_TO_STR(black); RETURN_VALUE_TO_STR(white); RETURN_VALUE_TO_STR(green); RETURN_VALUE_TO_STR(orange); RETURN_VALUE_TO_STR(purple); RETURN_VALUE_TO_STR(brown); RETURN_VALUE_TO_STR(gray); RETURN_VALUE_TO_STR(unknown_team_color); } ASSERT(false); return "invalid TeamColor"; } std::string GameData::toString(CompetitionPhase value) { switch (value) { RETURN_VALUE_TO_STR(roundrobin); RETURN_VALUE_TO_STR(playoff); } ASSERT(false); return "invalid CompetitionPhase"; } std::string GameData::toString(CompetitionType value) { switch (value) { RETURN_VALUE_TO_STR(competition_normal); RETURN_VALUE_TO_STR(competition_mixed); RETURN_VALUE_TO_STR(competition_penalty); } ASSERT(false); return "invalid CompetitionType"; } std::string GameData::toString(GamePhase value) { switch (value) { RETURN_VALUE_TO_STR(normal); RETURN_VALUE_TO_STR(penaltyshoot); RETURN_VALUE_TO_STR(overtime); RETURN_VALUE_TO_STR(timeout); } ASSERT(false); return "invalid SecondaryGameState"; } std::string GameData::toString(GameState value) { switch (value) { RETURN_VALUE_TO_STR(initial); RETURN_VALUE_TO_STR(ready); RETURN_VALUE_TO_STR(set); RETURN_VALUE_TO_STR(playing); RETURN_VALUE_TO_STR(finished); RETURN_VALUE_TO_STR(unknown_game_state); } ASSERT(false); return "invalid GameState"; } std::string GameData::toString(SetPlay value) { switch (value) { RETURN_VALUE_TO_STR(set_none); RETURN_VALUE_TO_STR(goal_free_kick); RETURN_VALUE_TO_STR(pushing_free_kick); } ASSERT(false); return "invalid SetPlay"; } std::string GameData::toString(Penalty value) { switch (value) { RETURN_VALUE_TO_STR(penalty_none); RETURN_VALUE_TO_STR(illegal_ball_contact); RETURN_VALUE_TO_STR(player_pushing); RETURN_VALUE_TO_STR(illegal_motion_in_set); RETURN_VALUE_TO_STR(inactive_player); RETURN_VALUE_TO_STR(illegal_defender); RETURN_VALUE_TO_STR(leaving_the_field); RETURN_VALUE_TO_STR(kick_off_goal); RETURN_VALUE_TO_STR(request_for_pickup); RETURN_VALUE_TO_STR(local_game_stuck); RETURN_VALUE_TO_STR(substitute); RETURN_VALUE_TO_STR(manual); } ASSERT(false); return "invalid Penalty"; } #define RETURN_STING_TO_VALUE(value, str) if(toString(value) == str) return value GameData::TeamColor GameData::teamColorFromString(const std::string& str) { RETURN_STING_TO_VALUE(blue, str); RETURN_STING_TO_VALUE(red, str); RETURN_STING_TO_VALUE(yellow, str); RETURN_STING_TO_VALUE(black, str); return unknown_team_color; } GameData::GameState GameData::gameStateFromString(const std::string& str) { RETURN_STING_TO_VALUE(initial, str); RETURN_STING_TO_VALUE(ready, str); RETURN_STING_TO_VALUE(set, str); RETURN_STING_TO_VALUE(playing, str); RETURN_STING_TO_VALUE(finished, str); return unknown_game_state; } void GameData::parseFrom(const spl::RoboCupGameControlData& data, int teamNumber) { playersPerTeam = data.playersPerTeam; competitionType = (CompetitionType) data.competitionType; competitionPhase = (CompetitionPhase) data.competitionPhase; gamePhase = (GamePhase) data.gamePhase; gameState = (GameState) data.state; setPlay = (SetPlay) data.setPlay; firstHalf = data.firstHalf == 1; kickingTeam = data.kickingTeam; dropInTeam = data.dropInTeam; // ACHTUNG: casting to signed values - game time can be negative (!) dropInTime = (int16_t)data.dropInTime; secsRemaining = (int16_t)data.secsRemaining; secondaryTime = (int16_t)data.secondaryTime; // team info if(data.teams[0].teamNumber == teamNumber) { parseTeamInfo(ownTeam, data.teams[0]); parseTeamInfo(oppTeam, data.teams[1]); } else if(data.teams[1].teamNumber == teamNumber) { parseTeamInfo(ownTeam, data.teams[1]); parseTeamInfo(oppTeam, data.teams[0]); } else { ASSERT(false); } } void GameData::parseTeamInfo(TeamInfo& teamInfoDst, const spl::TeamInfo& teamInfoSrc) const { teamInfoDst.penaltyShot = teamInfoSrc.penaltyShot; teamInfoDst.score = teamInfoSrc.score; teamInfoDst.teamColor = (TeamColor)teamInfoSrc.teamColor; teamInfoDst.teamNumber = teamInfoSrc.teamNumber; teamInfoDst.players.resize(playersPerTeam); for(int i = 0; i < playersPerTeam; i++) { teamInfoDst.players[i].penalty = (Penalty)teamInfoSrc.players[i].penalty; // ACHTUNG: casting to signed values - time can be negative (!) teamInfoDst.players[i].secsTillUnpenalised = (int8_t)teamInfoSrc.players[i].secsTillUnpenalised; } } void GameData::print(ostream& stream) const { stream << "playersPerTeam = " << playersPerTeam << std::endl; stream << "competitionPhase = " << toString(competitionPhase) << std::endl; stream << "competitionType = " << toString(competitionType) << std::endl; stream << "gamePhase = " << toString(gamePhase) << std::endl; stream << "gameState = " << toString(gameState) << std::endl; stream << "setPlay = " << toString(setPlay) << std::endl; stream << "firstHalf = " << firstHalf << std::endl; stream << "kickingTeam = " << kickingTeam << std::endl; stream << "dropInTeam = " << dropInTeam << std::endl; stream << "dropInTime = " << dropInTime << std::endl; stream << "secsRemaining = " << secsRemaining << std::endl; stream << "secondaryTime = " << secondaryTime << std::endl; stream << std::endl; stream << "Own Team:" << std::endl; stream << " |- number = " << ownTeam.teamNumber << std::endl; stream << " |- color = " << toString(ownTeam.teamColor) << std::endl; stream << " |- score = " << ownTeam.score << std::endl; stream << " |- penaltyShot = " << ownTeam.penaltyShot << std::endl; stream << " |- players (penalty, time until unpenalize in s):" << std::endl; for(size_t i = 0; i < ownTeam.players.size(); ++i) { stream << " |- " << (i+1) << ": " << toString(ownTeam.players[i].penalty) << " - " << ownTeam.players[i].secsTillUnpenalised << std::endl; } stream << std::endl; stream << "Opp Team:" << std::endl; stream << " |- number = " << oppTeam.teamNumber << std::endl; stream << " |- color = " << toString(oppTeam.teamColor) << std::endl; stream << " |- score = " << oppTeam.score << std::endl; stream << " |- penaltyShot = " << oppTeam.penaltyShot << std::endl; stream << " |- players (penalty, time until unpenalize in s):" << std::endl; for(size_t i = 0; i < oppTeam.players.size(); ++i) { stream << " |- " << (i+1) << ": " << toString(oppTeam.players[i].penalty) << " - " << oppTeam.players[i].secsTillUnpenalised << std::endl; } } std::string GameReturnData::toString(Message value) { switch (value) { RETURN_VALUE_TO_STR(manual_penalise); RETURN_VALUE_TO_STR(manual_unpenalise); RETURN_VALUE_TO_STR(alive); } ASSERT(false); return "invalide Message"; } <commit_msg>bugfix: added all team colors to conversion function<commit_after>/** * @file GameInfo.cpp * * @author <a href="mailto:[email protected]">Mellmann, Heinrich</a> * @breief the game information in RoboCup */ #include <iostream> #include "GameData.h" using namespace naoth; using namespace std; GameData::GameData() : valid(false), playersPerTeam(0), competitionPhase(roundrobin), competitionType(competition_normal), gamePhase(normal), gameState(unknown_game_state), setPlay(set_none), firstHalf(true), kickingTeam(0), dropInTeam(0), dropInTime(0), secsRemaining(0), secondaryTime(0), // HACK: for more info see declaration newPlayerNumber(0) { } #define RETURN_VALUE_TO_STR(v) case v: return #v std::string GameData::toString(TeamColor value) { switch (value) { RETURN_VALUE_TO_STR(blue); RETURN_VALUE_TO_STR(red); RETURN_VALUE_TO_STR(yellow); RETURN_VALUE_TO_STR(black); RETURN_VALUE_TO_STR(white); RETURN_VALUE_TO_STR(green); RETURN_VALUE_TO_STR(orange); RETURN_VALUE_TO_STR(purple); RETURN_VALUE_TO_STR(brown); RETURN_VALUE_TO_STR(gray); RETURN_VALUE_TO_STR(unknown_team_color); } ASSERT(false); return "invalid TeamColor"; } std::string GameData::toString(CompetitionPhase value) { switch (value) { RETURN_VALUE_TO_STR(roundrobin); RETURN_VALUE_TO_STR(playoff); } ASSERT(false); return "invalid CompetitionPhase"; } std::string GameData::toString(CompetitionType value) { switch (value) { RETURN_VALUE_TO_STR(competition_normal); RETURN_VALUE_TO_STR(competition_mixed); RETURN_VALUE_TO_STR(competition_penalty); } ASSERT(false); return "invalid CompetitionType"; } std::string GameData::toString(GamePhase value) { switch (value) { RETURN_VALUE_TO_STR(normal); RETURN_VALUE_TO_STR(penaltyshoot); RETURN_VALUE_TO_STR(overtime); RETURN_VALUE_TO_STR(timeout); } ASSERT(false); return "invalid SecondaryGameState"; } std::string GameData::toString(GameState value) { switch (value) { RETURN_VALUE_TO_STR(initial); RETURN_VALUE_TO_STR(ready); RETURN_VALUE_TO_STR(set); RETURN_VALUE_TO_STR(playing); RETURN_VALUE_TO_STR(finished); RETURN_VALUE_TO_STR(unknown_game_state); } ASSERT(false); return "invalid GameState"; } std::string GameData::toString(SetPlay value) { switch (value) { RETURN_VALUE_TO_STR(set_none); RETURN_VALUE_TO_STR(goal_free_kick); RETURN_VALUE_TO_STR(pushing_free_kick); } ASSERT(false); return "invalid SetPlay"; } std::string GameData::toString(Penalty value) { switch (value) { RETURN_VALUE_TO_STR(penalty_none); RETURN_VALUE_TO_STR(illegal_ball_contact); RETURN_VALUE_TO_STR(player_pushing); RETURN_VALUE_TO_STR(illegal_motion_in_set); RETURN_VALUE_TO_STR(inactive_player); RETURN_VALUE_TO_STR(illegal_defender); RETURN_VALUE_TO_STR(leaving_the_field); RETURN_VALUE_TO_STR(kick_off_goal); RETURN_VALUE_TO_STR(request_for_pickup); RETURN_VALUE_TO_STR(local_game_stuck); RETURN_VALUE_TO_STR(substitute); RETURN_VALUE_TO_STR(manual); } ASSERT(false); return "invalid Penalty"; } #define RETURN_STING_TO_VALUE(value, str) if(toString(value) == str) return value GameData::TeamColor GameData::teamColorFromString(const std::string& str) { RETURN_STING_TO_VALUE(blue, str); RETURN_STING_TO_VALUE(red, str); RETURN_STING_TO_VALUE(yellow, str); RETURN_STING_TO_VALUE(black, str); RETURN_STING_TO_VALUE(white, str); RETURN_STING_TO_VALUE(green, str); RETURN_STING_TO_VALUE(orange, str); RETURN_STING_TO_VALUE(purple, str); RETURN_STING_TO_VALUE(brown, str); RETURN_STING_TO_VALUE(gray, str); return unknown_team_color; } GameData::GameState GameData::gameStateFromString(const std::string& str) { RETURN_STING_TO_VALUE(initial, str); RETURN_STING_TO_VALUE(ready, str); RETURN_STING_TO_VALUE(set, str); RETURN_STING_TO_VALUE(playing, str); RETURN_STING_TO_VALUE(finished, str); return unknown_game_state; } void GameData::parseFrom(const spl::RoboCupGameControlData& data, int teamNumber) { playersPerTeam = data.playersPerTeam; competitionType = (CompetitionType) data.competitionType; competitionPhase = (CompetitionPhase) data.competitionPhase; gamePhase = (GamePhase) data.gamePhase; gameState = (GameState) data.state; setPlay = (SetPlay) data.setPlay; firstHalf = data.firstHalf == 1; kickingTeam = data.kickingTeam; dropInTeam = data.dropInTeam; // ACHTUNG: casting to signed values - game time can be negative (!) dropInTime = (int16_t)data.dropInTime; secsRemaining = (int16_t)data.secsRemaining; secondaryTime = (int16_t)data.secondaryTime; // team info if(data.teams[0].teamNumber == teamNumber) { parseTeamInfo(ownTeam, data.teams[0]); parseTeamInfo(oppTeam, data.teams[1]); } else if(data.teams[1].teamNumber == teamNumber) { parseTeamInfo(ownTeam, data.teams[1]); parseTeamInfo(oppTeam, data.teams[0]); } else { ASSERT(false); } } void GameData::parseTeamInfo(TeamInfo& teamInfoDst, const spl::TeamInfo& teamInfoSrc) const { teamInfoDst.penaltyShot = teamInfoSrc.penaltyShot; teamInfoDst.score = teamInfoSrc.score; teamInfoDst.teamColor = (TeamColor)teamInfoSrc.teamColor; teamInfoDst.teamNumber = teamInfoSrc.teamNumber; teamInfoDst.players.resize(playersPerTeam); for(int i = 0; i < playersPerTeam; i++) { teamInfoDst.players[i].penalty = (Penalty)teamInfoSrc.players[i].penalty; // ACHTUNG: casting to signed values - time can be negative (!) teamInfoDst.players[i].secsTillUnpenalised = (int8_t)teamInfoSrc.players[i].secsTillUnpenalised; } } void GameData::print(ostream& stream) const { stream << "playersPerTeam = " << playersPerTeam << std::endl; stream << "competitionPhase = " << toString(competitionPhase) << std::endl; stream << "competitionType = " << toString(competitionType) << std::endl; stream << "gamePhase = " << toString(gamePhase) << std::endl; stream << "gameState = " << toString(gameState) << std::endl; stream << "setPlay = " << toString(setPlay) << std::endl; stream << "firstHalf = " << firstHalf << std::endl; stream << "kickingTeam = " << kickingTeam << std::endl; stream << "dropInTeam = " << dropInTeam << std::endl; stream << "dropInTime = " << dropInTime << std::endl; stream << "secsRemaining = " << secsRemaining << std::endl; stream << "secondaryTime = " << secondaryTime << std::endl; stream << std::endl; stream << "Own Team:" << std::endl; stream << " |- number = " << ownTeam.teamNumber << std::endl; stream << " |- color = " << toString(ownTeam.teamColor) << std::endl; stream << " |- score = " << ownTeam.score << std::endl; stream << " |- penaltyShot = " << ownTeam.penaltyShot << std::endl; stream << " |- players (penalty, time until unpenalize in s):" << std::endl; for(size_t i = 0; i < ownTeam.players.size(); ++i) { stream << " |- " << (i+1) << ": " << toString(ownTeam.players[i].penalty) << " - " << ownTeam.players[i].secsTillUnpenalised << std::endl; } stream << std::endl; stream << "Opp Team:" << std::endl; stream << " |- number = " << oppTeam.teamNumber << std::endl; stream << " |- color = " << toString(oppTeam.teamColor) << std::endl; stream << " |- score = " << oppTeam.score << std::endl; stream << " |- penaltyShot = " << oppTeam.penaltyShot << std::endl; stream << " |- players (penalty, time until unpenalize in s):" << std::endl; for(size_t i = 0; i < oppTeam.players.size(); ++i) { stream << " |- " << (i+1) << ": " << toString(oppTeam.players[i].penalty) << " - " << oppTeam.players[i].secsTillUnpenalised << std::endl; } } std::string GameReturnData::toString(Message value) { switch (value) { RETURN_VALUE_TO_STR(manual_penalise); RETURN_VALUE_TO_STR(manual_unpenalise); RETURN_VALUE_TO_STR(alive); } ASSERT(false); return "invalide Message"; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: salvd.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2004-11-26 20:45:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALINST_HXX #include <salinst.hxx> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #ifndef _SV_SALVD_H #include <salvd.h> #endif // -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= SalVirtualDevice* X11SalInstance::CreateVirtualDevice( SalGraphics* pGraphics, long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData ) { X11SalVirtualDevice *pVDev = new X11SalVirtualDevice(); if( !nBitCount && pGraphics ) nBitCount = pGraphics->GetBitCount(); if( !pVDev->Init( GetSalData()->GetDisplay(), nDX, nDY, nBitCount ) ) { delete pVDev; return NULL; } pVDev->InitGraphics( pVDev ); return pVDev; } void X11SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice ) { delete pDevice; } // -=-= SalGraphicsData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void X11SalGraphics::Init( X11SalVirtualDevice *pDevice ) { SalDisplay *pDisplay = pDevice->GetDisplay(); int nVisualDepth = pDisplay->GetColormap().GetVisual()->GetDepth(); int nDeviceDepth = pDevice->GetDepth(); if( nDeviceDepth == nVisualDepth ) m_pColormap = &pDisplay->GetColormap(); else if( nDeviceDepth == 1 ) m_pDeleteColormap = m_pColormap = new SalColormap(); hDrawable_ = pDevice->GetDrawable(); m_pVDev = pDevice; m_pFrame = NULL; bWindow_ = pDisplay->IsDisplay(); bVirDev_ = TRUE; nPenPixel_ = GetPixel( nPenColor_ ); nTextPixel_ = GetPixel( nTextColor_ ); nBrushPixel_ = GetPixel( nBrushColor_ ); } // -=-= SalVirDevData / SalVirtualDevice -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= BOOL X11SalVirtualDevice::Init( SalDisplay *pDisplay, long nDX, long nDY, USHORT nBitCount ) { pDisplay_ = pDisplay; pGraphics_ = new X11SalGraphics(); pGraphics_->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL() nDX_ = nDX; nDY_ = nDY; nDepth_ = nBitCount; hDrawable_ = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), nDX_, nDY_, GetDepth() ); pGraphics_->Init( this ); return hDrawable_ != None ? TRUE : FALSE; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X11SalVirtualDevice::X11SalVirtualDevice() { pDisplay_ = (SalDisplay*)ILLEGAL_POINTER; pGraphics_ = NULL; hDrawable_ = None; nDX_ = 0; nDY_ = 0; nDepth_ = 0; bGraphics_ = FALSE; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X11SalVirtualDevice::~X11SalVirtualDevice() { if( pGraphics_ ) delete pGraphics_; if( GetDrawable() ) XFreePixmap( GetXDisplay(), GetDrawable() ); } SalGraphics* X11SalVirtualDevice::GetGraphics() { if( bGraphics_ ) return NULL; if( pGraphics_ ) bGraphics_ = TRUE; return pGraphics_; } void X11SalVirtualDevice::ReleaseGraphics( SalGraphics* ) { bGraphics_ = FALSE; } BOOL X11SalVirtualDevice::SetSize( long nDX, long nDY ) { if( !nDX ) nDX = 1; if( !nDY ) nDY = 1; Pixmap h = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), nDX, nDY, nDepth_ ); if( !h ) { if( !GetDrawable() ) { hDrawable_ = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), 1, 1, nDepth_ ); nDX_ = 1; nDY_ = 1; } return FALSE; } if( GetDrawable() ) XFreePixmap( GetXDisplay(), GetDrawable() ); hDrawable_ = h; nDX_ = nDX; nDY_ = nDY; if( pGraphics_ ) InitGraphics( this ); return TRUE; } <commit_msg>INTEGRATION: CWS ooo19126 (1.9.290); FILE MERGED 2005/09/05 14:45:45 rt 1.9.290.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salvd.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-09-09 13:08:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALINST_HXX #include <salinst.hxx> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #ifndef _SV_SALVD_H #include <salvd.h> #endif // -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= SalVirtualDevice* X11SalInstance::CreateVirtualDevice( SalGraphics* pGraphics, long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData ) { X11SalVirtualDevice *pVDev = new X11SalVirtualDevice(); if( !nBitCount && pGraphics ) nBitCount = pGraphics->GetBitCount(); if( !pVDev->Init( GetSalData()->GetDisplay(), nDX, nDY, nBitCount ) ) { delete pVDev; return NULL; } pVDev->InitGraphics( pVDev ); return pVDev; } void X11SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice ) { delete pDevice; } // -=-= SalGraphicsData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void X11SalGraphics::Init( X11SalVirtualDevice *pDevice ) { SalDisplay *pDisplay = pDevice->GetDisplay(); int nVisualDepth = pDisplay->GetColormap().GetVisual()->GetDepth(); int nDeviceDepth = pDevice->GetDepth(); if( nDeviceDepth == nVisualDepth ) m_pColormap = &pDisplay->GetColormap(); else if( nDeviceDepth == 1 ) m_pDeleteColormap = m_pColormap = new SalColormap(); hDrawable_ = pDevice->GetDrawable(); m_pVDev = pDevice; m_pFrame = NULL; bWindow_ = pDisplay->IsDisplay(); bVirDev_ = TRUE; nPenPixel_ = GetPixel( nPenColor_ ); nTextPixel_ = GetPixel( nTextColor_ ); nBrushPixel_ = GetPixel( nBrushColor_ ); } // -=-= SalVirDevData / SalVirtualDevice -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= BOOL X11SalVirtualDevice::Init( SalDisplay *pDisplay, long nDX, long nDY, USHORT nBitCount ) { pDisplay_ = pDisplay; pGraphics_ = new X11SalGraphics(); pGraphics_->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL() nDX_ = nDX; nDY_ = nDY; nDepth_ = nBitCount; hDrawable_ = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), nDX_, nDY_, GetDepth() ); pGraphics_->Init( this ); return hDrawable_ != None ? TRUE : FALSE; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X11SalVirtualDevice::X11SalVirtualDevice() { pDisplay_ = (SalDisplay*)ILLEGAL_POINTER; pGraphics_ = NULL; hDrawable_ = None; nDX_ = 0; nDY_ = 0; nDepth_ = 0; bGraphics_ = FALSE; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X11SalVirtualDevice::~X11SalVirtualDevice() { if( pGraphics_ ) delete pGraphics_; if( GetDrawable() ) XFreePixmap( GetXDisplay(), GetDrawable() ); } SalGraphics* X11SalVirtualDevice::GetGraphics() { if( bGraphics_ ) return NULL; if( pGraphics_ ) bGraphics_ = TRUE; return pGraphics_; } void X11SalVirtualDevice::ReleaseGraphics( SalGraphics* ) { bGraphics_ = FALSE; } BOOL X11SalVirtualDevice::SetSize( long nDX, long nDY ) { if( !nDX ) nDX = 1; if( !nDY ) nDY = 1; Pixmap h = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), nDX, nDY, nDepth_ ); if( !h ) { if( !GetDrawable() ) { hDrawable_ = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), 1, 1, nDepth_ ); nDX_ = 1; nDY_ = 1; } return FALSE; } if( GetDrawable() ) XFreePixmap( GetXDisplay(), GetDrawable() ); hDrawable_ = h; nDX_ = nDX; nDY_ = nDY; if( pGraphics_ ) InitGraphics( this ); return TRUE; } <|endoftext|>
<commit_before>/* type.cpp -*- C++ -*- Rémi Attab ([email protected]), 24 Mar 2014 FreeBSD-style copyright and disclaimer apply Type implementation. */ #include "reflect.h" #include <algorithm> #include <sstream> namespace reflect { /******************************************************************************/ /* TYPE */ /******************************************************************************/ void Type:: addTrait(std::string trait) { traits_.emplace(std::move(trait)); } bool Type:: is(const std::string& trait) const { return traits_.count(trait); } std::vector<std::string> Type:: traits() const { return { traits_.begin(), traits_.end() }; } void Type:: addFunctionTrait(const std::string& fn, std::string trait) { fnTraits_[fn].emplace(std::move(trait)); } bool Type:: functionIs(const std::string& fn, const std::string& trait) const { auto it = fnTraits_.find(fn); if (it != fnTraits_.end()) return it->second.count(trait); return parent_ ? parent_->functionIs(fn, trait) : false; } bool Type:: fieldIs(const std::string& field, const std::string& trait) const { return functionIs(field, trait); } std::vector<std::string> Type:: functionTraits(const std::string& fn) const { auto it = fnTraits_.find(fn); if (it != fnTraits_.end()) return { it->second.begin(), it->second.end() }; return parent_ ? parent_->functionTraits(fn) : std::vector<std::string>(); } std::vector<std::string> Type:: fieldTraits(const std::string& field) const { return functionTraits(field); } bool Type:: isChildOf(const Type* other) const { return this == other || (parent_ && parent_->isChildOf(other)); } bool Type:: isParentOf(const Type* other) const { return other->isChildOf(this); } bool Type:: hasConverter(const Type* other) const { return hasField("operator " + other->id() + "()"); } const Function& Type:: converter(const Type* other) const { auto& fns = field("operator " + other->id() + "()"); if (fns.size() > 1) { reflectError("<%s> has too many converters for <%s>", id_, other->id()); } return fns[0]; } bool Type:: isCopiable() const { if (!hasField(id_)) return false; auto& fns = field(id_); return fns.test( Argument(this, RefType::Copy, false), { Argument(this, RefType::Copy, false) }); } bool Type:: isMovable() const { if (!hasField(id_)) return false; auto& fns = field(id_); return fns.test( Argument(this, RefType::Copy, false), { Argument(this, RefType::RValue, false) }); } void Type:: functions(std::vector<std::string>& result) const { result.reserve(result.size() + fns_.size()); for (const auto& f : fns_) result.push_back(f.first); if (parent_) parent_->functions(result); } std::vector<std::string> Type:: functions() const { std::vector<std::string> result; functions(result); std::sort(result.begin(), result.end()); result.erase(std::unique(result.begin(), result.end()), result.end()); return result; } bool Type:: hasFunction(const std::string& function) const { if (fns_.find(function) != fns_.end()) return true; return parent_ ? parent_->hasFunction(function) : false; } const Overloads& Type:: function(const std::string& function) const { auto it = fns_.find(function); if (it != fns_.end()) return it->second; if (!parent_) reflectError("<%s> doesn't have a function <%s>", id_, function); return parent_->function(function); } void Type:: fields(std::vector<std::string>& result) const { result.reserve(result.size() + fns_.size()); for (const auto& f : fns_) { if (!f.second.isField()) continue; result.push_back(f.first); } if (parent_) parent_->fields(result); } std::vector<std::string> Type:: fields() const { std::vector<std::string> result; fields(result); std::sort(result.begin(), result.end()); result.erase(std::unique(result.begin(), result.end()), result.end()); return result; } bool Type:: hasField(const std::string& field) const { auto it = fns_.find(field); if (it != fns_.end() && it->second.isField()) return true; return parent_ ? parent_->hasField(field) : false; } const Overloads& Type:: field(const std::string& field) const { auto it = fns_.find(field); if (it != fns_.end() && it->second.isField()) return it->second; if (!parent_) reflectError("<%s> doesn't have a field <%s>", id_, field); return parent_->field(field); } const Type* Type:: fieldType(const std::string& field) const { auto& f = this->field(field); return f.fieldType(); } std::string Type:: print(size_t indent) const { enum { PadInc = 4 }; std::stringstream ss; std::string pad0(indent, ' '); indent += PadInc; std::string pad1(indent, ' '); ss << pad0 << "struct " << id_ << "\n"; ss << pad0 << "{\n"; if (parent_) ss << parent_->print(indent) << "\n"; for (const auto& field : fns_) { ss << pad1 << field.first << ":\n"; ss << field.second.print(indent + PadInc); } ss << pad0 << "}\n"; return ss.str(); } } // reflect <commit_msg>Traits are now printed in Type.<commit_after>/* type.cpp -*- C++ -*- Rémi Attab ([email protected]), 24 Mar 2014 FreeBSD-style copyright and disclaimer apply Type implementation. */ #include "reflect.h" #include <algorithm> #include <sstream> namespace reflect { /******************************************************************************/ /* TYPE */ /******************************************************************************/ void Type:: addTrait(std::string trait) { traits_.emplace(std::move(trait)); } bool Type:: is(const std::string& trait) const { return traits_.count(trait); } std::vector<std::string> Type:: traits() const { return { traits_.begin(), traits_.end() }; } void Type:: addFunctionTrait(const std::string& fn, std::string trait) { fnTraits_[fn].emplace(std::move(trait)); } bool Type:: functionIs(const std::string& fn, const std::string& trait) const { auto it = fnTraits_.find(fn); if (it != fnTraits_.end()) return it->second.count(trait); return parent_ ? parent_->functionIs(fn, trait) : false; } bool Type:: fieldIs(const std::string& field, const std::string& trait) const { return functionIs(field, trait); } std::vector<std::string> Type:: functionTraits(const std::string& fn) const { auto it = fnTraits_.find(fn); if (it != fnTraits_.end()) return { it->second.begin(), it->second.end() }; return parent_ ? parent_->functionTraits(fn) : std::vector<std::string>(); } std::vector<std::string> Type:: fieldTraits(const std::string& field) const { return functionTraits(field); } bool Type:: isChildOf(const Type* other) const { return this == other || (parent_ && parent_->isChildOf(other)); } bool Type:: isParentOf(const Type* other) const { return other->isChildOf(this); } bool Type:: hasConverter(const Type* other) const { return hasField("operator " + other->id() + "()"); } const Function& Type:: converter(const Type* other) const { auto& fns = field("operator " + other->id() + "()"); if (fns.size() > 1) { reflectError("<%s> has too many converters for <%s>", id_, other->id()); } return fns[0]; } bool Type:: isCopiable() const { if (!hasField(id_)) return false; auto& fns = field(id_); return fns.test( Argument(this, RefType::Copy, false), { Argument(this, RefType::Copy, false) }); } bool Type:: isMovable() const { if (!hasField(id_)) return false; auto& fns = field(id_); return fns.test( Argument(this, RefType::Copy, false), { Argument(this, RefType::RValue, false) }); } void Type:: functions(std::vector<std::string>& result) const { result.reserve(result.size() + fns_.size()); for (const auto& f : fns_) result.push_back(f.first); if (parent_) parent_->functions(result); } std::vector<std::string> Type:: functions() const { std::vector<std::string> result; functions(result); std::sort(result.begin(), result.end()); result.erase(std::unique(result.begin(), result.end()), result.end()); return result; } bool Type:: hasFunction(const std::string& function) const { if (fns_.find(function) != fns_.end()) return true; return parent_ ? parent_->hasFunction(function) : false; } const Overloads& Type:: function(const std::string& function) const { auto it = fns_.find(function); if (it != fns_.end()) return it->second; if (!parent_) reflectError("<%s> doesn't have a function <%s>", id_, function); return parent_->function(function); } void Type:: fields(std::vector<std::string>& result) const { result.reserve(result.size() + fns_.size()); for (const auto& f : fns_) { if (!f.second.isField()) continue; result.push_back(f.first); } if (parent_) parent_->fields(result); } std::vector<std::string> Type:: fields() const { std::vector<std::string> result; fields(result); std::sort(result.begin(), result.end()); result.erase(std::unique(result.begin(), result.end()), result.end()); return result; } bool Type:: hasField(const std::string& field) const { auto it = fns_.find(field); if (it != fns_.end() && it->second.isField()) return true; return parent_ ? parent_->hasField(field) : false; } const Overloads& Type:: field(const std::string& field) const { auto it = fns_.find(field); if (it != fns_.end() && it->second.isField()) return it->second; if (!parent_) reflectError("<%s> doesn't have a field <%s>", id_, field); return parent_->field(field); } const Type* Type:: fieldType(const std::string& field) const { auto& f = this->field(field); return f.fieldType(); } namespace { void printTraits( std::stringstream& ss, const std::unordered_set<std::string>& traits) { ss<< "traits: [ "; for (auto& trait : traits) ss << trait << " "; ss << "]\n"; } } // namespace anonymous std::string Type:: print(size_t indent) const { enum { PadInc = 4 }; std::stringstream ss; std::string pad0(indent, ' '); indent += PadInc; std::string pad1(indent, ' '); std::string pad2(indent + PadInc, ' '); ss << pad0 << "struct " << id_ << "\n"; ss << pad0 << "{\n"; if (parent_) ss << parent_->print(indent) << "\n"; if (!traits_.empty()) { ss << pad1; printTraits(ss, traits_); } for (auto& field : fns_) { ss << pad1 << field.first << ":\n"; auto it = fnTraits_.find(field.first); if (it != fnTraits_.end()) { ss << pad2; printTraits(ss, it->second); } ss << field.second.print(indent + PadInc); } ss << pad0 << "}\n"; return ss.str(); } } // reflect <|endoftext|>
<commit_before>// $Id$ // // Task to filter Esd tracks and propagate to Emcal surface. // // Author: C.Loizides #include "AliEmcalEsdTrackFilterTask.h" #include <TClonesArray.h> #include <TRandom3.h> #include <TGeoGlobalMagField.h> #include <AliAnalysisManager.h> #include <AliEMCALRecoUtils.h> #include <AliESDEvent.h> #include <AliESDtrackCuts.h> #include <AliMagF.h> #include <AliTrackerBase.h> ClassImp(AliEmcalEsdTrackFilterTask) //________________________________________________________________________ AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask() : AliAnalysisTaskSE("AliEmcalEsdTrackFilterTask"), fEsdTrackCuts(0), fDoSpdVtxCon(0), fHybridTrackCuts(0), fTracksName(), fIncludeNoITS(kTRUE), fDoPropagation(kFALSE), fDist(440), fTrackEfficiency(1), fEsdEv(0), fTracks(0) { // Constructor. } //________________________________________________________________________ AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask(const char *name) : AliAnalysisTaskSE(name), fEsdTrackCuts(0), fDoSpdVtxCon(0), fHybridTrackCuts(0), fTracksName("EsdTracksOut"), fIncludeNoITS(kTRUE), fDoPropagation(kFALSE), fDist(440), fTrackEfficiency(1), fEsdEv(0), fTracks(0) { // Constructor. if (!name) return; SetName(name); fBranchNames = "ESD:AliESDHeader.,AliESDRun.,SPDVertex.,Tracks"; } //________________________________________________________________________ AliEmcalEsdTrackFilterTask::~AliEmcalEsdTrackFilterTask() { //Destructor delete fEsdTrackCuts; } //________________________________________________________________________ void AliEmcalEsdTrackFilterTask::UserCreateOutputObjects() { // Create histograms. fTracks = new TClonesArray("AliESDtrack"); fTracks->SetName(fTracksName); if (fDoSpdVtxCon) { if (!fEsdTrackCuts) { AliInfo("No track cuts given, creating default (standard only TPC) cuts"); fEsdTrackCuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); fEsdTrackCuts->SetPtRange(0.15,1e3); } } else { AliWarning("No track cuts given, but maybe this is indeed intended?"); } } //________________________________________________________________________ void AliEmcalEsdTrackFilterTask::UserExec(Option_t *) { // Main loop, called for each event. fEsdEv = dynamic_cast<AliESDEvent*>(InputEvent()); if (!fEsdEv) { AliError("Task works only on ESD events, returning"); return; } AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); if (!am) { AliError("Manager zero, returning"); return; } // add tracks to event if not yet there fTracks->Delete(); if (!(InputEvent()->FindListObject(fTracksName))) InputEvent()->AddObject(fTracks); if (!fHybridTrackCuts) { // constrain TPC tracks to SPD vertex if fDoSpdVtxCon==kTRUE am->LoadBranch("AliESDRun."); am->LoadBranch("AliESDHeader."); am->LoadBranch("Tracks"); if (fDoSpdVtxCon) { if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map fEsdEv->InitMagneticField(); } am->LoadBranch("SPDVertex."); const AliESDVertex *vtxSPD = fEsdEv->GetPrimaryVertexSPD(); if (!vtxSPD) { AliError("No SPD vertex, returning"); return; } Int_t ntr = fEsdEv->GetNumberOfTracks(); for (Int_t i=0, ntrnew=0; i<ntr; ++i) { AliESDtrack *etrack = fEsdEv->GetTrack(i); if (!etrack) continue; if (fTrackEfficiency < 1) { Double_t r = gRandom->Rndm(); if (fTrackEfficiency < r) continue; } if (!fEsdTrackCuts->AcceptTrack(etrack)) continue; AliESDtrack *ntrack = AliESDtrackCuts::GetTPCOnlyTrack(fEsdEv,etrack->GetID()); if (!ntrack) continue; if (ntrack->Pt()<=0) { delete ntrack; continue; } Double_t bfield[3] = {0,0,0}; ntrack->GetBxByBz(bfield); AliExternalTrackParam exParam; Bool_t relate = ntrack->RelateToVertexBxByBz(vtxSPD,bfield,kVeryBig,&exParam); if (!relate) { delete ntrack; continue; } // set the constraint parameters to the track ntrack->Set(exParam.GetX(),exParam.GetAlpha(),exParam.GetParameter(),exParam.GetCovariance()); if (ntrack->Pt()<=0) { delete ntrack; continue; } if (fDoPropagation) AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(ntrack,fDist); new ((*fTracks)[ntrnew++]) AliESDtrack(*ntrack); delete ntrack; } } else { /* no spd vtx constraint */ Int_t ntr = fEsdEv->GetNumberOfTracks(); for (Int_t i=0, ntrnew=0; i<ntr; ++i) { AliESDtrack *etrack = fEsdEv->GetTrack(i); if (!etrack) continue; if (fTrackEfficiency < 1) { Double_t r = gRandom->Rndm(); if (fTrackEfficiency < r) continue; } if ((fEsdTrackCuts!=0) && !fEsdTrackCuts->AcceptTrack(etrack)) continue; AliESDtrack *ntrack = new ((*fTracks)[ntrnew++]) AliESDtrack(*etrack); if (fDoPropagation) AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(ntrack,fDist); } } } else { // use hybrid track cuts am->LoadBranch("Tracks"); Int_t ntr = fEsdEv->GetNumberOfTracks(); for (Int_t i=0, ntrnew=0; i<ntr; ++i) { AliESDtrack *etrack = fEsdEv->GetTrack(i); if (!etrack) continue; if (fTrackEfficiency < 1) { Double_t r = gRandom->Rndm(); if (fTrackEfficiency < r) continue; } if (fEsdTrackCuts->AcceptTrack(etrack)) { AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack); if (fDoPropagation) AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist); newTrack->SetBit(BIT(22),0); newTrack->SetBit(BIT(23),0); ++ntrnew; } else if (fHybridTrackCuts->AcceptTrack(etrack)) { if (!etrack->GetConstrainedParam()) continue; UInt_t status = etrack->GetStatus(); if (!fIncludeNoITS && ((status&AliESDtrack::kITSrefit)==0)) continue; AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack); if (fDoPropagation) AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist); const AliExternalTrackParam* constrainParam = etrack->GetConstrainedParam(); newTrack->Set(constrainParam->GetX(), constrainParam->GetAlpha(), constrainParam->GetParameter(), constrainParam->GetCovariance()); if ((status&AliESDtrack::kITSrefit)==0) { newTrack->SetBit(BIT(22),0); //type 2 newTrack->SetBit(BIT(23),1); } else { newTrack->SetBit(BIT(22),1); //type 1 newTrack->SetBit(BIT(23),0); } ++ntrnew; } } } } <commit_msg>random track rejection (tracking efficiency studies) only after all cuts have been applied<commit_after>// $Id$ // // Task to filter Esd tracks and propagate to Emcal surface. // // Author: C.Loizides #include "AliEmcalEsdTrackFilterTask.h" #include <TClonesArray.h> #include <TRandom3.h> #include <TGeoGlobalMagField.h> #include <AliAnalysisManager.h> #include <AliEMCALRecoUtils.h> #include <AliESDEvent.h> #include <AliESDtrackCuts.h> #include <AliMagF.h> #include <AliTrackerBase.h> ClassImp(AliEmcalEsdTrackFilterTask) //________________________________________________________________________ AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask() : AliAnalysisTaskSE("AliEmcalEsdTrackFilterTask"), fEsdTrackCuts(0), fDoSpdVtxCon(0), fHybridTrackCuts(0), fTracksName(), fIncludeNoITS(kTRUE), fDoPropagation(kFALSE), fDist(440), fTrackEfficiency(1), fEsdEv(0), fTracks(0) { // Constructor. } //________________________________________________________________________ AliEmcalEsdTrackFilterTask::AliEmcalEsdTrackFilterTask(const char *name) : AliAnalysisTaskSE(name), fEsdTrackCuts(0), fDoSpdVtxCon(0), fHybridTrackCuts(0), fTracksName("EsdTracksOut"), fIncludeNoITS(kTRUE), fDoPropagation(kFALSE), fDist(440), fTrackEfficiency(1), fEsdEv(0), fTracks(0) { // Constructor. if (!name) return; SetName(name); fBranchNames = "ESD:AliESDHeader.,AliESDRun.,SPDVertex.,Tracks"; } //________________________________________________________________________ AliEmcalEsdTrackFilterTask::~AliEmcalEsdTrackFilterTask() { //Destructor delete fEsdTrackCuts; } //________________________________________________________________________ void AliEmcalEsdTrackFilterTask::UserCreateOutputObjects() { // Create histograms. fTracks = new TClonesArray("AliESDtrack"); fTracks->SetName(fTracksName); if (fDoSpdVtxCon) { if (!fEsdTrackCuts) { AliInfo("No track cuts given, creating default (standard only TPC) cuts"); fEsdTrackCuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); fEsdTrackCuts->SetPtRange(0.15,1e3); } } else { AliWarning("No track cuts given, but maybe this is indeed intended?"); } } //________________________________________________________________________ void AliEmcalEsdTrackFilterTask::UserExec(Option_t *) { // Main loop, called for each event. fEsdEv = dynamic_cast<AliESDEvent*>(InputEvent()); if (!fEsdEv) { AliError("Task works only on ESD events, returning"); return; } AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); if (!am) { AliError("Manager zero, returning"); return; } // add tracks to event if not yet there fTracks->Delete(); if (!(InputEvent()->FindListObject(fTracksName))) InputEvent()->AddObject(fTracks); if (!fHybridTrackCuts) { // constrain TPC tracks to SPD vertex if fDoSpdVtxCon==kTRUE am->LoadBranch("AliESDRun."); am->LoadBranch("AliESDHeader."); am->LoadBranch("Tracks"); if (fDoSpdVtxCon) { if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map fEsdEv->InitMagneticField(); } am->LoadBranch("SPDVertex."); const AliESDVertex *vtxSPD = fEsdEv->GetPrimaryVertexSPD(); if (!vtxSPD) { AliError("No SPD vertex, returning"); return; } Int_t ntr = fEsdEv->GetNumberOfTracks(); for (Int_t i=0, ntrnew=0; i<ntr; ++i) { AliESDtrack *etrack = fEsdEv->GetTrack(i); if (!etrack) continue; if (!fEsdTrackCuts->AcceptTrack(etrack)) continue; AliESDtrack *ntrack = AliESDtrackCuts::GetTPCOnlyTrack(fEsdEv,etrack->GetID()); if (!ntrack) continue; if (ntrack->Pt()<=0) { delete ntrack; continue; } Double_t bfield[3] = {0,0,0}; ntrack->GetBxByBz(bfield); AliExternalTrackParam exParam; Bool_t relate = ntrack->RelateToVertexBxByBz(vtxSPD,bfield,kVeryBig,&exParam); if (!relate) { delete ntrack; continue; } // set the constraint parameters to the track ntrack->Set(exParam.GetX(),exParam.GetAlpha(),exParam.GetParameter(),exParam.GetCovariance()); if (ntrack->Pt()<=0) { delete ntrack; continue; } if (fTrackEfficiency < 1) { Double_t r = gRandom->Rndm(); if (fTrackEfficiency < r) continue; } if (fDoPropagation) AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(ntrack,fDist); new ((*fTracks)[ntrnew++]) AliESDtrack(*ntrack); delete ntrack; } } else { /* no spd vtx constraint */ Int_t ntr = fEsdEv->GetNumberOfTracks(); for (Int_t i=0, ntrnew=0; i<ntr; ++i) { AliESDtrack *etrack = fEsdEv->GetTrack(i); if (!etrack) continue; if ((fEsdTrackCuts!=0) && !fEsdTrackCuts->AcceptTrack(etrack)) continue; if (fTrackEfficiency < 1) { Double_t r = gRandom->Rndm(); if (fTrackEfficiency < r) continue; } AliESDtrack *ntrack = new ((*fTracks)[ntrnew++]) AliESDtrack(*etrack); if (fDoPropagation) AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(ntrack,fDist); } } } else { // use hybrid track cuts am->LoadBranch("Tracks"); Int_t ntr = fEsdEv->GetNumberOfTracks(); for (Int_t i=0, ntrnew=0; i<ntr; ++i) { AliESDtrack *etrack = fEsdEv->GetTrack(i); if (!etrack) continue; if (fEsdTrackCuts->AcceptTrack(etrack)) { AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack); if (fDoPropagation) AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist); newTrack->SetBit(BIT(22),0); newTrack->SetBit(BIT(23),0); ++ntrnew; } else if (fHybridTrackCuts->AcceptTrack(etrack)) { if (!etrack->GetConstrainedParam()) continue; UInt_t status = etrack->GetStatus(); if (!fIncludeNoITS && ((status&AliESDtrack::kITSrefit)==0)) continue; if (fTrackEfficiency < 1) { Double_t r = gRandom->Rndm(); if (fTrackEfficiency < r) continue; } AliESDtrack *newTrack = new ((*fTracks)[ntrnew]) AliESDtrack(*etrack); if (fDoPropagation) AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(newTrack,fDist); const AliExternalTrackParam* constrainParam = etrack->GetConstrainedParam(); newTrack->Set(constrainParam->GetX(), constrainParam->GetAlpha(), constrainParam->GetParameter(), constrainParam->GetCovariance()); if ((status&AliESDtrack::kITSrefit)==0) { newTrack->SetBit(BIT(22),0); //type 2 newTrack->SetBit(BIT(23),1); } else { newTrack->SetBit(BIT(22),1); //type 1 newTrack->SetBit(BIT(23),0); } ++ntrnew; } } } } <|endoftext|>
<commit_before>#include "type_name.h" int main() { const volatile char abc[1][2][3]{}; std::cout << type_name<decltype(abc)>() << std::endl; } <commit_msg>Remove main.C - missed with rename to main.cpp<commit_after><|endoftext|>
<commit_before>AliAnalysisTaskSE *AddTaskSigma0Run2(bool isRun1 = false, bool isMC = false, bool isHeavyIon = false, TString trigger = "kINT7", const char *cutVariation = "0") { TString suffix; suffix.Form("%s", cutVariation); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskSigma0Run2()", "No analysis manager found."); return 0x0; } // ================== GetInputEventHandler ============================= AliVEventHandler *inputHandler = mgr->GetInputEventHandler(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); //========= Set Cutnumber for V0Reader ================================ TString cutnumberPhoton; cutnumberPhoton = "00200008400000002280920000"; TString cutnumberEvent = "00000000"; if (suffix == "0") { // Borissov cuts cutnumberPhoton = "00200008400020002282020000"; cutnumberEvent = "00000003"; } TString periodNameV0Reader = ""; Bool_t enableV0findingEffi = kFALSE; Bool_t fillHistos = kTRUE; Bool_t runLightOutput = kFALSE; if (suffix != "0" && suffix != "999") { runLightOutput = kTRUE; fillHistos = kFALSE; } //========= Add V0 Reader to ANALYSIS manager if not yet existent ===== TString V0ReaderName = Form("V0ReaderV1_%s_%s", cutnumberEvent.Data(), cutnumberPhoton.Data()); AliConvEventCuts *fEventCuts = NULL; if (!(AliV0ReaderV1 *)mgr->GetTask(V0ReaderName.Data())) { AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data()); if (periodNameV0Reader.CompareTo("") != 0) fV0ReaderV1->SetPeriodName(periodNameV0Reader); fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE); fV0ReaderV1->SetCreateAODs(kFALSE); // AOD Output fV0ReaderV1->SetUseAODConversionPhoton(kTRUE); fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi); if (!mgr) { Error("AddTask_V0ReaderV1", "No analysis manager found."); return NULL; } if (cutnumberEvent != "") { fEventCuts = new AliConvEventCuts(cutnumberEvent.Data(), cutnumberEvent.Data()); fEventCuts->SetPreSelectionCutFlag(kTRUE); fEventCuts->SetV0ReaderName(V0ReaderName); fEventCuts->SetLightOutput(runLightOutput); fEventCuts->SetFillCutHistograms("", fillHistos); if (periodNameV0Reader.CompareTo("") != 0) fEventCuts->SetPeriodEnum(periodNameV0Reader); fV0ReaderV1->SetEventCuts(fEventCuts); } // Set AnalysisCut Number AliConversionPhotonCuts *fCuts = NULL; if (cutnumberPhoton != "") { fCuts = new AliConversionPhotonCuts(cutnumberPhoton.Data(), cutnumberPhoton.Data()); fCuts->SetPreSelectionCutFlag(kTRUE); fCuts->SetIsHeavyIon(isHeavyIon); fCuts->SetV0ReaderName(V0ReaderName); fCuts->SetLightOutput(runLightOutput); fCuts->SetFillCutHistograms("", fillHistos); if (fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())) { fV0ReaderV1->SetConversionCuts(fCuts); } } fV0ReaderV1->Init(); AliLog::SetGlobalLogLevel(AliLog::kFatal); // connect input V0Reader mgr->AddTask(fV0ReaderV1); mgr->ConnectInput(fV0ReaderV1, 0, cinput); } //========= Init subtasks and start analyis ============================ // Track Cuts AliSigma0V0Cuts *v0Cuts = AliSigma0V0Cuts::LambdaCuts(); v0Cuts->SetIsMC(isMC); v0Cuts->SetPID(3122); v0Cuts->SetPosPID(AliPID::kProton, 2212); v0Cuts->SetNegPID(AliPID::kPion, -211); if (suffix == "0") { // Run1 cuts v0Cuts->SetPileUpRejectionMode(AliSigma0V0Cuts::None); v0Cuts->SetV0OnFlyStatus(true); v0Cuts->SetDaughterDCAtoPV(0.06); v0Cuts->SetDaughterDCAMax(1.5); v0Cuts->SetDaughterDCAtoPV(0.06); v0Cuts->SetV0CosPAMin(0.993); v0Cuts->SetV0RadiusMax(220.f); v0Cuts->SetV0RadiusMin(0.5); v0Cuts->SetArmenterosCut(0.01, 0.17, 0.2, 0.9); v0Cuts->SetPIDnSigma(100.f); v0Cuts->SetV0PtMin(0.); v0Cuts->SetK0Rejection(0., 0.); v0Cuts->SetLambdaSelection(1.110, 1.120); v0Cuts->SetTPCclusterMin(0.f); v0Cuts->SetEtaMax(0.9); } // TEMPORARY FIX TO GET MORE YIELD IN MC v0Cuts->SetV0OnFlyStatus(false); AliSigma0V0Cuts *antiv0Cuts = AliSigma0V0Cuts::LambdaCuts(); antiv0Cuts->SetIsMC(isMC); antiv0Cuts->SetPID(-3122); antiv0Cuts->SetPosPID(AliPID::kPion, 211); antiv0Cuts->SetNegPID(AliPID::kProton, -2212); if (suffix == "0") { // Run1 cuts antiv0Cuts->SetPileUpRejectionMode(AliSigma0V0Cuts::None); antiv0Cuts->SetV0OnFlyStatus(true); antiv0Cuts->SetDaughterDCAtoPV(0.06); antiv0Cuts->SetDaughterDCAMax(1.5); antiv0Cuts->SetDaughterDCAtoPV(0.06); antiv0Cuts->SetV0CosPAMin(0.993); antiv0Cuts->SetV0RadiusMax(220.f); antiv0Cuts->SetV0RadiusMin(0.5); antiv0Cuts->SetArmenterosCut(0.01, 0.17, 0.2, 0.9); antiv0Cuts->SetPIDnSigma(100.f); antiv0Cuts->SetV0PtMin(0.); antiv0Cuts->SetK0Rejection(0., 0.); antiv0Cuts->SetLambdaSelection(1.110, 1.120); antiv0Cuts->SetTPCclusterMin(0.f); antiv0Cuts->SetEtaMax(0.9); } // TEMPORARY FIX TO GET MORE YIELD IN MC antiv0Cuts->SetV0OnFlyStatus(false); if (suffix != "0") { v0Cuts->SetLightweight(true); antiv0Cuts->SetLightweight(true); } if (suffix == "999") { v0Cuts->SetCheckCutsMC(true); antiv0Cuts->SetCheckCutsMC(true); v0Cuts->SetLightweight(false); antiv0Cuts->SetLightweight(false); } AliSigma0PhotonMotherCuts *sigmaCuts = AliSigma0PhotonMotherCuts::DefaultCuts(); sigmaCuts->SetIsMC(isMC); sigmaCuts->SetPDG(3212, 3122, 22); sigmaCuts->SetLambdaCuts(v0Cuts); sigmaCuts->SetV0ReaderName(V0ReaderName.Data()); if (suffix == "0"){ sigmaCuts->SetArmenterosCut(0,0.12,-1,-0.6); } if (suffix != "0" && suffix != "999") { sigmaCuts->SetLightweight(true); sigmaCuts->SetIsSpectrum(false); } AliSigma0PhotonMotherCuts *antiSigmaCuts = AliSigma0PhotonMotherCuts::DefaultCuts(); antiSigmaCuts->SetIsMC(isMC); antiSigmaCuts->SetPDG(-3212, -3122, 22); antiSigmaCuts->SetLambdaCuts(antiv0Cuts); antiSigmaCuts->SetV0ReaderName(V0ReaderName.Data()); if (suffix == "0"){ antiSigmaCuts->SetArmenterosCut(0,0.12,-1,-0.6); } if (suffix != "0" && suffix != "999") { antiSigmaCuts->SetLightweight(true); antiSigmaCuts->SetIsSpectrum(false); } if (trigger == "kINT7") { sigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); } else if (trigger == "kHighMultV0") { sigmaCuts->SetMultiplicityMode(AliVEvent::kHighMultV0); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kHighMultV0); } else if (trigger == "AliVEvent::kMB") { sigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); } AliAnalysisTaskSigma0Run2 *task = new AliAnalysisTaskSigma0Run2("AnalysisTaskSigma0Run2"); if (trigger == "kINT7") { task->SetTrigger(AliVEvent::kINT7); task->SetMultiplicityMode(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); } else if (trigger == "kHighMultV0") { if (isMC) { task->SetTrigger(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); task->SetMultiplicityMode(AliVEvent::kHighMultV0); } else { task->SetTrigger(AliVEvent::kHighMultV0); task->SelectCollisionCandidates(AliVEvent::kHighMultV0); task->SetMultiplicityMode(AliVEvent::kHighMultV0); } } else if (trigger == "AliVEvent::kMB") { task->SetTrigger(AliVEvent::kMB); task->SelectCollisionCandidates(AliVEvent::kMB); task->SetMultiplicityMode(AliVEvent::kINT7); } task->SetV0ReaderName(V0ReaderName.Data()); task->SetIsRun1(isRun1); task->SetIsHeavyIon(isHeavyIon); task->SetIsMC(isMC); task->SetV0Cuts(v0Cuts); task->SetAntiV0Cuts(antiv0Cuts); task->SetSigmaCuts(sigmaCuts); task->SetAntiSigmaCuts(antiSigmaCuts); if (suffix != "0" && suffix != "999") { task->SetLightweight(true); } mgr->AddTask(task); TString containerName = mgr->GetCommonFileName(); containerName += ":Sigma0_Femto_"; if (trigger == "kHighMultV0") containerName += "HighMultV0_"; containerName += suffix; TString name = "histo_"; if (trigger == "kHighMultV0") name += "HighMultV0_"; name += suffix; AliAnalysisDataContainer *cOutputList = mgr->CreateContainer( name, TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, cOutputList); return task; } <commit_msg>Additional Output for CutVariation.<commit_after>AliAnalysisTaskSE *AddTaskSigma0Run2(bool isRun1 = false, bool isMC = false, bool isHeavyIon = false, TString trigger = "kINT7", const char *cutVariation = "0") { TString suffix; suffix.Form("%s", cutVariation); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskSigma0Run2()", "No analysis manager found."); return 0x0; } // ================== GetInputEventHandler ============================= AliVEventHandler *inputHandler = mgr->GetInputEventHandler(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); //========= Set Cutnumber for V0Reader ================================ TString cutnumberPhoton; cutnumberPhoton = "00200008400000002280920000"; TString cutnumberEvent = "00000000"; if (suffix == "0") { // Borissov cuts cutnumberPhoton = "00200008400020002282020000"; cutnumberEvent = "00000003"; } TString periodNameV0Reader = ""; Bool_t enableV0findingEffi = kFALSE; Bool_t fillHistos = kTRUE; Bool_t runLightOutput = kFALSE; if (suffix != "0" && suffix != "999") { runLightOutput = kTRUE; fillHistos = kFALSE; } //========= Add V0 Reader to ANALYSIS manager if not yet existent ===== TString V0ReaderName = Form("V0ReaderV1_%s_%s", cutnumberEvent.Data(), cutnumberPhoton.Data()); AliConvEventCuts *fEventCuts = NULL; if (!(AliV0ReaderV1 *)mgr->GetTask(V0ReaderName.Data())) { AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1(V0ReaderName.Data()); if (periodNameV0Reader.CompareTo("") != 0) fV0ReaderV1->SetPeriodName(periodNameV0Reader); fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE); fV0ReaderV1->SetCreateAODs(kFALSE); // AOD Output fV0ReaderV1->SetUseAODConversionPhoton(kTRUE); fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi); if (!mgr) { Error("AddTask_V0ReaderV1", "No analysis manager found."); return NULL; } if (cutnumberEvent != "") { fEventCuts = new AliConvEventCuts(cutnumberEvent.Data(), cutnumberEvent.Data()); fEventCuts->SetPreSelectionCutFlag(kTRUE); fEventCuts->SetV0ReaderName(V0ReaderName); fEventCuts->SetLightOutput(runLightOutput); fEventCuts->SetFillCutHistograms("", fillHistos); if (periodNameV0Reader.CompareTo("") != 0) fEventCuts->SetPeriodEnum(periodNameV0Reader); fV0ReaderV1->SetEventCuts(fEventCuts); } // Set AnalysisCut Number AliConversionPhotonCuts *fCuts = NULL; if (cutnumberPhoton != "") { fCuts = new AliConversionPhotonCuts(cutnumberPhoton.Data(), cutnumberPhoton.Data()); fCuts->SetPreSelectionCutFlag(kTRUE); fCuts->SetIsHeavyIon(isHeavyIon); fCuts->SetV0ReaderName(V0ReaderName); fCuts->SetLightOutput(runLightOutput); fCuts->SetFillCutHistograms("", fillHistos); if (fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())) { fV0ReaderV1->SetConversionCuts(fCuts); } } fV0ReaderV1->Init(); AliLog::SetGlobalLogLevel(AliLog::kFatal); // connect input V0Reader mgr->AddTask(fV0ReaderV1); mgr->ConnectInput(fV0ReaderV1, 0, cinput); } //========= Init subtasks and start analyis ============================ // Track Cuts AliSigma0V0Cuts *v0Cuts = AliSigma0V0Cuts::LambdaCuts(); v0Cuts->SetIsMC(isMC); v0Cuts->SetPID(3122); v0Cuts->SetPosPID(AliPID::kProton, 2212); v0Cuts->SetNegPID(AliPID::kPion, -211); if (suffix == "0") { // Run1 cuts v0Cuts->SetPileUpRejectionMode(AliSigma0V0Cuts::None); v0Cuts->SetV0OnFlyStatus(true); v0Cuts->SetDaughterDCAtoPV(0.06); v0Cuts->SetDaughterDCAMax(1.5); v0Cuts->SetDaughterDCAtoPV(0.06); v0Cuts->SetV0CosPAMin(0.993); v0Cuts->SetV0RadiusMax(220.f); v0Cuts->SetV0RadiusMin(0.5); v0Cuts->SetArmenterosCut(0.01, 0.17, 0.2, 0.9); v0Cuts->SetPIDnSigma(100.f); v0Cuts->SetV0PtMin(0.); v0Cuts->SetK0Rejection(0., 0.); v0Cuts->SetLambdaSelection(1.110, 1.120); v0Cuts->SetTPCclusterMin(0.f); v0Cuts->SetEtaMax(0.9); } // TEMPORARY FIX TO GET MORE YIELD IN MC v0Cuts->SetV0OnFlyStatus(false); AliSigma0V0Cuts *antiv0Cuts = AliSigma0V0Cuts::LambdaCuts(); antiv0Cuts->SetIsMC(isMC); antiv0Cuts->SetPID(-3122); antiv0Cuts->SetPosPID(AliPID::kPion, 211); antiv0Cuts->SetNegPID(AliPID::kProton, -2212); if (suffix == "0") { // Run1 cuts antiv0Cuts->SetPileUpRejectionMode(AliSigma0V0Cuts::None); antiv0Cuts->SetV0OnFlyStatus(true); antiv0Cuts->SetDaughterDCAtoPV(0.06); antiv0Cuts->SetDaughterDCAMax(1.5); antiv0Cuts->SetDaughterDCAtoPV(0.06); antiv0Cuts->SetV0CosPAMin(0.993); antiv0Cuts->SetV0RadiusMax(220.f); antiv0Cuts->SetV0RadiusMin(0.5); antiv0Cuts->SetArmenterosCut(0.01, 0.17, 0.2, 0.9); antiv0Cuts->SetPIDnSigma(100.f); antiv0Cuts->SetV0PtMin(0.); antiv0Cuts->SetK0Rejection(0., 0.); antiv0Cuts->SetLambdaSelection(1.110, 1.120); antiv0Cuts->SetTPCclusterMin(0.f); antiv0Cuts->SetEtaMax(0.9); } // TEMPORARY FIX TO GET MORE YIELD IN MC antiv0Cuts->SetV0OnFlyStatus(false); if (suffix != "0" && suffix != "1") { v0Cuts->SetLightweight(true); antiv0Cuts->SetLightweight(true); } if (suffix == "999") { v0Cuts->SetCheckCutsMC(true); antiv0Cuts->SetCheckCutsMC(true); v0Cuts->SetLightweight(false); antiv0Cuts->SetLightweight(false); } AliSigma0PhotonMotherCuts *sigmaCuts = AliSigma0PhotonMotherCuts::DefaultCuts(); sigmaCuts->SetIsMC(isMC); sigmaCuts->SetPDG(3212, 3122, 22); sigmaCuts->SetLambdaCuts(v0Cuts); sigmaCuts->SetV0ReaderName(V0ReaderName.Data()); if (suffix == "0"){ sigmaCuts->SetArmenterosCut(0,0.12,-1,-0.6); } if (suffix != "0" && suffix != "999" && suffix != "1") { sigmaCuts->SetLightweight(true); sigmaCuts->SetIsSpectrum(false); } AliSigma0PhotonMotherCuts *antiSigmaCuts = AliSigma0PhotonMotherCuts::DefaultCuts(); antiSigmaCuts->SetIsMC(isMC); antiSigmaCuts->SetPDG(-3212, -3122, 22); antiSigmaCuts->SetLambdaCuts(antiv0Cuts); antiSigmaCuts->SetV0ReaderName(V0ReaderName.Data()); if (suffix == "0"){ antiSigmaCuts->SetArmenterosCut(0,0.12,-1,-0.6); } if (suffix != "0" && suffix != "999" && suffix != "1") { antiSigmaCuts->SetLightweight(true); antiSigmaCuts->SetIsSpectrum(false); } if (trigger == "kINT7") { sigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); } else if (trigger == "kHighMultV0") { sigmaCuts->SetMultiplicityMode(AliVEvent::kHighMultV0); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kHighMultV0); } else if (trigger == "AliVEvent::kMB") { sigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); antiSigmaCuts->SetMultiplicityMode(AliVEvent::kINT7); } AliAnalysisTaskSigma0Run2 *task = new AliAnalysisTaskSigma0Run2("AnalysisTaskSigma0Run2"); if (trigger == "kINT7") { task->SetTrigger(AliVEvent::kINT7); task->SetMultiplicityMode(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); } else if (trigger == "kHighMultV0") { if (isMC) { task->SetTrigger(AliVEvent::kINT7); task->SelectCollisionCandidates(AliVEvent::kINT7); task->SetMultiplicityMode(AliVEvent::kHighMultV0); } else { task->SetTrigger(AliVEvent::kHighMultV0); task->SelectCollisionCandidates(AliVEvent::kHighMultV0); task->SetMultiplicityMode(AliVEvent::kHighMultV0); } } else if (trigger == "AliVEvent::kMB") { task->SetTrigger(AliVEvent::kMB); task->SelectCollisionCandidates(AliVEvent::kMB); task->SetMultiplicityMode(AliVEvent::kINT7); } task->SetV0ReaderName(V0ReaderName.Data()); task->SetIsRun1(isRun1); task->SetIsHeavyIon(isHeavyIon); task->SetIsMC(isMC); task->SetV0Cuts(v0Cuts); task->SetAntiV0Cuts(antiv0Cuts); task->SetSigmaCuts(sigmaCuts); task->SetAntiSigmaCuts(antiSigmaCuts); if (suffix != "0" && suffix != "999" && suffix != "1") { task->SetLightweight(true); } mgr->AddTask(task); TString containerName = mgr->GetCommonFileName(); containerName += ":Sigma0_Femto_"; if (trigger == "kHighMultV0") containerName += "HighMultV0_"; containerName += suffix; TString name = "histo_"; if (trigger == "kHighMultV0") name += "HighMultV0_"; name += suffix; AliAnalysisDataContainer *cOutputList = mgr->CreateContainer( name, TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, cOutputList); return task; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../../StroikaPreComp.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #if qPlatform_Windows #include <io.h> #elif qPlatform_POSIX #include <unistd.h> #endif #include "../../Debug/AssertExternallySynchronizedLock.h" #include "../../Execution/Common.h" #include "../../Execution/ErrNoException.h" #include "../../Execution/Exceptions.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #endif #include "../../IO/FileAccessException.h" #include "../../Streams/BufferedInputStream.h" #include "FileInputStream.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; using Execution::make_unique_lock; using Streams::InputStream; using Streams::SeekOffsetType; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; #endif /* ******************************************************************************** **************************** FileSystem::FileInputStream *********************** ******************************************************************************** */ class FileInputStream::Rep_ : public InputStream<Byte>::_IRep, private Debug::AssertExternallySynchronizedLock { public: Rep_ () = delete; Rep_ (const Rep_&) = delete; Rep_ (const String& fileName, SeekableFlag seekable) : fFD_ (-1) , fSeekable_ (seekable) { try { #if qPlatform_Windows errno_t e = _wsopen_s (&fFD_, fileName.c_str (), (O_RDONLY | O_BINARY), _SH_DENYNO, 0); if (e != 0) { Execution::errno_ErrorException::Throw (e); } ThrowIfFalseGetLastError (fFD_ != -1); #else Execution::ThrowErrNoIfNegative (fFD_ = open (fileName.AsNarrowSDKString ().c_str (), O_RDONLY)); #endif } Stroika_Foundation_IO_FileAccessException_CATCH_REBIND_FILENAME_ACCCESS_HELPER(fileName, FileAccessMode::eRead); } ~Rep_ () { #if qPlatform_Windows ::_close (fFD_); #else ::close (fFD_); #endif } nonvirtual Rep_& operator= (const Rep_&) = delete; virtual bool IsSeekable () const override { return fSeekable_ == eSeekable; } virtual size_t Read (SeekOffsetType* offset, Byte* intoStart, Byte* intoEnd) override { // @todo implement 'offset' support RequireNotNull (intoStart); RequireNotNull (intoEnd); Require (intoStart < intoEnd); size_t nRequested = intoEnd - intoStart; lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if qPlatform_Windows return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::_read (fFD_, intoStart, Math::PinToMaxForType<unsigned int> (nRequested)))); #else return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::read (fFD_, intoStart, nRequested))); #endif } virtual Streams::SeekOffsetType GetReadOffset () const override { lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (_lseeki64 (fFD_, 0, SEEK_CUR))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (lseek64 (fFD_, 0, SEEK_CUR))); #endif } virtual Streams::SeekOffsetType SeekRead (Streams::Whence whence, Streams::SignedSeekOffsetType offset) override { using namespace Streams; lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; switch (whence) { case Whence::eFromStart: { if (offset < 0) { Execution::Throw (std::range_error ("seek")); } #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (_lseeki64 (fFD_, offset, SEEK_SET))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (lseek64 (fFD_, offset, SEEK_SET))); #endif } break; case Whence::eFromCurrent: { #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (_lseeki64 (fFD_, offset, SEEK_CUR))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (lseek64 (fFD_, offset, SEEK_CUR))); #endif } break; case Whence::eFromEnd: { #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (_lseeki64 (fFD_, offset, SEEK_END))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (lseek64 (fFD_, offset, SEEK_END))); #endif } break; } RequireNotReached (); return 0; } private: int fFD_; SeekableFlag fSeekable_; }; FileInputStream::FileInputStream (const String& fileName, SeekableFlag seekable) : FileInputStream (make_shared<Rep_> (fileName, seekable)) { } FileInputStream::FileInputStream (const shared_ptr<Rep_>& rep) : inherited (rep) { } InputStream<Byte> FileInputStream::mk (const String& fileName, SeekableFlag seekable, BufferFlag bufferFlag) { InputStream<Byte> in = FileInputStream (fileName, seekable); switch (bufferFlag) { case eBuffered: return Streams::BufferedInputStream<Byte> (in); case eUnbuffered: return in; default: AssertNotReached (); return in; } } <commit_msg>cleanup; and added disabled USE_NOISY_TRACE_IN_THIS_MODULE_; to IO/FileSystem/FileInputStream<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../../StroikaPreComp.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #if qPlatform_Windows #include <io.h> #elif qPlatform_POSIX #include <unistd.h> #endif #include "../../Debug/AssertExternallySynchronizedLock.h" #include "../../Debug/Trace.h" #include "../../Execution/Common.h" #include "../../Execution/ErrNoException.h" #include "../../Execution/Exceptions.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #endif #include "../../IO/FileAccessException.h" #include "../../Streams/BufferedInputStream.h" #include "FileInputStream.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; using Execution::make_unique_lock; using Streams::InputStream; using Streams::SeekOffsetType; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; #endif // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** **************************** FileSystem::FileInputStream *********************** ******************************************************************************** */ class FileInputStream::Rep_ : public InputStream<Byte>::_IRep, private Debug::AssertExternallySynchronizedLock { public: Rep_ () = delete; Rep_ (const Rep_&) = delete; Rep_ (const String& fileName, SeekableFlag seekable) : fFD_ (-1) , fSeekable_ (seekable) { try { #if qPlatform_Windows errno_t e = ::_wsopen_s (&fFD_, fileName.c_str (), (O_RDONLY | O_BINARY), _SH_DENYNO, 0); if (e != 0) { Execution::errno_ErrorException::Throw (e); } ThrowIfFalseGetLastError (fFD_ != -1); #else Execution::ThrowErrNoIfNegative (fFD_ = ::open (fileName.AsNarrowSDKString ().c_str (), O_RDONLY)); #endif } Stroika_Foundation_IO_FileAccessException_CATCH_REBIND_FILENAME_ACCCESS_HELPER(fileName, FileAccessMode::eRead); } ~Rep_ () { #if qPlatform_Windows ::_close (fFD_); #else ::close (fFD_); #endif } nonvirtual Rep_& operator= (const Rep_&) = delete; virtual bool IsSeekable () const override { return fSeekable_ == eSeekable; } virtual size_t Read (SeekOffsetType* offset, Byte* intoStart, Byte* intoEnd) override { // @todo implement 'offset' support RequireNotNull (intoStart); RequireNotNull (intoEnd); Require (intoStart < intoEnd); size_t nRequested = intoEnd - intoStart; lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if qPlatform_Windows return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::_read (fFD_, intoStart, Math::PinToMaxForType<unsigned int> (nRequested)))); #else return static_cast<size_t> (Execution::ThrowErrNoIfNegative (::read (fFD_, intoStart, nRequested))); #endif } virtual Streams::SeekOffsetType GetReadOffset () const override { lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, 0, SEEK_CUR))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, 0, SEEK_CUR))); #endif } virtual Streams::SeekOffsetType SeekRead (Streams::Whence whence, Streams::SignedSeekOffsetType offset) override { using namespace Streams; lock_guard<const AssertExternallySynchronizedLock> critSec { *this }; switch (whence) { case Whence::eFromStart: { if (offset < 0) { Execution::Throw (std::range_error ("seek")); } #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_SET))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_SET))); #endif } break; case Whence::eFromCurrent: { #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_CUR))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_CUR))); #endif } break; case Whence::eFromEnd: { #if qPlatform_Windows return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::_lseeki64 (fFD_, offset, SEEK_END))); #else return static_cast<Streams::SeekOffsetType> (Execution::ThrowErrNoIfNegative (::lseek64 (fFD_, offset, SEEK_END))); #endif } break; } RequireNotReached (); return 0; } private: int fFD_; SeekableFlag fSeekable_; }; FileInputStream::FileInputStream (const String& fileName, SeekableFlag seekable) : FileInputStream (make_shared<Rep_> (fileName, seekable)) { } FileInputStream::FileInputStream (const shared_ptr<Rep_>& rep) : inherited (rep) { } InputStream<Byte> FileInputStream::mk (const String& fileName, SeekableFlag seekable, BufferFlag bufferFlag) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (L"FileInputStream::mk"); DbgTrace (L"(fileName: %s, seekable: %d, bufferFlag: %d)", fileName.c_str (), seekable, bufferFlag); #endif InputStream<Byte> in = FileInputStream (fileName, seekable); switch (bufferFlag) { case eBuffered: return Streams::BufferedInputStream<Byte> (in); case eUnbuffered: return in; default: AssertNotReached (); return in; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkFieldDataSerializer.cxx Copyright (c) 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 "vtkFieldDataSerializer.h" #include "vtkObjectFactory.h" #include "vtkFieldData.h" #include "vtkDataArray.h" #include "vtkIdList.h" #include "vtkStructuredData.h" #include "vtkStringArray.h" #include "vtkIntArray.h" #include "vtkMultiProcessStream.h" #include <cassert> // For assert() #include <cstring> // For memcpy vtkStandardNewMacro(vtkFieldDataSerializer); //------------------------------------------------------------------------------ vtkFieldDataSerializer::vtkFieldDataSerializer() { } //------------------------------------------------------------------------------ vtkFieldDataSerializer::~vtkFieldDataSerializer() { } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::SerializeMetaData( vtkFieldData *fieldData, vtkMultiProcessStream& bytestream) { if( fieldData == NULL ) { vtkGenericWarningMacro("Field data is NULL!"); return; } // STEP 0: Write the number of arrays bytestream << fieldData->GetNumberOfArrays(); // STEP 1: Loop through each array and write the metadata for( int array=0; array < fieldData->GetNumberOfArrays(); ++array ) { vtkDataArray *dataArray = fieldData->GetArray( array ); assert("pre: data array should not be NULL!" && (dataArray != NULL)); int dataType = dataArray->GetDataType(); int numComp = dataArray->GetNumberOfComponents(); int numTuples = dataArray->GetNumberOfTuples(); // serialize array information bytestream << dataType << numTuples << numComp; bytestream << std::string( dataArray->GetName() ); } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::DeserializeMetaData( vtkMultiProcessStream& bytestream, vtkStringArray *names, vtkIntArray *datatypes, vtkIntArray *dimensions) { if( bytestream.Empty() ) { vtkGenericWarningMacro("ByteStream is empty"); return; } if( (names == NULL) || (datatypes == NULL) || (dimensions == NULL) ) { vtkGenericWarningMacro( "ERROR: caller must pre-allocation names/datatypes/dimensions!"); return; } // STEP 0: Extract the number of arrays int NumberOfArrays; bytestream >> NumberOfArrays; if( NumberOfArrays == 0 ) { return; } // STEP 1: Allocate output data-structures names->SetNumberOfValues(NumberOfArrays); datatypes->SetNumberOfValues(NumberOfArrays); dimensions->SetNumberOfComponents(2); dimensions->SetNumberOfValues(NumberOfArrays); std::string *namesPtr = static_cast<std::string*>(names->GetVoidPointer(0)); int *datatypesPtr = static_cast<int*>(datatypes->GetVoidPointer(0)); int *dimensionsPtr = static_cast<int*>(dimensions->GetVoidPointer(0)); // STEP 2: Extract metadata for each array in corresponding output arrays for( int arrayIdx=0; arrayIdx < NumberOfArrays; ++arrayIdx ) { bytestream >> datatypesPtr[ arrayIdx ] >> dimensionsPtr[arrayIdx*2] >> dimensionsPtr[arrayIdx*2+1] >> namesPtr[ arrayIdx ]; } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::Serialize( vtkFieldData *fieldData, vtkMultiProcessStream& bytestream) { if( fieldData == NULL ) { vtkGenericWarningMacro("Field data is NULL!"); return; } // STEP 0: Write the number of arrays bytestream << fieldData->GetNumberOfArrays(); if( fieldData->GetNumberOfArrays() == 0 ) { return; } // STEP 1: Loop through each array and serialize its metadata for( int array=0; array < fieldData->GetNumberOfArrays(); ++array ) { vtkDataArray *dataArray = fieldData->GetArray( array ); vtkFieldDataSerializer::SerializeDataArray( dataArray, bytestream ); } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::SerializeTuples( vtkIdList *tupleIds, vtkFieldData *fieldData, vtkMultiProcessStream& bytestream ) { if( fieldData == NULL ) { vtkGenericWarningMacro("Field data is NULL!"); return; } // STEP 0: Write the number of arrays bytestream << fieldData->GetNumberOfArrays(); if( fieldData->GetNumberOfArrays() == 0 ) { return; } // STEP 1: Loop through each array, extract the data on the selected tuples // and serialize it for( int array=0; array < fieldData->GetNumberOfArrays(); ++array ) { vtkDataArray *dataArray = fieldData->GetArray( array ); // STEP 2: For each array extract only the selected tuples, i.e., a subset vtkDataArray *subSet = NULL; subSet = vtkFieldDataSerializer::ExtractSelectedTuples(tupleIds,dataArray); assert("pre: subset array is NULL!" && (subSet != NULL) ); // STEP 3: Serialize only a subset of the data vtkFieldDataSerializer::SerializeDataArray( subSet, bytestream ); subSet->Delete(); } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::SerializeSubExtent( int subext[6], int gridExtent[6], vtkFieldData *fieldData, vtkMultiProcessStream& bytestream) { if( fieldData == NULL ) { vtkGenericWarningMacro("Field data is NULL!"); return; } // STEP 0: Write the number of arrays bytestream << fieldData->GetNumberOfArrays(); if( fieldData->GetNumberOfArrays() == 0 ) { return; } // STEP 1: Loop through each array, extract the data within the subext // and serialize it for( int array=0; array < fieldData->GetNumberOfArrays(); ++array ) { vtkDataArray *dataArray = fieldData->GetArray( array ); // STEP 2: Extract the data within the requested sub-extent vtkDataArray *subSet = NULL; subSet = vtkFieldDataSerializer::ExtractSubExtentData( subext,gridExtent,dataArray); assert("pre: subset array is NULL!" && (subSet != NULL) ); // STEP 3: Serialize only a subset of the data vtkFieldDataSerializer::SerializeDataArray( subSet, bytestream ); subSet->Delete(); } // END for all arrays } //------------------------------------------------------------------------------ vtkDataArray* vtkFieldDataSerializer::ExtractSubExtentData( int subext[6], int gridExtent[6], vtkDataArray *inputDataArray ) { if( inputDataArray == NULL ) { vtkGenericWarningMacro("input data array is NULL!"); return NULL; } // STEP 0: Acquire structured data description, i.e, XY_PLANE, XYZ_GRID etc. int description = vtkStructuredData::GetDataDescriptionFromExtent(gridExtent); // STEP 1: Allocate subset array vtkDataArray *subSetArray = vtkDataArray::CreateDataArray( inputDataArray->GetDataType() ); subSetArray->SetName( inputDataArray->GetName() ); subSetArray->SetNumberOfComponents( inputDataArray->GetNumberOfComponents()); subSetArray->SetNumberOfTuples( vtkStructuredData::GetNumberOfNodes(subext,description)); int ijk[3]; for( ijk[0]=subext[0]; ijk[0] <= subext[1]; ++ijk[0] ) { for( ijk[1]=subext[2]; ijk[1] <= subext[3]; ++ijk[1] ) { for( ijk[2]=subext[4]; ijk[2] <= subext[5]; ++ijk[2] ) { // Compute the source index from the grid extent. Note, this could be // a cell index if the incoming gridExtent and subext are cell extents. vtkIdType sourceIdx = vtkStructuredData::ComputePointIdForExtent( gridExtent,ijk,description); assert("pre: source index is out-of-bounds" && (sourceIdx >= 0) && (sourceIdx < inputDataArray->GetNumberOfTuples())); // Compute the target index in the subset array. Likewise, this could be // either a cell index or a node index depending on what gridExtent or // subext represent. vtkIdType targetIdx = vtkStructuredData::ComputePointIdForExtent( subext,ijk,description); assert("pre: target index is out-of-bounds" && (targetIdx >= 0) && (targetIdx < subSetArray->GetNumberOfTuples())); subSetArray->SetTuple( targetIdx, sourceIdx, inputDataArray ); } // END for all k } // END for all j } // END for all i return(subSetArray); } //------------------------------------------------------------------------------ vtkDataArray* vtkFieldDataSerializer::ExtractSelectedTuples( vtkIdList *tupleIds, vtkDataArray *inputDataArray ) { vtkDataArray *subSetArray = vtkDataArray::CreateDataArray( inputDataArray->GetDataType() ); subSetArray->SetName( inputDataArray->GetName() ); subSetArray->SetNumberOfComponents( inputDataArray->GetNumberOfComponents()); subSetArray->SetNumberOfTuples(tupleIds->GetNumberOfIds()); vtkIdType idx = 0; for( ; idx < tupleIds->GetNumberOfIds(); ++idx ) { vtkIdType tupleIdx = tupleIds->GetId(idx); assert("pre: tuple ID is out-of bounds" && (tupleIdx >= 0) && (tupleIdx < inputDataArray->GetNumberOfTuples())); subSetArray->SetTuple( idx, tupleIdx, inputDataArray ); } // END for all tuples to extract return( subSetArray ); } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::SerializeDataArray( vtkDataArray *dataArray, vtkMultiProcessStream& bytestream) { if( dataArray == NULL ) { vtkGenericWarningMacro("data array is NULL!"); return; } // STEP 0: Serialize array information int dataType = dataArray->GetDataType(); int numComp = dataArray->GetNumberOfComponents(); int numTuples = dataArray->GetNumberOfTuples(); // serialize array information bytestream << dataType << numTuples << numComp; bytestream << std::string( dataArray->GetName() ); // STEP 1: Push the raw data into the bytestream // TODO: Add more cases for more datatypes here (?) unsigned int size = numComp*numTuples; switch( dataArray->GetDataType() ) { case VTK_FLOAT: bytestream.Push(static_cast<float*>(dataArray->GetVoidPointer(0)),size); break; case VTK_DOUBLE: bytestream.Push(static_cast<double*>(dataArray->GetVoidPointer(0)),size); break; case VTK_INT: bytestream.Push(static_cast<int*>(dataArray->GetVoidPointer(0)),size); break; default: assert("ERROR: cannot serialize data of given type" && false); cerr << "Canot serialize data of type=" << dataArray->GetDataType() << endl; } } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::Deserialize( vtkMultiProcessStream& bytestream, vtkFieldData *fieldData) { if( fieldData == NULL ) { vtkGenericWarningMacro("FieldData is NULL!"); return; } if( bytestream.Empty() ) { vtkGenericWarningMacro("Bytestream is empty!"); return; } // STEP 0: Get the number of arrays int numberOfArrays = 0; bytestream >> numberOfArrays; if( numberOfArrays == 0 ) { return; } // STEP 1: Loop and deserialize each array for( int array=0; array < numberOfArrays; ++array ) { vtkDataArray *dataArray = NULL; vtkFieldDataSerializer::DeserializeDataArray( bytestream,dataArray ); assert("post: deserialized data array should not be NULL!" && (dataArray != NULL)); fieldData->AddArray( dataArray ); dataArray->Delete(); } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::DeserializeDataArray( vtkMultiProcessStream& bytestream, vtkDataArray *&dataArray) { if( bytestream.Empty() ) { vtkGenericWarningMacro("Bytestream is empty!"); return; } // STEP 0: Deserialize array information int dataType, numTuples, numComp; std::string name; bytestream >> dataType >> numTuples >> numComp >> name; // STEP 1: Construct vtkDataArray object dataArray = vtkDataArray::CreateDataArray( dataType ); dataArray->SetNumberOfComponents( numComp ); dataArray->SetNumberOfTuples( numTuples ); dataArray->SetName( name.c_str() ); // STEP 2: Extract raw data to vtkDataArray // TODO: Add more cases for more datatypes here (?) unsigned int size = 0; switch( dataType ) { case VTK_FLOAT: { float *data = NULL; bytestream.Pop(data,size); assert("pre: deserialized raw data array is NULL" && (data != NULL) ); float *dataArrayPtr = static_cast<float*>(dataArray->GetVoidPointer(0)); assert("pre: data array pointer is NULL!" && (dataArrayPtr != NULL) ); std::memcpy(dataArrayPtr,data,size*sizeof(float)); delete [] data; } break; case VTK_DOUBLE: { double *data = NULL; bytestream.Pop(data,size); assert("pre: deserialized raw data array is NULL" && (data != NULL) ); double *dataArrayPtr = static_cast<double*>(dataArray->GetVoidPointer(0)); assert("pre: data array pointer is NULL!" && (dataArrayPtr != NULL) ); std::memcpy(dataArrayPtr,data,size*sizeof(double)); delete [] data; } break; case VTK_INT: { int *data = NULL; bytestream.Pop(data,size); assert("pre: deserialized raw data array is NULL" && (data != NULL) ); int *dataArrayPtr = static_cast<int*>(dataArray->GetVoidPointer(0)); assert("pre: data array pointer is NULL!" && (dataArrayPtr != NULL) ); std::memcpy(dataArrayPtr,data,size*sizeof(int)); delete [] data; } break; default: assert("ERROR: cannot serialize data of given type" && false); cerr << "Canot serialize data of type=" << dataArray->GetDataType() << endl; } } <commit_msg>Fix TestFieldDataSerialization.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkFieldDataSerializer.cxx Copyright (c) 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 "vtkFieldDataSerializer.h" #include "vtkObjectFactory.h" #include "vtkFieldData.h" #include "vtkDataArray.h" #include "vtkIdList.h" #include "vtkStructuredData.h" #include "vtkStringArray.h" #include "vtkIntArray.h" #include "vtkMultiProcessStream.h" #include <cassert> // For assert() #include <cstring> // For memcpy vtkStandardNewMacro(vtkFieldDataSerializer); //------------------------------------------------------------------------------ vtkFieldDataSerializer::vtkFieldDataSerializer() { } //------------------------------------------------------------------------------ vtkFieldDataSerializer::~vtkFieldDataSerializer() { } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::SerializeMetaData( vtkFieldData *fieldData, vtkMultiProcessStream& bytestream) { if( fieldData == NULL ) { vtkGenericWarningMacro("Field data is NULL!"); return; } // STEP 0: Write the number of arrays bytestream << fieldData->GetNumberOfArrays(); // STEP 1: Loop through each array and write the metadata for( int array=0; array < fieldData->GetNumberOfArrays(); ++array ) { vtkDataArray *dataArray = fieldData->GetArray( array ); assert("pre: data array should not be NULL!" && (dataArray != NULL)); int dataType = dataArray->GetDataType(); int numComp = dataArray->GetNumberOfComponents(); int numTuples = dataArray->GetNumberOfTuples(); // serialize array information bytestream << dataType << numTuples << numComp; bytestream << std::string( dataArray->GetName() ); } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::DeserializeMetaData( vtkMultiProcessStream& bytestream, vtkStringArray *names, vtkIntArray *datatypes, vtkIntArray *dimensions) { if( bytestream.Empty() ) { vtkGenericWarningMacro("ByteStream is empty"); return; } if( (names == NULL) || (datatypes == NULL) || (dimensions == NULL) ) { vtkGenericWarningMacro( "ERROR: caller must pre-allocation names/datatypes/dimensions!"); return; } // STEP 0: Extract the number of arrays int NumberOfArrays; bytestream >> NumberOfArrays; if( NumberOfArrays == 0 ) { return; } // STEP 1: Allocate output data-structures names->SetNumberOfValues(NumberOfArrays); datatypes->SetNumberOfValues(NumberOfArrays); dimensions->SetNumberOfComponents(2); dimensions->SetNumberOfTuples(NumberOfArrays); std::string *namesPtr = static_cast<std::string*>(names->GetVoidPointer(0)); int *datatypesPtr = static_cast<int*>(datatypes->GetVoidPointer(0)); int *dimensionsPtr = static_cast<int*>(dimensions->GetVoidPointer(0)); // STEP 2: Extract metadata for each array in corresponding output arrays for( int arrayIdx=0; arrayIdx < NumberOfArrays; ++arrayIdx ) { bytestream >> datatypesPtr[ arrayIdx ] >> dimensionsPtr[arrayIdx*2] >> dimensionsPtr[arrayIdx*2+1] >> namesPtr[ arrayIdx ]; } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::Serialize( vtkFieldData *fieldData, vtkMultiProcessStream& bytestream) { if( fieldData == NULL ) { vtkGenericWarningMacro("Field data is NULL!"); return; } // STEP 0: Write the number of arrays bytestream << fieldData->GetNumberOfArrays(); if( fieldData->GetNumberOfArrays() == 0 ) { return; } // STEP 1: Loop through each array and serialize its metadata for( int array=0; array < fieldData->GetNumberOfArrays(); ++array ) { vtkDataArray *dataArray = fieldData->GetArray( array ); vtkFieldDataSerializer::SerializeDataArray( dataArray, bytestream ); } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::SerializeTuples( vtkIdList *tupleIds, vtkFieldData *fieldData, vtkMultiProcessStream& bytestream ) { if( fieldData == NULL ) { vtkGenericWarningMacro("Field data is NULL!"); return; } // STEP 0: Write the number of arrays bytestream << fieldData->GetNumberOfArrays(); if( fieldData->GetNumberOfArrays() == 0 ) { return; } // STEP 1: Loop through each array, extract the data on the selected tuples // and serialize it for( int array=0; array < fieldData->GetNumberOfArrays(); ++array ) { vtkDataArray *dataArray = fieldData->GetArray( array ); // STEP 2: For each array extract only the selected tuples, i.e., a subset vtkDataArray *subSet = NULL; subSet = vtkFieldDataSerializer::ExtractSelectedTuples(tupleIds,dataArray); assert("pre: subset array is NULL!" && (subSet != NULL) ); // STEP 3: Serialize only a subset of the data vtkFieldDataSerializer::SerializeDataArray( subSet, bytestream ); subSet->Delete(); } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::SerializeSubExtent( int subext[6], int gridExtent[6], vtkFieldData *fieldData, vtkMultiProcessStream& bytestream) { if( fieldData == NULL ) { vtkGenericWarningMacro("Field data is NULL!"); return; } // STEP 0: Write the number of arrays bytestream << fieldData->GetNumberOfArrays(); if( fieldData->GetNumberOfArrays() == 0 ) { return; } // STEP 1: Loop through each array, extract the data within the subext // and serialize it for( int array=0; array < fieldData->GetNumberOfArrays(); ++array ) { vtkDataArray *dataArray = fieldData->GetArray( array ); // STEP 2: Extract the data within the requested sub-extent vtkDataArray *subSet = NULL; subSet = vtkFieldDataSerializer::ExtractSubExtentData( subext,gridExtent,dataArray); assert("pre: subset array is NULL!" && (subSet != NULL) ); // STEP 3: Serialize only a subset of the data vtkFieldDataSerializer::SerializeDataArray( subSet, bytestream ); subSet->Delete(); } // END for all arrays } //------------------------------------------------------------------------------ vtkDataArray* vtkFieldDataSerializer::ExtractSubExtentData( int subext[6], int gridExtent[6], vtkDataArray *inputDataArray ) { if( inputDataArray == NULL ) { vtkGenericWarningMacro("input data array is NULL!"); return NULL; } // STEP 0: Acquire structured data description, i.e, XY_PLANE, XYZ_GRID etc. int description = vtkStructuredData::GetDataDescriptionFromExtent(gridExtent); // STEP 1: Allocate subset array vtkDataArray *subSetArray = vtkDataArray::CreateDataArray( inputDataArray->GetDataType() ); subSetArray->SetName( inputDataArray->GetName() ); subSetArray->SetNumberOfComponents( inputDataArray->GetNumberOfComponents()); subSetArray->SetNumberOfTuples( vtkStructuredData::GetNumberOfNodes(subext,description)); int ijk[3]; for( ijk[0]=subext[0]; ijk[0] <= subext[1]; ++ijk[0] ) { for( ijk[1]=subext[2]; ijk[1] <= subext[3]; ++ijk[1] ) { for( ijk[2]=subext[4]; ijk[2] <= subext[5]; ++ijk[2] ) { // Compute the source index from the grid extent. Note, this could be // a cell index if the incoming gridExtent and subext are cell extents. vtkIdType sourceIdx = vtkStructuredData::ComputePointIdForExtent( gridExtent,ijk,description); assert("pre: source index is out-of-bounds" && (sourceIdx >= 0) && (sourceIdx < inputDataArray->GetNumberOfTuples())); // Compute the target index in the subset array. Likewise, this could be // either a cell index or a node index depending on what gridExtent or // subext represent. vtkIdType targetIdx = vtkStructuredData::ComputePointIdForExtent( subext,ijk,description); assert("pre: target index is out-of-bounds" && (targetIdx >= 0) && (targetIdx < subSetArray->GetNumberOfTuples())); subSetArray->SetTuple( targetIdx, sourceIdx, inputDataArray ); } // END for all k } // END for all j } // END for all i return(subSetArray); } //------------------------------------------------------------------------------ vtkDataArray* vtkFieldDataSerializer::ExtractSelectedTuples( vtkIdList *tupleIds, vtkDataArray *inputDataArray ) { vtkDataArray *subSetArray = vtkDataArray::CreateDataArray( inputDataArray->GetDataType() ); subSetArray->SetName( inputDataArray->GetName() ); subSetArray->SetNumberOfComponents( inputDataArray->GetNumberOfComponents()); subSetArray->SetNumberOfTuples(tupleIds->GetNumberOfIds()); vtkIdType idx = 0; for( ; idx < tupleIds->GetNumberOfIds(); ++idx ) { vtkIdType tupleIdx = tupleIds->GetId(idx); assert("pre: tuple ID is out-of bounds" && (tupleIdx >= 0) && (tupleIdx < inputDataArray->GetNumberOfTuples())); subSetArray->SetTuple( idx, tupleIdx, inputDataArray ); } // END for all tuples to extract return( subSetArray ); } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::SerializeDataArray( vtkDataArray *dataArray, vtkMultiProcessStream& bytestream) { if( dataArray == NULL ) { vtkGenericWarningMacro("data array is NULL!"); return; } // STEP 0: Serialize array information int dataType = dataArray->GetDataType(); int numComp = dataArray->GetNumberOfComponents(); int numTuples = dataArray->GetNumberOfTuples(); // serialize array information bytestream << dataType << numTuples << numComp; bytestream << std::string( dataArray->GetName() ); // STEP 1: Push the raw data into the bytestream // TODO: Add more cases for more datatypes here (?) unsigned int size = numComp*numTuples; switch( dataArray->GetDataType() ) { case VTK_FLOAT: bytestream.Push(static_cast<float*>(dataArray->GetVoidPointer(0)),size); break; case VTK_DOUBLE: bytestream.Push(static_cast<double*>(dataArray->GetVoidPointer(0)),size); break; case VTK_INT: bytestream.Push(static_cast<int*>(dataArray->GetVoidPointer(0)),size); break; default: assert("ERROR: cannot serialize data of given type" && false); cerr << "Canot serialize data of type=" << dataArray->GetDataType() << endl; } } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::Deserialize( vtkMultiProcessStream& bytestream, vtkFieldData *fieldData) { if( fieldData == NULL ) { vtkGenericWarningMacro("FieldData is NULL!"); return; } if( bytestream.Empty() ) { vtkGenericWarningMacro("Bytestream is empty!"); return; } // STEP 0: Get the number of arrays int numberOfArrays = 0; bytestream >> numberOfArrays; if( numberOfArrays == 0 ) { return; } // STEP 1: Loop and deserialize each array for( int array=0; array < numberOfArrays; ++array ) { vtkDataArray *dataArray = NULL; vtkFieldDataSerializer::DeserializeDataArray( bytestream,dataArray ); assert("post: deserialized data array should not be NULL!" && (dataArray != NULL)); fieldData->AddArray( dataArray ); dataArray->Delete(); } // END for all arrays } //------------------------------------------------------------------------------ void vtkFieldDataSerializer::DeserializeDataArray( vtkMultiProcessStream& bytestream, vtkDataArray *&dataArray) { if( bytestream.Empty() ) { vtkGenericWarningMacro("Bytestream is empty!"); return; } // STEP 0: Deserialize array information int dataType, numTuples, numComp; std::string name; bytestream >> dataType >> numTuples >> numComp >> name; // STEP 1: Construct vtkDataArray object dataArray = vtkDataArray::CreateDataArray( dataType ); dataArray->SetNumberOfComponents( numComp ); dataArray->SetNumberOfTuples( numTuples ); dataArray->SetName( name.c_str() ); // STEP 2: Extract raw data to vtkDataArray // TODO: Add more cases for more datatypes here (?) unsigned int size = 0; switch( dataType ) { case VTK_FLOAT: { float *data = NULL; bytestream.Pop(data,size); assert("pre: deserialized raw data array is NULL" && (data != NULL) ); float *dataArrayPtr = static_cast<float*>(dataArray->GetVoidPointer(0)); assert("pre: data array pointer is NULL!" && (dataArrayPtr != NULL) ); std::memcpy(dataArrayPtr,data,size*sizeof(float)); delete [] data; } break; case VTK_DOUBLE: { double *data = NULL; bytestream.Pop(data,size); assert("pre: deserialized raw data array is NULL" && (data != NULL) ); double *dataArrayPtr = static_cast<double*>(dataArray->GetVoidPointer(0)); assert("pre: data array pointer is NULL!" && (dataArrayPtr != NULL) ); std::memcpy(dataArrayPtr,data,size*sizeof(double)); delete [] data; } break; case VTK_INT: { int *data = NULL; bytestream.Pop(data,size); assert("pre: deserialized raw data array is NULL" && (data != NULL) ); int *dataArrayPtr = static_cast<int*>(dataArray->GetVoidPointer(0)); assert("pre: data array pointer is NULL!" && (dataArrayPtr != NULL) ); std::memcpy(dataArrayPtr,data,size*sizeof(int)); delete [] data; } break; default: assert("ERROR: cannot serialize data of given type" && false); cerr << "Canot serialize data of type=" << dataArray->GetDataType() << endl; } } <|endoftext|>
<commit_before>/* * unap.cpp * * Created on: Apr 2, 2013 * Author: [email protected] */ #include "unap.h" #include "formats.h" #include "exception.h" #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <fcntl.h> #include <netinet/in.h> #include <netdb.h> #include <poll.h> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <random> unsigned int UNAP::s_cSeed = 0; std::default_random_engine UNAP::s_randomEngine = std::default_random_engine(); UNAP::UNAP() : strHost("127.0.0.1"), nPort(26751), nMTU(1500), m_nSockWorker(0), m_status(usStopped), m_nSocket(-1) { if (s_cSeed == 0) { try { std::random_device rd; s_cSeed = rd(); } catch (...) { s_cSeed = Clock::now().time_since_epoch().count(); } s_randomEngine.seed(s_cSeed); } _reset(true); _init_descriptors(); } UNAP::~UNAP() { if (m_nSocket >= -1) close(m_nSocket); } UNAP::Status UNAP::get_status() const { return m_status; } void UNAP::start() { _reset(false); m_status = usRunning; m_startTime = Clock::now(); m_worker = std::thread(_make_worker()); } void UNAP::stop() { if (m_status & usRunning) _send_stop(); m_status = usStopped; if (m_worker.joinable()) m_worker.join(); } snd_pcm_sframes_t UNAP::get_buffer_pointer() const { if (!m_bPrepared) return 0; const snd_pcm_sframes_t frames = _estimate_frames(); snd_pcm_sframes_t nPointer = std::min(frames, m_nPointer)%get_buffer_size(); std::lock_guard<std::mutex> lock(m_mutex); if (nPointer == 0 && m_queue.empty() && m_nPointer > 0 && frames > 0) nPointer = get_buffer_size(); // Nothing more to play, buffer must have ran out. return nPointer; } snd_pcm_sframes_t UNAP::transfer(const char *_pData, size_t _cOffset, size_t _cSize) { assert(m_bPrepared); std::lock_guard<std::mutex> lock(m_mutex); size_t cSizeBytes = std::min<size_t>(_cSize, get_buffer_size() - m_nAvail); _cSize = cSizeBytes; cSizeBytes *= get_bytes_per_frame(); if (cSizeBytes == 0) return 0; char *pStart = m_pBuffer.get(); char *pDest = m_queue.empty() ? m_pBuffer.get() : m_queue.back().second; const char *pSrc = _pData + _cOffset*get_bytes_per_frame(); const size_t cBufferBytes = get_buffer_size()*get_bytes_per_frame(); if (pDest < pStart + cBufferBytes) { const size_t cPart = std::min(cSizeBytes, cBufferBytes - (pDest - pStart)); memcpy(pDest, pSrc, cPart); m_queue.emplace_back(pDest, pDest + cPart); cSizeBytes -= cPart; pSrc += cPart; assert(m_queue.back().second > m_queue.back().first); } if (cSizeBytes > 0) { assert(cSizeBytes < cBufferBytes); memcpy(pStart, pSrc, cSizeBytes); m_queue.emplace_back(pStart, pStart + cSizeBytes); assert(m_queue.back().second > m_queue.back().first); } m_nAvail += _cSize; return _cSize; } void UNAP::prepare() { _reset(true); m_nAvail = 0; m_strFormat = get_format_name(get_format()); m_cBitsPerSample = snd_pcm_format_physical_width(get_format()); assert(get_bytes_per_frame() > 0); assert(get_buffer_size() > 0); std::unique_ptr<char[]> pBuffer(new char[get_buffer_size()*get_bytes_per_frame()]); m_pBuffer = std::move(pBuffer); m_bPrepared = true; } void UNAP::drain() { assert(m_bPrepared); m_status = usStopping; if (m_worker.joinable()) m_worker.join(); } void UNAP::pause() { assert(m_bPrepared && m_status == usRunning); m_nLastFrames = _estimate_frames(); m_status = usPaused; m_startTime = TimePoint(); } void UNAP::unpause() { m_status = usRunning; m_startTime = Clock::now(); } snd_pcm_sframes_t UNAP::get_unplayed_frames() const { return m_nAvail; // TODO m_nPosition - estimateFrames } void UNAP::_reset(bool _bResetStreamParams) { m_nPointer = 0; m_nLastFrames = 0; m_startTime = TimePoint(); m_cStreamId = s_randomEngine(); if (_bResetStreamParams) { m_nAvail = 0; m_strFormat = ""; m_cBitsPerSample = 0; m_queue.clear(); m_bPrepared = false; } } void UNAP::_init_descriptors() { int fds[2]; if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) != 0) throw SystemError("socketpair()"); for (int fd : fds) { int fl; if ((fl = fcntl(fd, F_GETFL)) < 0) throw SystemError("fcntl()"); if (fl & O_NONBLOCK) break; if (fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) throw SystemError("fcntl()"); } poll_fd = fds[0]; m_nSockWorker = fds[1]; poll_events = POLLIN; } snd_pcm_sframes_t UNAP::_estimate_frames() const { if (m_status == usPaused) return m_nLastFrames; DurationMS ms(std::chrono::duration_cast<DurationMS>(Clock::now() - m_startTime)); return m_nLastFrames + ms.count()*(get_rate()/1000.0); } std::function<void(void)> UNAP::_make_worker() { return [&]() { if (!m_nSockWorker) return; Status prev = usRunning; while (m_status & usRunning) { if (prev == usRunning && m_status == usPaused) _send_pause(); else if (prev == usPaused && m_status == usRunning) _send_unpause(); if (!m_queue.empty()) { std::lock_guard<std::mutex> lock(m_mutex); while (!m_queue.empty()) _send_data(); } else if (m_bPrepared && m_status == UNAP::usStopping && _estimate_frames() >= m_nPointer) { _send_stop(); m_status = UNAP::usStopped; } char buf[1] = {0}; write(m_nSockWorker, buf, 1); prev = m_status; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }; } void UNAP::_prepare_packet(unap::Packet &_packet, unap::Packet_Kind _kind, uint64_t _nTimestamp) { _packet.set_version(1); _packet.set_stream(m_cStreamId); _packet.set_kind(_kind); _packet.set_channels(get_channel_count()); _packet.set_rate(get_rate()); _packet.set_format(m_strFormat); _packet.set_timestamp(_nTimestamp); if (_kind != unap::Packet_Kind_DATA) _packet.set_samples(""); } void UNAP::_send_buffer(const void *_pBuf, size_t _cSize) { for (size_t cRetry = 0; cRetry < 5; ++cRetry) { if (send(m_nSocket, _pBuf, _cSize, 0) >= 0) break; if (errno != ECONNREFUSED) throw SystemError("send()"); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } void UNAP::_send_packet(const unap::Packet &_packet) { auto pBuf = std::unique_ptr<char[]>(new char[this->nMTU]); assert(_packet.ByteSize() <= this->nMTU); _packet.SerializeToArray((void *)pBuf.get(), this->nMTU); _send_buffer((const void *)pBuf.get(), _packet.ByteSize()); } void UNAP::_send_stop() { unap::Packet packet; _prepare_packet(packet, unap::Packet_Kind_STOP, _estimate_frames()); _send_packet(packet); } void UNAP::_send_pause() { unap::Packet packet; _prepare_packet(packet, unap::Packet_Kind_PAUSE, _estimate_frames()); _send_packet(packet); } void UNAP::_send_unpause() { unap::Packet packet; _prepare_packet(packet, unap::Packet_Kind_UNPAUSE, m_nLastFrames); _send_packet(packet); } void UNAP::_send_data() { unap::Packet packet; assert(m_queue.front().second > m_queue.front().first); assert(m_bPrepared); _prepare_packet(packet, unap::Packet_Kind_DATA, m_nPointer); const size_t cHeaderSize = packet.ByteSize() + 4; // Account for data length field. const size_t cFrameSize = get_bytes_per_frame(); const size_t cTotal = ((this->nMTU - cHeaderSize)/cFrameSize)*cFrameSize; size_t cBytes = cTotal; auto pBuf = std::unique_ptr<char[]>(new char[this->nMTU]); // Reuse as serialization buffer. char *pPos = pBuf.get(); while (!m_queue.empty() && cBytes > 0) { char *pSource = m_queue.front().first; char *pEnd = m_queue.front().second; const size_t cAvailable = pEnd - pSource; if (cAvailable > 0) { const size_t c = std::min(cAvailable, (cBytes/cFrameSize)*cFrameSize); // FIXME c may equal zero. memcpy(pPos, pSource, c); pSource += c; pPos += c; cBytes -= c; } m_queue.front().first = pSource; assert(m_queue.front().second >= m_queue.front().first); if (pSource == pEnd) m_queue.pop_front(); } packet.set_samples((const void *)pBuf.get(), cTotal - cBytes); m_nPointer += (cTotal - cBytes)/get_bytes_per_frame(); m_nAvail -= (cTotal - cBytes)/get_bytes_per_frame(); // Send. assert(packet.ByteSize() <= this->nMTU); packet.SerializeToArray((void *)pBuf.get(), this->nMTU); _send_buffer((const void *)pBuf.get(), packet.ByteSize()); } void UNAP::connect() { struct sockaddr_in name; if (m_nSocket >= 0) close(m_nSocket); m_nSocket = socket(PF_INET, SOCK_DGRAM, 0); if (m_nSocket < 0) throw SystemError("socket()"); name.sin_family = AF_INET; name.sin_port = htons(this->nPort); struct hostent *pHost = gethostbyname(this->strHost.c_str()); if (!pHost) throw SystemError("gethostbyname()"); name.sin_addr = *(struct in_addr *)pHost->h_addr; if (::connect(m_nSocket, (struct sockaddr *)&name, sizeof(name)) < 0) throw SystemError("connect()"); } const std::vector<unsigned int> &UNAP::get_format_values() { m_formatValues.clear(); for (const std::string &strFormat : formats) { auto iFormat = g_formats.find(strFormat); if (iFormat != g_formats.end()) m_formatValues.push_back(iFormat->second); } return m_formatValues; } unsigned int UNAP::get_channel_count() const { return this->channels; } snd_pcm_uframes_t UNAP::get_buffer_size() const { return this->buffer_size; } snd_pcm_uframes_t UNAP::get_period_size() const { return this->buffer_size; } size_t UNAP::get_bytes_per_frame() const { return get_channel_count()*m_cBitsPerSample/8; } snd_pcm_format_t UNAP::get_format() const { return this->format; } unsigned int UNAP::get_rate() const { return this->rate; } <commit_msg>Add sanity check.<commit_after>/* * unap.cpp * * Created on: Apr 2, 2013 * Author: [email protected] */ #include "unap.h" #include "formats.h" #include "exception.h" #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <fcntl.h> #include <netinet/in.h> #include <netdb.h> #include <poll.h> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <random> unsigned int UNAP::s_cSeed = 0; std::default_random_engine UNAP::s_randomEngine = std::default_random_engine(); UNAP::UNAP() : strHost("127.0.0.1"), nPort(26751), nMTU(1500), m_nSockWorker(0), m_status(usStopped), m_nSocket(-1) { if (s_cSeed == 0) { try { std::random_device rd; s_cSeed = rd(); } catch (...) { s_cSeed = Clock::now().time_since_epoch().count(); } s_randomEngine.seed(s_cSeed); } _reset(true); _init_descriptors(); } UNAP::~UNAP() { if (m_nSocket >= -1) close(m_nSocket); } UNAP::Status UNAP::get_status() const { return m_status; } void UNAP::start() { _reset(false); m_status = usRunning; m_startTime = Clock::now(); m_worker = std::thread(_make_worker()); } void UNAP::stop() { if (m_status & usRunning) _send_stop(); m_status = usStopped; if (m_worker.joinable()) m_worker.join(); } snd_pcm_sframes_t UNAP::get_buffer_pointer() const { if (!m_bPrepared) return 0; const snd_pcm_sframes_t frames = _estimate_frames(); snd_pcm_sframes_t nPointer = std::min(frames, m_nPointer)%get_buffer_size(); std::lock_guard<std::mutex> lock(m_mutex); if (nPointer == 0 && m_queue.empty() && m_nPointer > 0 && frames > 0) nPointer = get_buffer_size(); // Nothing more to play, buffer must have ran out. return nPointer; } snd_pcm_sframes_t UNAP::transfer(const char *_pData, size_t _cOffset, size_t _cSize) { assert(m_bPrepared); std::lock_guard<std::mutex> lock(m_mutex); size_t cSizeBytes = std::min<size_t>(_cSize, get_buffer_size() - m_nAvail); _cSize = cSizeBytes; cSizeBytes *= get_bytes_per_frame(); if (cSizeBytes == 0) return 0; char *pStart = m_pBuffer.get(); char *pDest = m_queue.empty() ? m_pBuffer.get() : m_queue.back().second; const char *pSrc = _pData + _cOffset*get_bytes_per_frame(); const size_t cBufferBytes = get_buffer_size()*get_bytes_per_frame(); if (pDest < pStart + cBufferBytes) { const size_t cPart = std::min(cSizeBytes, cBufferBytes - (pDest - pStart)); memcpy(pDest, pSrc, cPart); m_queue.emplace_back(pDest, pDest + cPart); cSizeBytes -= cPart; pSrc += cPart; assert(m_queue.back().second > m_queue.back().first); } if (cSizeBytes > 0) { assert(cSizeBytes < cBufferBytes); memcpy(pStart, pSrc, cSizeBytes); m_queue.emplace_back(pStart, pStart + cSizeBytes); assert(m_queue.back().second > m_queue.back().first); } m_nAvail += _cSize; return _cSize; } void UNAP::prepare() { _reset(true); m_nAvail = 0; m_strFormat = get_format_name(get_format()); m_cBitsPerSample = snd_pcm_format_physical_width(get_format()); assert(get_bytes_per_frame() > 0); assert(get_buffer_size() > 0); std::unique_ptr<char[]> pBuffer(new char[get_buffer_size()*get_bytes_per_frame()]); m_pBuffer = std::move(pBuffer); m_bPrepared = true; } void UNAP::drain() { assert(m_bPrepared); m_status = usStopping; if (m_worker.joinable()) m_worker.join(); } void UNAP::pause() { assert(m_bPrepared && m_status == usRunning); m_nLastFrames = _estimate_frames(); m_status = usPaused; m_startTime = TimePoint(); } void UNAP::unpause() { m_status = usRunning; m_startTime = Clock::now(); } snd_pcm_sframes_t UNAP::get_unplayed_frames() const { return m_nAvail; // TODO m_nPosition - estimateFrames } void UNAP::_reset(bool _bResetStreamParams) { m_nPointer = 0; m_nLastFrames = 0; m_startTime = TimePoint(); m_cStreamId = s_randomEngine(); if (_bResetStreamParams) { m_nAvail = 0; m_strFormat = ""; m_cBitsPerSample = 0; m_queue.clear(); m_bPrepared = false; } } void UNAP::_init_descriptors() { int fds[2]; if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) != 0) throw SystemError("socketpair()"); for (int fd : fds) { int fl; if ((fl = fcntl(fd, F_GETFL)) < 0) throw SystemError("fcntl()"); if (fl & O_NONBLOCK) break; if (fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) throw SystemError("fcntl()"); } poll_fd = fds[0]; m_nSockWorker = fds[1]; poll_events = POLLIN; } snd_pcm_sframes_t UNAP::_estimate_frames() const { if (m_status == usPaused) return m_nLastFrames; DurationMS ms(std::chrono::duration_cast<DurationMS>(Clock::now() - m_startTime)); return m_nLastFrames + ms.count()*(get_rate()/1000.0); } std::function<void(void)> UNAP::_make_worker() { return [&]() { if (!m_nSockWorker) return; Status prev = usRunning; while (m_status & usRunning) { if (prev == usRunning && m_status == usPaused) _send_pause(); else if (prev == usPaused && m_status == usRunning) _send_unpause(); if (!m_queue.empty()) { std::lock_guard<std::mutex> lock(m_mutex); while (!m_queue.empty()) _send_data(); } else if (m_bPrepared && m_status == UNAP::usStopping && _estimate_frames() >= m_nPointer) { _send_stop(); m_status = UNAP::usStopped; } char buf[1] = {0}; write(m_nSockWorker, buf, 1); prev = m_status; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }; } void UNAP::_prepare_packet(unap::Packet &_packet, unap::Packet_Kind _kind, uint64_t _nTimestamp) { _packet.set_version(1); _packet.set_stream(m_cStreamId); _packet.set_kind(_kind); _packet.set_channels(get_channel_count()); _packet.set_rate(get_rate()); _packet.set_format(m_strFormat); _packet.set_timestamp(_nTimestamp); if (_kind != unap::Packet_Kind_DATA) _packet.set_samples(""); } void UNAP::_send_buffer(const void *_pBuf, size_t _cSize) { for (size_t cRetry = 0; cRetry < 5; ++cRetry) { if (send(m_nSocket, _pBuf, _cSize, 0) >= 0) break; if (errno != ECONNREFUSED) throw SystemError("send()"); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } void UNAP::_send_packet(const unap::Packet &_packet) { auto pBuf = std::unique_ptr<char[]>(new char[this->nMTU]); assert(_packet.ByteSize() <= this->nMTU); _packet.SerializeToArray((void *)pBuf.get(), this->nMTU); _send_buffer((const void *)pBuf.get(), _packet.ByteSize()); } void UNAP::_send_stop() { unap::Packet packet; _prepare_packet(packet, unap::Packet_Kind_STOP, _estimate_frames()); _send_packet(packet); } void UNAP::_send_pause() { unap::Packet packet; _prepare_packet(packet, unap::Packet_Kind_PAUSE, _estimate_frames()); _send_packet(packet); } void UNAP::_send_unpause() { unap::Packet packet; _prepare_packet(packet, unap::Packet_Kind_UNPAUSE, m_nLastFrames); _send_packet(packet); } void UNAP::_send_data() { unap::Packet packet; assert(m_queue.front().second > m_queue.front().first); assert(m_bPrepared); _prepare_packet(packet, unap::Packet_Kind_DATA, m_nPointer); const size_t cHeaderSize = packet.ByteSize() + 4; // Account for data length field. const size_t cFrameSize = get_bytes_per_frame(); const size_t cTotal = ((this->nMTU - cHeaderSize)/cFrameSize)*cFrameSize; size_t cBytes = cTotal; auto pBuf = std::unique_ptr<char[]>(new char[this->nMTU]); // Reuse as serialization buffer. char *pPos = pBuf.get(); while (!m_queue.empty() && cBytes > 0) { char *pSource = m_queue.front().first; char *pEnd = m_queue.front().second; const size_t cAvailable = pEnd - pSource; if (cAvailable > 0) { const size_t c = std::min(cAvailable, (cBytes/cFrameSize)*cFrameSize); if (c == 0) throw LogicError("Queue element size isn't mulptiple of frame size"); memcpy(pPos, pSource, c); pSource += c; pPos += c; cBytes -= c; } m_queue.front().first = pSource; assert(m_queue.front().second >= m_queue.front().first); if (pSource == pEnd) m_queue.pop_front(); } packet.set_samples((const void *)pBuf.get(), cTotal - cBytes); m_nPointer += (cTotal - cBytes)/get_bytes_per_frame(); m_nAvail -= (cTotal - cBytes)/get_bytes_per_frame(); // Send. assert(packet.ByteSize() <= this->nMTU); packet.SerializeToArray((void *)pBuf.get(), this->nMTU); _send_buffer((const void *)pBuf.get(), packet.ByteSize()); } void UNAP::connect() { struct sockaddr_in name; if (m_nSocket >= 0) close(m_nSocket); m_nSocket = socket(PF_INET, SOCK_DGRAM, 0); if (m_nSocket < 0) throw SystemError("socket()"); name.sin_family = AF_INET; name.sin_port = htons(this->nPort); struct hostent *pHost = gethostbyname(this->strHost.c_str()); if (!pHost) throw SystemError("gethostbyname()"); name.sin_addr = *(struct in_addr *)pHost->h_addr; if (::connect(m_nSocket, (struct sockaddr *)&name, sizeof(name)) < 0) throw SystemError("connect()"); } const std::vector<unsigned int> &UNAP::get_format_values() { m_formatValues.clear(); for (const std::string &strFormat : formats) { auto iFormat = g_formats.find(strFormat); if (iFormat != g_formats.end()) m_formatValues.push_back(iFormat->second); } return m_formatValues; } unsigned int UNAP::get_channel_count() const { return this->channels; } snd_pcm_uframes_t UNAP::get_buffer_size() const { return this->buffer_size; } snd_pcm_uframes_t UNAP::get_period_size() const { return this->buffer_size; } size_t UNAP::get_bytes_per_frame() const { return get_channel_count()*m_cBitsPerSample/8; } snd_pcm_format_t UNAP::get_format() const { return this->format; } unsigned int UNAP::get_rate() const { return this->rate; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-05-13 14:52:01 +0200 (Mi, 13. Mai 2009) $ Version: $Revision: 17230 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkNavigationDataToNavigationDataFilter.h" #include "mitkNavigationData.h" #include "mitkTestingMacros.h" /**Documentation * \brief test class to be able to instantiate the normally abstract (private constructor) mitk::NavigationDataToNavigationDataFilter */ class NavigationDataToNavigationDataFilterTestClass : public mitk::NavigationDataToNavigationDataFilter { public: mitkClassMacro(NavigationDataToNavigationDataFilterTestClass, NavigationDataToNavigationDataFilter); itkNewMacro(Self); }; /**Documentation * test for the class "NavigationDataToNavigationDataFilter". */ int mitkNavigationDataToNavigationDataFilterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationDataToNavigationDataFilter") // let's create an object of our class mitk::NavigationDataToNavigationDataFilter::Pointer myFilter = NavigationDataToNavigationDataFilterTestClass::New().GetPointer(); // create testing subclass, but treat it like the real NavigationDataToNavigationDataFilter MITK_TEST_CONDITION_REQUIRED(myFilter.IsNotNull(),"Testing instantiation"); /* create helper objects: navigation data with position as origin, zero quaternion, zero error and data valid */ mitk::NavigationData::PositionType initialPos; mitk::FillVector3D(initialPos, 1.0, 2.0, 3.0); mitk::NavigationData::OrientationType initialOri(0.1, 0.2, 0.3, 0.4); mitk::ScalarType initialError(22.22); bool initialValid(true); mitk::NavigationData::Pointer nd0 = mitk::NavigationData::New(); nd0->SetPosition(initialPos); nd0->SetOrientation(initialOri); nd0->SetPositionAccuracy(initialError); nd0->SetDataValid(initialValid); MITK_TEST_CONDITION(myFilter->GetOutput() == NULL, "testing GetOutput()"); myFilter->SetInput(nd0); MITK_TEST_CONDITION(myFilter->GetInput() == nd0, "testing Set-/GetInput()"); MITK_TEST_CONDITION(myFilter->GetInput(0) == nd0, "testing Set-/GetInput(0)"); MITK_TEST_CONDITION(myFilter->GetOutput() != NULL, "testing GetOutput() after SetInput()"); MITK_TEST_CONDITION(myFilter->GetOutput(0) != NULL, "testing GetOutput() after SetInput()"); MITK_TEST_CONDITION(myFilter->GetOutput(0) != nd0, "testing GetOutput() different object than input"); mitk::NavigationData::Pointer nd1 = mitk::NavigationData::New(); nd1->Graft(nd0); nd1->SetDataValid(false); myFilter->SetInput(1, nd1); MITK_TEST_CONDITION(myFilter->GetInput(1) == nd1, "testing Set-/GetInput(1)"); MITK_TEST_CONDITION(myFilter->GetInput(0) == nd0, "testing Set-/GetInput(0) again"); MITK_TEST_CONDITION(myFilter->GetOutput(1) != NULL, "testing GetOutput() after SetInput()"); MITK_TEST_CONDITION(myFilter->GetOutput(0) != myFilter->GetOutput(1), "testing GetOutput(0) different object than GetOutput(1)"); myFilter->SetInput(10, nd1); MITK_TEST_CONDITION(myFilter->GetNumberOfInputs() == 11, "testing SetInput(10) produces 11 outputs"); MITK_TEST_CONDITION(myFilter->GetInput(10) == nd1, "testing Set-/GetInput(10)"); myFilter->SetInput(10, NULL); MITK_TEST_CONDITION(myFilter->GetNumberOfInputs() == 10, "testing SetInput(10, NULL) removes output with index 10"); myFilter->SetInput(1, NULL); MITK_TEST_CONDITION(myFilter->GetNumberOfInputs() == 10, "testing SetInput(1, NULL) does not change number of outputs"); // always end with this! MITK_TEST_END(); } <commit_msg>test cases extended<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-05-13 14:52:01 +0200 (Mi, 13. Mai 2009) $ Version: $Revision: 17230 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkNavigationDataToNavigationDataFilter.h" #include "mitkNavigationData.h" #include "mitkTestingMacros.h" /**Documentation * \brief test class to be able to instantiate the normally abstract (private constructor) mitk::NavigationDataToNavigationDataFilter */ class NavigationDataToNavigationDataFilterTestClass : public mitk::NavigationDataToNavigationDataFilter { public: mitkClassMacro(NavigationDataToNavigationDataFilterTestClass, NavigationDataToNavigationDataFilter); itkNewMacro(Self); }; /**Documentation * test for the class "NavigationDataToNavigationDataFilter". */ int mitkNavigationDataToNavigationDataFilterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationDataToNavigationDataFilter") // let's create an object of our class mitk::NavigationDataToNavigationDataFilter::Pointer myFilter = NavigationDataToNavigationDataFilterTestClass::New().GetPointer(); // create testing subclass, but treat it like the real NavigationDataToNavigationDataFilter MITK_TEST_CONDITION_REQUIRED(myFilter.IsNotNull(),"Testing instantiation"); /* create helper objects: navigation data with position as origin, zero quaternion, zero error and data valid */ mitk::NavigationData::PositionType initialPos; mitk::FillVector3D(initialPos, 1.0, 2.0, 3.0); mitk::NavigationData::OrientationType initialOri(0.1, 0.2, 0.3, 0.4); mitk::ScalarType initialError(22.22); bool initialValid(true); mitk::NavigationData::Pointer nd0 = mitk::NavigationData::New(); nd0->SetPosition(initialPos); nd0->SetOrientation(initialOri); nd0->SetPositionAccuracy(initialError); nd0->SetDataValid(initialValid); nd0->SetName("testName"); MITK_TEST_CONDITION(myFilter->GetOutput() == NULL, "testing GetOutput()"); MITK_TEST_CONDITION(myFilter->GetInput() == NULL, "testing GetInput() without SetInput()"); MITK_TEST_CONDITION(myFilter->GetInput(0) == NULL, "testing GetInput(0) without SetInput()"); myFilter->SetInput(nd0); MITK_TEST_CONDITION(myFilter->GetInput() == nd0, "testing Set-/GetInput()"); MITK_TEST_CONDITION(myFilter->GetInput(0) == nd0, "testing Set-/GetInput(0)"); MITK_TEST_CONDITION(myFilter->GetOutput() != NULL, "testing GetOutput() after SetInput()"); MITK_TEST_CONDITION(myFilter->GetOutput(0) != NULL, "testing GetOutput() after SetInput()"); MITK_TEST_CONDITION(myFilter->GetOutput(0) != nd0, "testing GetOutput() different object than input"); // check getInput() string input MITK_TEST_CONDITION(myFilter->GetInput("invalidName") == NULL, "testing GetInput(string) invalid string"); MITK_TEST_CONDITION(myFilter->GetInput("testName") == nd0, "testing GetInput(string) valid string"); // check getInputIndex() string input bool throwsException = false; try { myFilter->GetInputIndex("invalidName"); } catch(std::invalid_argument e) { throwsException = true; } MITK_TEST_CONDITION_REQUIRED(throwsException, "testing GetInputIndex(string) invalid string"); MITK_TEST_CONDITION(myFilter->GetInputIndex("testName") == 0, "testing GetInputIndex(string) valid string"); mitk::NavigationData::Pointer nd1 = mitk::NavigationData::New(); nd1->Graft(nd0); nd1->SetDataValid(false); myFilter->SetInput(1, nd1); MITK_TEST_CONDITION(myFilter->GetInput(1) == nd1, "testing Set-/GetInput(1)"); MITK_TEST_CONDITION(myFilter->GetInput(0) == nd0, "testing Set-/GetInput(0) again"); MITK_TEST_CONDITION(myFilter->GetOutput(1) != NULL, "testing GetOutput() after SetInput()"); MITK_TEST_CONDITION(myFilter->GetOutput(0) != myFilter->GetOutput(1), "testing GetOutput(0) different object than GetOutput(1)"); myFilter->SetInput(10, nd1); MITK_TEST_CONDITION(myFilter->GetNumberOfInputs() == 11, "testing SetInput(10) produces 11 outputs"); MITK_TEST_CONDITION(myFilter->GetInput(10) == nd1, "testing Set-/GetInput(10)"); myFilter->SetInput(10, NULL); MITK_TEST_CONDITION(myFilter->GetNumberOfInputs() == 10, "testing SetInput(10, NULL) removes output with index 10"); myFilter->SetInput(1, NULL); MITK_TEST_CONDITION(myFilter->GetNumberOfInputs() == 10, "testing SetInput(1, NULL) does not change number of outputs"); // always end with this! MITK_TEST_END(); } <|endoftext|>
<commit_before>#pragma once #include <string> #include <sstream> #include <iomanip> #include <iostream> #if defined(ENABLE_LLVM) && !defined(NDEBUG) && !defined(EMSCRIPTEN) #include <llvm/IR/Constants.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Module.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Value.h> #include <llvm/IR/ValueSymbolTable.h> #include <llvm/AsmParser/Parser.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/SourceMgr.h> #endif #include "definitions.hpp" namespace processwarp { namespace Util { /** * Convert instruction code to readable string. * @param code Instruction code. * @return Converted string. */ std::string code2str(instruction_t code); /** * Convert integer to decimal string. * @param v Integer. * @return Converted string. */ template<class T> std::string num2dec_str(T v) { return std::to_string(v); } /** * Convert integer to hex string. * @param v Integer. * @return Converted string. */ template<class T> std::string num2hex_str(T v) { std::ostringstream os; os << std::hex << std::setfill('0') << std::setw(sizeof(T) * 2) << v; return os.str(); } template<> std::string num2hex_str<uint8_t>(uint8_t v); inline std::string numptr2str(const void* ptr, unsigned int size) { longest_uint_t buffer; std::memcpy(&buffer, ptr, size); std::ostringstream os; os << std::hex << std::setfill('0') << std::setw(size * 2) << buffer; return os.str(); } /** * Convert hex formated string to integer. * @param str Hex formated string. * @return Converted integer. */ template<class T> T hex_str2num(const std::string& str) { std::istringstream is(str); T v; is >> std::hex >> v; return v; } template<> uint8_t hex_str2num<uint8_t>(const std::string& str); /** * Convert address string to vaddr_t. * @param str address string. * @return Converted address. */ inline vaddr_t str2vaddr(const std::string& str) { return hex_str2num<vaddr_t>(str); } /** * Converted address vaddr_t to string. * @param addr address vaddr_t. * @return Converted address. */ inline std::string vaddr2str(vaddr_t addr) { return num2hex_str<vaddr_t>(addr); } /** * Show alert to fix function when NDEBUG isn't defined. * @param mesg Message to show. */ #ifdef NDEBUG #define fixme(mesg) // #else #define fixme(mesg) Util::_fixme(__LINE__, __FILE__, mesg); #endif void _fixme(long line, const char* file, std::string mesg); /** * Show debug message when NEBUG isn't defined. * @param mesg Message to show (format is the same to printf). */ #ifdef NDEBUG #define print_debug(...) // #else // NDEBUG #ifndef EMSCRIPTEN #define print_debug(...) { \ fprintf(stderr, "\x1b[36mdebug\x1b[39m [%d@" __FILE__ "] ", __LINE__); \ fprintf(stderr, "" __VA_ARGS__); \ } #else // EMSCRIPTEN #define print_debug(...) { \ fprintf(stderr, "debug [%d@" __FILE__ "] ", __LINE__); \ fprintf(stderr, "" __VA_ARGS__); \ } #endif // EMSCRIPTEN #endif // NDEBUG #if !defined(ENABLE_LLVM) || defined(NDEBUG) || defined(EMSCRIPTEN) #define save_llvm_instruction(I) // #define print_llvm_instruction() // #else extern const llvm::Instruction* llvm_instruction; #define save_llvm_instruction(I) Util::llvm_instruction = (I) #define print_llvm_instruction() Util::llvm_instruction->dump(); #endif } } <commit_msg>avoid compile error on memcpy<commit_after>#pragma once #include <cstring> #include <string> #include <sstream> #include <iomanip> #include <iostream> #if defined(ENABLE_LLVM) && !defined(NDEBUG) && !defined(EMSCRIPTEN) #include <llvm/IR/Constants.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Module.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Value.h> #include <llvm/IR/ValueSymbolTable.h> #include <llvm/AsmParser/Parser.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/SourceMgr.h> #endif #include "definitions.hpp" namespace processwarp { namespace Util { /** * Convert instruction code to readable string. * @param code Instruction code. * @return Converted string. */ std::string code2str(instruction_t code); /** * Convert integer to decimal string. * @param v Integer. * @return Converted string. */ template<class T> std::string num2dec_str(T v) { return std::to_string(v); } /** * Convert integer to hex string. * @param v Integer. * @return Converted string. */ template<class T> std::string num2hex_str(T v) { std::ostringstream os; os << std::hex << std::setfill('0') << std::setw(sizeof(T) * 2) << v; return os.str(); } template<> std::string num2hex_str<uint8_t>(uint8_t v); inline std::string numptr2str(const void* ptr, unsigned int size) { longest_uint_t buffer; std::memcpy(&buffer, ptr, size); std::ostringstream os; os << std::hex << std::setfill('0') << std::setw(size * 2) << buffer; return os.str(); } /** * Convert hex formated string to integer. * @param str Hex formated string. * @return Converted integer. */ template<class T> T hex_str2num(const std::string& str) { std::istringstream is(str); T v; is >> std::hex >> v; return v; } template<> uint8_t hex_str2num<uint8_t>(const std::string& str); /** * Convert address string to vaddr_t. * @param str address string. * @return Converted address. */ inline vaddr_t str2vaddr(const std::string& str) { return hex_str2num<vaddr_t>(str); } /** * Converted address vaddr_t to string. * @param addr address vaddr_t. * @return Converted address. */ inline std::string vaddr2str(vaddr_t addr) { return num2hex_str<vaddr_t>(addr); } /** * Show alert to fix function when NDEBUG isn't defined. * @param mesg Message to show. */ #ifdef NDEBUG #define fixme(mesg) // #else #define fixme(mesg) Util::_fixme(__LINE__, __FILE__, mesg); #endif void _fixme(long line, const char* file, std::string mesg); /** * Show debug message when NEBUG isn't defined. * @param mesg Message to show (format is the same to printf). */ #ifdef NDEBUG #define print_debug(...) // #else // NDEBUG #ifndef EMSCRIPTEN #define print_debug(...) { \ fprintf(stderr, "\x1b[36mdebug\x1b[39m [%d@" __FILE__ "] ", __LINE__); \ fprintf(stderr, "" __VA_ARGS__); \ } #else // EMSCRIPTEN #define print_debug(...) { \ fprintf(stderr, "debug [%d@" __FILE__ "] ", __LINE__); \ fprintf(stderr, "" __VA_ARGS__); \ } #endif // EMSCRIPTEN #endif // NDEBUG #if !defined(ENABLE_LLVM) || defined(NDEBUG) || defined(EMSCRIPTEN) #define save_llvm_instruction(I) // #define print_llvm_instruction() // #else extern const llvm::Instruction* llvm_instruction; #define save_llvm_instruction(I) Util::llvm_instruction = (I) #define print_llvm_instruction() Util::llvm_instruction->dump(); #endif } } <|endoftext|>
<commit_before>/* The MIT License Copyright (c) 2008 Dennis Mllegaard Pedersen <[email protected]> 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 "view.h" #include "query.h" #include "mainframe_impl.h" ServerListView::ServerListView(const Query& query, long sort) : serverList(NULL), version(0) { this->query = query; this->currentSortMode = sort; wxLogDebug(_T("ServerListView() (%lx - version = %d - query = %s"), (long int)this, this->version, query.get().c_str()); } <commit_msg>Quell shadows warning<commit_after>/* The MIT License Copyright (c) 2008 Dennis Mllegaard Pedersen <[email protected]> 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 "view.h" #include "query.h" #include "mainframe_impl.h" ServerListView::ServerListView(const Query& thequery, long sort) : serverList(NULL), version(0) { this->query = thequery; this->currentSortMode = sort; wxLogDebug(_T("ServerListView() (%lx - version = %d - query = %s"), (long int)this, this->version, query.get().c_str()); } <|endoftext|>
<commit_before><commit_msg>cppcheck: zerodiv<commit_after><|endoftext|>
<commit_before>#include "cinder/app/AppBasic.h" #include "cinder/audio/Io.h" #include "cinder/audio/Output.h" #include "cinder/audio/FftProcessor.h" #include "Resources.h" using namespace ci; using namespace ci::app; using namespace std; // We'll create a new Cinder Application by deriving from the AppBasic class class AudioAnalysisSampleApp : public AppBasic { public: void setup(); void draw(); void drawWaveForm( audio::TrackRef track ); void drawFft( audio::TrackRef track ); void keyDown( KeyEvent e ); audio::TrackRef mTrack1; audio::TrackRef mTrack2; }; void AudioAnalysisSampleApp::setup() { //mTrack1 = audio::Output::addTrack( audio::load( "C:\\code\\cinder\\samples\\AudioPlayback\\resources\\booyah.mp3" ) ); //mTrack1->setPcmBuffering( true ); mTrack1 = audio::Output::addTrack( audio::load( loadResource( RES_GUITAR ) ) ); //mTrack1 = audio::Output::addTrack( audio::load( "../../../../AudioPlayback/resources/booyah.mp3" ) ); mTrack1->setPcmBuffering( true ); //mTrack2 = audio::Output::addTrack( audio::load( loadResource( RES_DRUMS ) ) ); //mTrack2->setPcmBuffering( true ); } void AudioAnalysisSampleApp::keyDown( KeyEvent e ) { if( e.getChar() == 'p' ) { ( mTrack1->isPlaying() ) ? mTrack1->stop() : mTrack1->play(); } else if( e.getChar() == 'c' ) { std::cout << audio::Output::getVolume() << std::endl; std::cout << mTrack1->getVolume() << std::endl; } } void AudioAnalysisSampleApp::drawWaveForm( audio::TrackRef track ) { audio::PcmBuffer32fRef aPcmBuffer = track->getPcmBuffer(); if( ! aPcmBuffer ) { return; } uint32_t bufferSamples = aPcmBuffer->getSampleCount(); audio::Buffer32fRef leftBuffer = aPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT ); audio::Buffer32fRef rightBuffer = aPcmBuffer->getChannelData( audio::CHANNEL_FRONT_RIGHT ); int displaySize = getWindowWidth(); int endIdx = bufferSamples; float scale = displaySize / (float)endIdx; glColor3f( 1.0f, 0.5f, 0.25f ); glBegin( GL_LINE_STRIP ); for( int i = 0; i < endIdx; i++ ) { float y = ( ( leftBuffer->mData[i] - 1 ) * - 100 ); glVertex2f( ( i * scale ) , y ); } glEnd(); glColor3f( 1.0f, 0.96f, 0.0f ); glBegin( GL_LINE_STRIP ); for( int i = 0; i < endIdx; i++ ) { float y = ( ( rightBuffer->mData[i] - 1 ) * - 100 ); glVertex2f( ( i * scale ) , y ); } glEnd(); } void AudioAnalysisSampleApp::drawFft( audio::TrackRef track ) { float ht = 100.0f; uint16_t bandCount = 32; audio::PcmBuffer32fRef aPcmBuffer = track->getPcmBuffer(); if( ! aPcmBuffer ) { return; } boost::shared_ptr<float> fftRef = audio::calculateFft( aPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT ), bandCount ); if( ! fftRef ) { return; } float * fftBuffer = fftRef.get(); for( int i = 0; i < ( bandCount ); i++ ) { float barY = fftBuffer[i] / bandCount * ht; glBegin( GL_QUADS ); glColor3f( 255.0f, 255.0f, 0.0f ); glVertex2f( i * 3, ht ); glVertex2f( i * 3 + 1, ht ); glColor3f( 0.0f, 255.0f, 0.0f ); glVertex2f( i * 3 + 1, ht - barY ); glVertex2f( i * 3, ht - barY ); glEnd(); } } void AudioAnalysisSampleApp::draw() { gl::clear( Color( 0.0f, 0.0f, 0.0f ) ); glPushMatrix(); glTranslatef( 0.0, 0.0, 0.0 ); drawFft( mTrack1 ); //drawWaveForm( mTrack1 ); glTranslatef( 0.0, 120.0, 0.0 ); //drawFft( mTrack2 ); //drawWaveForm( mTrack2 ); glPopMatrix(); } // This line tells Cinder to actually create the application CINDER_APP_BASIC( AudioAnalysisSampleApp, RendererGl ) <commit_msg>cleaning up audio analysis sample<commit_after>#include "cinder/app/AppBasic.h" #include "cinder/audio/Io.h" #include "cinder/audio/Output.h" #include "cinder/audio/FftProcessor.h" #include "cinder/audio/PcmBuffer.h" #include "Resources.h" using namespace ci; using namespace ci::app; using namespace std; // We'll create a new Cinder Application by deriving from the AppBasic class class AudioAnalysisSampleApp : public AppBasic { public: void setup(); void update(); void draw(); void keyDown( KeyEvent e ); void drawWaveForm(); void drawFft(); audio::TrackRef mTrack; audio::PcmBuffer32fRef mPcmBuffer; }; void AudioAnalysisSampleApp::setup() { //add the audio track the default audio output mTrack = audio::Output::addTrack( audio::load( loadResource( RES_GUITAR ) ) ); //you must enable enable PCM buffering on the track to be able to call getPcmBuffer on it later mTrack->setPcmBuffering( true ); } void AudioAnalysisSampleApp::keyDown( KeyEvent e ) { if( e.getChar() == 'p' ) { ( mTrack->isPlaying() ) ? mTrack->stop() : mTrack->play(); } } void AudioAnalysisSampleApp::update() { //get the latest pcm buffer from the track mPcmBuffer = mTrack->getPcmBuffer(); } void AudioAnalysisSampleApp::draw() { gl::clear( Color( 0.0f, 0.0f, 0.0f ) ); glPushMatrix(); glTranslatef( 0.0, 0.0, 0.0 ); drawWaveForm(); #if defined( CINDER_MAC ) glTranslatef( 0.0, 200.0, 0.0 ); drawFft(); #endif glPopMatrix(); } void AudioAnalysisSampleApp::drawWaveForm() { //if the buffer is null, for example if this gets called before any PCM data has been buffered //don't do anything if( ! mPcmBuffer ) { return; } uint32_t bufferLength = mPcmBuffer->getSampleCount(); audio::Buffer32fRef leftBuffer = mPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT ); audio::Buffer32fRef rightBuffer = mPcmBuffer->getChannelData( audio::CHANNEL_FRONT_RIGHT ); int displaySize = getWindowWidth(); float scale = displaySize / (float)bufferLength; PolyLine<Vec2f> leftBufferLine; PolyLine<Vec2f> rightBufferLine; for( int i = 0; i < bufferLength; i++ ) { float x = ( i * scale ); //get the PCM value from the left channel buffer float y = ( ( leftBuffer->mData[i] - 1 ) * - 100 ); leftBufferLine.push_back( Vec2f( x , y) ); y = ( ( rightBuffer->mData[i] - 1 ) * - 100 ); rightBufferLine.push_back( Vec2f( x , y) ); } gl::color( Color( 1.0f, 0.5f, 0.25f ) ); gl::draw( leftBufferLine ); gl::draw( rightBufferLine ); } #if defined(CINDER_MAC) void AudioAnalysisSampleApp::drawFft() { float ht = 100.0f; uint16_t bandCount = 32; if( ! mPcmBuffer ) return; //use the most recent Pcm data to calculate the Fft boost::shared_ptr<float> fftRef = audio::calculateFft( mPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT ), bandCount ); if( ! fftRef ) { return; } float * fftBuffer = fftRef.get(); //draw the bands for( int i = 0; i < ( bandCount ); i++ ) { float barY = fftBuffer[i] / bandCount * ht; glBegin( GL_QUADS ); glColor3f( 255.0f, 255.0f, 0.0f ); glVertex2f( i * 3, ht ); glVertex2f( i * 3 + 1, ht ); glColor3f( 0.0f, 255.0f, 0.0f ); glVertex2f( i * 3 + 1, ht - barY ); glVertex2f( i * 3, ht - barY ); glEnd(); } } #endif // This line tells Cinder to actually create the application CINDER_APP_BASIC( AudioAnalysisSampleApp, RendererGl ) <|endoftext|>
<commit_before>#include "display_driver_ssd1306.h" #define _BV(bit) (1 << (bit)) #define SSD_Command_Mode 0x00 /* C0 and DC bit are 0 */ #define SSD_Data_Mode 0x40 /* C0 bit is 0 and DC bit is 1 */ #define SSD_Inverse_Display 0xA7 #define SSD_Display_Off 0xAE #define SSD_Display_On 0xAF #define SSD_Set_ContrastLevel 0x81 #define SSD_External_Vcc 0x01 #define SSD_Internal_Vcc 0x02 #define SSD_Activate_Scroll 0x2F #define SSD_Deactivate_Scroll 0x2E #define Scroll_Left 0x00 #define Scroll_Right 0x01 #define Scroll_2Frames 0x07 #define Scroll_3Frames 0x04 #define Scroll_4Frames 0x05 #define Scroll_5Frames 0x00 #define Scroll_25Frames 0x06 #define Scroll_64Frames 0x01 #define Scroll_128Frames 0x02 #define Scroll_256Frames 0x03 #define SSD1306_DISPLAYALLON_RESUME 0xA4 #define SSD1306_DISPLAYALLON 0xA5 #define SSD1306_Normal_Display 0xA6 #define SSD1306_SETDISPLAYOFFSET 0xD3 #define SSD1306_SETCOMPINS 0xDA #define SSD1306_SETVCOMDETECT 0xDB #define SSD1306_SETDISPLAYCLOCKDIV 0xD5 #define SSD1306_SETPRECHARGE 0xD9 #define SSD1306_SETMULTIPLEX 0xA8 #define SSD1306_SETLOWCOLUMN 0x00 #define SSD1306_SETHIGHCOLUMN 0x10 #define SSD1306_SETSTARTLINE 0x40 #define SSD1306_MEMORYMODE 0x20 #define SSD1306_COMSCANINC 0xC0 #define SSD1306_COMSCANDEC 0xC8 #define SSD1306_SEGREMAP 0xA0 #define SSD1306_CHARGEPUMP 0x8D // Scrolling #defines #define SSD1306_SET_VERTICAL_SCROLL_AREA 0xA3 #define SSD1306_RIGHT_HORIZONTAL_SCROLL 0x26 #define SSD1306_LEFT_HORIZONTAL_SCROLL 0x27 #define SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL 0x29 #define SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL 0x2A namespace gameAmbiance { namespace hw { void display_driver_ssd1306::sendCommand(uint8_t c) const { _busDriver.sendCommand(_dcPin, c); } void display_driver_ssd1306::sendCommand(uint8_t c0, uint8_t c1) const { _busDriver.sendCommand(_dcPin, c0, c1); } void display_driver_ssd1306::sendCommand(uint8_t c0, uint8_t c1, uint8_t c2) const { _busDriver.sendCommand(_dcPin, c0, c1, c2); } void display_driver_ssd1306::sendData(uint8_t* buf, uint32_t len) const { _busDriver.sendCommand(_dcPin, buf, len); } display_driver_ssd1306::display_driver_ssd1306(const bus_driver_interface& busDriver, uint8_t dcPin, uint8_t rstPin, int16_t width, int16_t height) : _busDriver(busDriver) , _dcPin(dcPin) , _rstPin(rstPin) , _screenWidth(width) , _screenHeight(height) , _screenBuffer((uint8_t *)malloc((_screenWidth * _screenHeight / 8))) { } display_driver_ssd1306::~display_driver_ssd1306() { term(); free(_screenBuffer); _screenBuffer = 0; } void display_driver_ssd1306::init() { // SPI Reset // bcm2835_gpio_write(_pinRST, HIGH); // delay(1000); // bcm2835_gpio_write(_pinRST, LOW); // delay(10000); // bcm2835_gpio_write(_pinRST, HIGH); _busDriver.setPinOutputMode(_dcPin); _busDriver.setPinOutputMode(_rstPin); sendCommand(SSD_Display_Off); // 0xAE sendCommand(SSD1306_SETDISPLAYCLOCKDIV, 0x80); // 0xD5 + the suggested ratio 0x80 sendCommand(SSD1306_SETMULTIPLEX, 0x3F); sendCommand(SSD1306_SETDISPLAYOFFSET, 0x00); // 0xD3 + no offset sendCommand(SSD1306_SETSTARTLINE | 0x0); // line #0 sendCommand(SSD1306_CHARGEPUMP, 0x14); sendCommand(SSD1306_MEMORYMODE, 0x00); // 0x20 0x0 act like ks0108 sendCommand(SSD1306_SEGREMAP | 0x1); sendCommand(SSD1306_COMSCANDEC); sendCommand(SSD1306_SETCOMPINS, 0x12); // 0xDA sendCommand(SSD_Set_ContrastLevel, 0xCF); sendCommand(SSD1306_SETPRECHARGE, 0x22); // 0xd9 sendCommand(SSD1306_SETVCOMDETECT, 0x40); // 0xDB sendCommand(SSD1306_DISPLAYALLON_RESUME); // 0xA4 sendCommand(SSD1306_Normal_Display); // 0xA6 sendCommand(SSD_Display_On); } void display_driver_ssd1306::term() { } void display_driver_ssd1306::clear(uint32_t color) { int c = color ? 0xFF : 0x00; std::memset(_screenBuffer, c, _screenWidth*_screenHeight / 8); } void display_driver_ssd1306::setPixel(int16_t x, int16_t y, uint32_t color) { if ((x < 0) || (x >= _screenWidth) || (y < 0) || (y >= _screenHeight)) { return; } // Get where to do the change in the buffer uint8_t * target = _screenBuffer + (x + (y / 8)*_screenWidth); // x is which column if (color) *target |= _BV((y % 8)); else *target &= ~_BV((y % 8)); } void display_driver_ssd1306::render() { _busDriver.sendCommand(SSD1306_SETLOWCOLUMN | 0x0); // low col = 0 _busDriver.sendCommand(SSD1306_SETHIGHCOLUMN | 0x0); // hi col = 0 _busDriver.sendCommand(SSD1306_SETSTARTLINE | 0x0); // line #0 _busDriver.sendData(_screenBuffer, _screenWidth*_screenHeight/8); } } }<commit_msg>Fix compilation errors<commit_after>#include "display_driver_ssd1306.h" #define _BV(bit) (1 << (bit)) #define SSD_Command_Mode 0x00 /* C0 and DC bit are 0 */ #define SSD_Data_Mode 0x40 /* C0 bit is 0 and DC bit is 1 */ #define SSD_Inverse_Display 0xA7 #define SSD_Display_Off 0xAE #define SSD_Display_On 0xAF #define SSD_Set_ContrastLevel 0x81 #define SSD_External_Vcc 0x01 #define SSD_Internal_Vcc 0x02 #define SSD_Activate_Scroll 0x2F #define SSD_Deactivate_Scroll 0x2E #define Scroll_Left 0x00 #define Scroll_Right 0x01 #define Scroll_2Frames 0x07 #define Scroll_3Frames 0x04 #define Scroll_4Frames 0x05 #define Scroll_5Frames 0x00 #define Scroll_25Frames 0x06 #define Scroll_64Frames 0x01 #define Scroll_128Frames 0x02 #define Scroll_256Frames 0x03 #define SSD1306_DISPLAYALLON_RESUME 0xA4 #define SSD1306_DISPLAYALLON 0xA5 #define SSD1306_Normal_Display 0xA6 #define SSD1306_SETDISPLAYOFFSET 0xD3 #define SSD1306_SETCOMPINS 0xDA #define SSD1306_SETVCOMDETECT 0xDB #define SSD1306_SETDISPLAYCLOCKDIV 0xD5 #define SSD1306_SETPRECHARGE 0xD9 #define SSD1306_SETMULTIPLEX 0xA8 #define SSD1306_SETLOWCOLUMN 0x00 #define SSD1306_SETHIGHCOLUMN 0x10 #define SSD1306_SETSTARTLINE 0x40 #define SSD1306_MEMORYMODE 0x20 #define SSD1306_COMSCANINC 0xC0 #define SSD1306_COMSCANDEC 0xC8 #define SSD1306_SEGREMAP 0xA0 #define SSD1306_CHARGEPUMP 0x8D // Scrolling #defines #define SSD1306_SET_VERTICAL_SCROLL_AREA 0xA3 #define SSD1306_RIGHT_HORIZONTAL_SCROLL 0x26 #define SSD1306_LEFT_HORIZONTAL_SCROLL 0x27 #define SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL 0x29 #define SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL 0x2A namespace gameAmbiance { namespace hw { void display_driver_ssd1306::sendCommand(uint8_t c) const { _busDriver.sendCommand(_dcPin, c); } void display_driver_ssd1306::sendCommand(uint8_t c0, uint8_t c1) const { _busDriver.sendCommand(_dcPin, c0, c1); } void display_driver_ssd1306::sendCommand(uint8_t c0, uint8_t c1, uint8_t c2) const { _busDriver.sendCommand(_dcPin, c0, c1, c2); } void display_driver_ssd1306::sendData(uint8_t* buf, uint32_t len) const { _busDriver.sendData(_dcPin, buf, len); } display_driver_ssd1306::display_driver_ssd1306(const bus_driver_interface& busDriver, uint8_t dcPin, uint8_t rstPin, int16_t width, int16_t height) : _busDriver(busDriver) , _dcPin(dcPin) , _rstPin(rstPin) , _screenWidth(width) , _screenHeight(height) , _screenBuffer((uint8_t *)malloc((_screenWidth * _screenHeight / 8))) { } display_driver_ssd1306::~display_driver_ssd1306() { term(); free(_screenBuffer); _screenBuffer = 0; } void display_driver_ssd1306::init() { // SPI Reset // bcm2835_gpio_write(_pinRST, HIGH); // delay(1000); // bcm2835_gpio_write(_pinRST, LOW); // delay(10000); // bcm2835_gpio_write(_pinRST, HIGH); _busDriver.setPinOutputMode(_dcPin); _busDriver.setPinOutputMode(_rstPin); sendCommand(SSD_Display_Off); // 0xAE sendCommand(SSD1306_SETDISPLAYCLOCKDIV, 0x80); // 0xD5 + the suggested ratio 0x80 sendCommand(SSD1306_SETMULTIPLEX, 0x3F); sendCommand(SSD1306_SETDISPLAYOFFSET, 0x00); // 0xD3 + no offset sendCommand(SSD1306_SETSTARTLINE | 0x0); // line #0 sendCommand(SSD1306_CHARGEPUMP, 0x14); sendCommand(SSD1306_MEMORYMODE, 0x00); // 0x20 0x0 act like ks0108 sendCommand(SSD1306_SEGREMAP | 0x1); sendCommand(SSD1306_COMSCANDEC); sendCommand(SSD1306_SETCOMPINS, 0x12); // 0xDA sendCommand(SSD_Set_ContrastLevel, 0xCF); sendCommand(SSD1306_SETPRECHARGE, 0x22); // 0xd9 sendCommand(SSD1306_SETVCOMDETECT, 0x40); // 0xDB sendCommand(SSD1306_DISPLAYALLON_RESUME); // 0xA4 sendCommand(SSD1306_Normal_Display); // 0xA6 sendCommand(SSD_Display_On); } void display_driver_ssd1306::term() { } void display_driver_ssd1306::clear(uint32_t color) { int c = color ? 0xFF : 0x00; memset(_screenBuffer, c, _screenWidth*_screenHeight / 8); } void display_driver_ssd1306::setPixel(int16_t x, int16_t y, uint32_t color) { if ((x < 0) || (x >= _screenWidth) || (y < 0) || (y >= _screenHeight)) { return; } // Get where to do the change in the buffer uint8_t * target = _screenBuffer + (x + (y / 8)*_screenWidth); // x is which column if (color) *target |= _BV((y % 8)); else *target &= ~_BV((y % 8)); } void display_driver_ssd1306::render() { _busDriver.sendCommand((_uint8_t)(SSD1306_SETLOWCOLUMN | 0x0)); // low col = 0 _busDriver.sendCommand((_uint8_t)(SSD1306_SETHIGHCOLUMN | 0x0)); // hi col = 0 _busDriver.sendCommand((_uint8_t)(SSD1306_SETSTARTLINE | 0x0)); // line #0 _busDriver.sendData(_screenBuffer, _screenWidth*_screenHeight/8); } } }<|endoftext|>
<commit_before>/** @file Script.hpp @brief Class responsible for starting the game, creating an owner. @copyright LGPL. MIT License. */ #ifndef __SCRIPT__ #define __SCRIPT__ #include "Engine/Component.hpp" #include "Engine/GameObject.hpp" #include <utility> class Script : public Component { public: // constructor and destructor Script(GameObject *owner); // pure virtual name getter virtual std::string GetComponentName() = 0; }; #endif <commit_msg>Fourth Application: Script.hpp - Comments in the file of classes; - Comments in its variables;<commit_after>/** @file Script.hpp @brief Class responsible for starting the game, creating an owner. @copyright LGPL. MIT License. */ #ifndef __SCRIPT__ #define __SCRIPT__ #include "Engine/Component.hpp" #include "Engine/GameObject.hpp" #include <utility> class Script : public Component { public: // constructor and destructor. Script(GameObject *owner); // pure virtual name getter. virtual std::string GetComponentName() = 0; }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AccessibleOutlineEditSource.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:24:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #ifndef _SVX_UNOEDHLP_HXX #include <svx/unoedhlp.hxx> #endif #ifndef _SVDOUTL_HXX #include <svx/svdoutl.hxx> #endif #ifndef SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_EDIT_SOURCE_HXX #include <AccessibleOutlineEditSource.hxx> #endif #ifndef SD_OUTLINE_VIEW_HXX #include "OutlineView.hxx" #endif namespace accessibility { AccessibleOutlineEditSource::AccessibleOutlineEditSource( SdrOutliner& rOutliner, SdrView& rView, OutlinerView& rOutlView, const ::Window& rViewWindow ) : mrView( rView ), mrWindow( rViewWindow ), mpOutliner( &rOutliner ), mpOutlinerView( &rOutlView ), mTextForwarder( rOutliner, NULL ), mViewForwarder( rOutlView ) { // register as listener - need to broadcast state change messages rOutliner.SetNotifyHdl( LINK(this, AccessibleOutlineEditSource, NotifyHdl) ); } AccessibleOutlineEditSource::~AccessibleOutlineEditSource() { if( mpOutliner ) mpOutliner->SetNotifyHdl( Link() ); Broadcast( TextHint( SFX_HINT_DYING ) ); } SvxEditSource* AccessibleOutlineEditSource::Clone() const { return NULL; } SvxTextForwarder* AccessibleOutlineEditSource::GetTextForwarder() { // TODO: maybe suboptimal if( IsValid() ) return &mTextForwarder; else return NULL; } SvxViewForwarder* AccessibleOutlineEditSource::GetViewForwarder() { // TODO: maybe suboptimal if( IsValid() ) return this; else return NULL; } SvxEditViewForwarder* AccessibleOutlineEditSource::GetEditViewForwarder( sal_Bool ) { // TODO: maybe suboptimal if( IsValid() ) { // ignore parameter, we're always in edit mode here return &mViewForwarder; } else return NULL; } void AccessibleOutlineEditSource::UpdateData() { // NOOP, since we're always working on the 'real' outliner, // i.e. changes are immediately reflected on the screen } SfxBroadcaster& AccessibleOutlineEditSource::GetBroadcaster() const { return *( const_cast< AccessibleOutlineEditSource* > (this) ); } BOOL AccessibleOutlineEditSource::IsValid() const { if( mpOutliner && mpOutlinerView ) { // Our view still on outliner? ULONG nCurrView, nViews; for( nCurrView=0, nViews=mpOutliner->GetViewCount(); nCurrView<nViews; ++nCurrView ) { if( mpOutliner->GetView(nCurrView) == mpOutlinerView ) return sal_True; } } return sal_False; } Rectangle AccessibleOutlineEditSource::GetVisArea() const { if( IsValid() ) { Rectangle aVisArea = mrView.GetVisibleArea( mrView.FindWin( const_cast< Window* > (&mrWindow) ) ); MapMode aMapMode(mrWindow.GetMapMode()); aMapMode.SetOrigin(Point()); return mrWindow.LogicToPixel( aVisArea, aMapMode ); } return Rectangle(); } Point AccessibleOutlineEditSource::LogicToPixel( const Point& rPoint, const MapMode& rMapMode ) const { if( IsValid() && mrView.GetModel() ) { Point aPoint( OutputDevice::LogicToLogic( rPoint, rMapMode, MapMode(mrView.GetModel()->GetScaleUnit()) ) ); MapMode aMapMode(mrWindow.GetMapMode()); aMapMode.SetOrigin(Point()); return mrWindow.LogicToPixel( aPoint, aMapMode ); } return Point(); } Point AccessibleOutlineEditSource::PixelToLogic( const Point& rPoint, const MapMode& rMapMode ) const { if( IsValid() && mrView.GetModel() ) { MapMode aMapMode(mrWindow.GetMapMode()); aMapMode.SetOrigin(Point()); Point aPoint( mrWindow.PixelToLogic( rPoint, aMapMode ) ); return OutputDevice::LogicToLogic( aPoint, MapMode(mrView.GetModel()->GetScaleUnit()), rMapMode ); } return Point(); } void AccessibleOutlineEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { const SdrHint* pSdrHint = PTR_CAST( SdrHint, &rHint ); if( pSdrHint ) { switch( pSdrHint->GetKind() ) { case HINT_MODELCLEARED: // model is dying under us, going defunc if( mpOutliner ) mpOutliner->SetNotifyHdl( Link() ); mpOutliner = NULL; mpOutlinerView = NULL; Broadcast( TextHint( SFX_HINT_DYING ) ); break; } } } IMPL_LINK(AccessibleOutlineEditSource, NotifyHdl, EENotify*, aNotify) { if( aNotify ) { ::std::auto_ptr< SfxHint > aHint( SvxEditSourceHelper::EENotification2Hint( aNotify) ); if( aHint.get() ) Broadcast( *aHint.get() ); } return 0; } } // end of namespace accessibility <commit_msg>INTEGRATION: CWS aw024 (1.7.308); FILE MERGED 2006/09/21 22:53:58 aw 1.7.308.3: RESYNC: (1.8-1.9); FILE MERGED 2005/09/17 10:37:07 aw 1.7.308.2: RESYNC: (1.7-1.8); FILE MERGED 2005/05/19 12:11:20 aw 1.7.308.1: #i39529#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AccessibleOutlineEditSource.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: ihi $ $Date: 2006-11-14 14:23:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #ifndef _SVX_UNOEDHLP_HXX #include <svx/unoedhlp.hxx> #endif #ifndef _SVDOUTL_HXX #include <svx/svdoutl.hxx> #endif #ifndef SD_ACCESSIBILITY_ACCESSIBLE_OUTLINE_EDIT_SOURCE_HXX #include <AccessibleOutlineEditSource.hxx> #endif #ifndef SD_OUTLINE_VIEW_HXX #include "OutlineView.hxx" #endif #ifndef _SDRPAINTWINDOW_HXX #include <svx/sdrpaintwindow.hxx> #endif namespace accessibility { AccessibleOutlineEditSource::AccessibleOutlineEditSource( SdrOutliner& rOutliner, SdrView& rView, OutlinerView& rOutlView, const ::Window& rViewWindow ) : mrView( rView ), mrWindow( rViewWindow ), mpOutliner( &rOutliner ), mpOutlinerView( &rOutlView ), mTextForwarder( rOutliner, NULL ), mViewForwarder( rOutlView ) { // register as listener - need to broadcast state change messages rOutliner.SetNotifyHdl( LINK(this, AccessibleOutlineEditSource, NotifyHdl) ); } AccessibleOutlineEditSource::~AccessibleOutlineEditSource() { if( mpOutliner ) mpOutliner->SetNotifyHdl( Link() ); Broadcast( TextHint( SFX_HINT_DYING ) ); } SvxEditSource* AccessibleOutlineEditSource::Clone() const { return NULL; } SvxTextForwarder* AccessibleOutlineEditSource::GetTextForwarder() { // TODO: maybe suboptimal if( IsValid() ) return &mTextForwarder; else return NULL; } SvxViewForwarder* AccessibleOutlineEditSource::GetViewForwarder() { // TODO: maybe suboptimal if( IsValid() ) return this; else return NULL; } SvxEditViewForwarder* AccessibleOutlineEditSource::GetEditViewForwarder( sal_Bool ) { // TODO: maybe suboptimal if( IsValid() ) { // ignore parameter, we're always in edit mode here return &mViewForwarder; } else return NULL; } void AccessibleOutlineEditSource::UpdateData() { // NOOP, since we're always working on the 'real' outliner, // i.e. changes are immediately reflected on the screen } SfxBroadcaster& AccessibleOutlineEditSource::GetBroadcaster() const { return *( const_cast< AccessibleOutlineEditSource* > (this) ); } BOOL AccessibleOutlineEditSource::IsValid() const { if( mpOutliner && mpOutlinerView ) { // Our view still on outliner? ULONG nCurrView, nViews; for( nCurrView=0, nViews=mpOutliner->GetViewCount(); nCurrView<nViews; ++nCurrView ) { if( mpOutliner->GetView(nCurrView) == mpOutlinerView ) return sal_True; } } return sal_False; } Rectangle AccessibleOutlineEditSource::GetVisArea() const { if( IsValid() ) { SdrPaintWindow* pPaintWindow = mrView.FindPaintWindow(mrWindow); Rectangle aVisArea; if(pPaintWindow) { aVisArea = pPaintWindow->GetVisibleArea(); } MapMode aMapMode(mrWindow.GetMapMode()); aMapMode.SetOrigin(Point()); return mrWindow.LogicToPixel( aVisArea, aMapMode ); } return Rectangle(); } Point AccessibleOutlineEditSource::LogicToPixel( const Point& rPoint, const MapMode& rMapMode ) const { if( IsValid() && mrView.GetModel() ) { Point aPoint( OutputDevice::LogicToLogic( rPoint, rMapMode, MapMode(mrView.GetModel()->GetScaleUnit()) ) ); MapMode aMapMode(mrWindow.GetMapMode()); aMapMode.SetOrigin(Point()); return mrWindow.LogicToPixel( aPoint, aMapMode ); } return Point(); } Point AccessibleOutlineEditSource::PixelToLogic( const Point& rPoint, const MapMode& rMapMode ) const { if( IsValid() && mrView.GetModel() ) { MapMode aMapMode(mrWindow.GetMapMode()); aMapMode.SetOrigin(Point()); Point aPoint( mrWindow.PixelToLogic( rPoint, aMapMode ) ); return OutputDevice::LogicToLogic( aPoint, MapMode(mrView.GetModel()->GetScaleUnit()), rMapMode ); } return Point(); } void AccessibleOutlineEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { const SdrHint* pSdrHint = PTR_CAST( SdrHint, &rHint ); if( pSdrHint ) { switch( pSdrHint->GetKind() ) { case HINT_MODELCLEARED: // model is dying under us, going defunc if( mpOutliner ) mpOutliner->SetNotifyHdl( Link() ); mpOutliner = NULL; mpOutlinerView = NULL; Broadcast( TextHint( SFX_HINT_DYING ) ); break; } } } IMPL_LINK(AccessibleOutlineEditSource, NotifyHdl, EENotify*, aNotify) { if( aNotify ) { ::std::auto_ptr< SfxHint > aHint( SvxEditSourceHelper::EENotification2Hint( aNotify) ); if( aHint.get() ) Broadcast( *aHint.get() ); } return 0; } } // end of namespace accessibility <|endoftext|>
<commit_before>/** * \file * \brief SignalsCatcherControlBlock class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-04-16 */ #ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ #include "distortos/SignalAction.hpp" namespace distortos { namespace synchronization { /// SignalsCatcherControlBlock class is a structure required by threads for "catching" and "handling" of signals class SignalsCatcherControlBlock { public: /// association of signal number with SignalAction using Association = std::pair<uint8_t, SignalAction>; /// type of uninitialized storage for Association objects using Storage = std::aligned_storage<sizeof(Association), alignof(Association)>::type; /** * \brief SignalsCatcherControlBlock's constructor */ constexpr SignalsCatcherControlBlock() { } }; } // namespace synchronization } // namespace distortos #endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ <commit_msg>SignalsCatcherControlBlock: add member variables with pointers to beginning and end of ranges of SignalsCatcherControlBlock::Association objects and SignalsCatcherControlBlock::Storage objects<commit_after>/** * \file * \brief SignalsCatcherControlBlock class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-04-16 */ #ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ #include "distortos/SignalAction.hpp" namespace distortos { namespace synchronization { /// SignalsCatcherControlBlock class is a structure required by threads for "catching" and "handling" of signals class SignalsCatcherControlBlock { public: /// association of signal number with SignalAction using Association = std::pair<uint8_t, SignalAction>; /// type of uninitialized storage for Association objects using Storage = std::aligned_storage<sizeof(Association), alignof(Association)>::type; /** * \brief SignalsCatcherControlBlock's constructor */ constexpr SignalsCatcherControlBlock() : associationsBegin_{}, storageBegin_{}, storageEnd_{} { } private: /// pointer to first element of range of Association objects Association* associationsBegin_; /// union binds \a associationsEnd_ and \a storageBegin_ - these point to the same address union { /// pointer to "one past the last" element of range of Association objects Association* associationsEnd_; /// pointer to first element of range of Storage objects Storage* storageBegin_; }; /// pointer to "one past the last" element of range of Storage objects Storage* storageEnd_; }; } // namespace synchronization } // namespace distortos #endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Daniel Vrátil <[email protected]> * * 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 "merge.h" #include "fetchhelper.h" #include "imapstreamparser.h" #include "storage/selectquerybuilder.h" #include "storage/datastore.h" #include "storage/transaction.h" #include "storage/parthelper.h" #include "storage/parttypehelper.h" #include "storage/itemretriever.h" #include "storage/partstreamer.h" #include "connection.h" #include "handlerhelper.h" #include <response.h> #include <libs/imapparser_p.h> #include <libs/protocol_p.h> #include <numeric> using namespace Akonadi; using namespace Akonadi::Server; Merge::Merge() : AkAppend() { } Merge::~Merge() { } bool Merge::mergeItem( PimItem &newItem, PimItem &currentItem, const ChangedAttributes &itemFlags, const ChangedAttributes &itemTagsRID, const ChangedAttributes &itemTagsGID ) { if ( !newItem.rev() > 0 ) { currentItem.setRev( newItem.rev() ); } if ( !newItem.remoteId().isEmpty() && currentItem.remoteId() != newItem.remoteId() ) { currentItem.setRemoteId( newItem.remoteId() ); mChangedParts << AKONADI_PARAM_REMOTEID; } if ( !newItem.remoteRevision().isEmpty() && currentItem.remoteRevision() != newItem.remoteRevision() ) { currentItem.setRemoteRevision( newItem.remoteRevision() ); mChangedParts << AKONADI_PARAM_REMOTEREVISION; } if ( !newItem.gid().isEmpty() && currentItem.gid() != newItem.gid() ) { currentItem.setGid( newItem.gid() ); mChangedParts << AKONADI_PARAM_GID; } if ( newItem.datetime().isValid() ) { currentItem.setDatetime( newItem.datetime() ); } currentItem.setAtime( QDateTime::currentDateTime() ); // Only mark dirty when merged from application currentItem.setDirty( !connection()->context()->resource().isValid() ); const Collection col = Collection::retrieveById( newItem.collectionId() ); if ( itemFlags.incremental ) { bool flagsAdded = false, flagsRemoved = false; if ( !itemFlags.added.isEmpty() ) { const Flag::List addedFlags = HandlerHelper::resolveFlags( itemFlags.added ); DataStore::self()->appendItemsFlags( PimItem::List() << currentItem, addedFlags, &flagsAdded, true, col, true ); } if ( !itemFlags.removed.isEmpty() ) { const Flag::List removedFlags = HandlerHelper::resolveFlags( itemFlags.removed ); DataStore::self()->removeItemsFlags( PimItem::List() << currentItem, removedFlags, &flagsRemoved, true ); } if ( flagsAdded || flagsRemoved ) { mChangedParts << AKONADI_PARAM_FLAGS; } } else if ( !itemFlags.added.isEmpty() ) { bool flagsChanged = false; const Flag::List flags = HandlerHelper::resolveFlags( itemFlags.added ); DataStore::self()->setItemsFlags( PimItem::List() << currentItem, flags, &flagsChanged, true ); if ( flagsChanged ) { mChangedParts << AKONADI_PARAM_FLAGS; } } if ( itemTagsRID.incremental ) { bool tagsAdded = false, tagsRemoved = false; if ( !itemTagsRID.added.isEmpty() ) { const Tag::List addedTags = HandlerHelper::resolveTagsByRID( itemTagsRID.added, connection()->context() ); DataStore::self()->appendItemsTags( PimItem::List() << currentItem, addedTags, &tagsAdded, true, col, true ); } if ( !itemTagsRID.removed.isEmpty() ) { const Tag::List removedTags = HandlerHelper::resolveTagsByRID( itemTagsRID.removed, connection()->context() ); DataStore::self()->removeItemsTags( PimItem::List() << currentItem, removedTags, &tagsRemoved, true ); } if ( tagsAdded || tagsRemoved ) { mChangedParts << AKONADI_PARAM_TAGS; } } else if ( !itemTagsRID.added.isEmpty() ) { bool tagsChanged = false; const Tag::List tags = HandlerHelper::resolveTagsByRID( itemTagsRID.added, connection()->context() ); DataStore::self()->setItemsTags( PimItem::List() << currentItem, tags, &tagsChanged, true ); if ( tagsChanged ) { mChangedParts << AKONADI_PARAM_TAGS; } } if ( itemTagsGID.incremental ) { bool tagsAdded = false, tagsRemoved = false; if ( !itemTagsGID.added.isEmpty() ) { const Tag::List addedTags = HandlerHelper::resolveTagsByGID( itemTagsGID.added ); DataStore::self()->appendItemsTags( PimItem::List() << currentItem, addedTags, &tagsAdded, true, col, true ); } if ( !itemTagsGID.removed.isEmpty() ) { const Tag::List removedTags = HandlerHelper::resolveTagsByGID( itemTagsGID.removed ); DataStore::self()->removeItemsTags( PimItem::List() << currentItem, removedTags, &tagsRemoved, true ); } if ( tagsAdded || tagsRemoved ) { mChangedParts << AKONADI_PARAM_TAGS; } } else if ( !itemTagsGID.added.isEmpty() ) { bool tagsChanged = false; const Tag::List tags = HandlerHelper::resolveTagsByGID( itemTagsGID.added ); DataStore::self()->setItemsTags( PimItem::List() << currentItem, tags, &tagsChanged, true ); if ( tagsChanged ) { mChangedParts << AKONADI_PARAM_TAGS; } } Part::List existingParts = Part::retrieveFiltered( Part::pimItemIdColumn(), currentItem.id() ); QMap<QByteArray, qint64> partsSizes; Q_FOREACH ( const Part &part, existingParts ) { partsSizes.insert( PartTypeHelper::fullName( part.partType() ).toLatin1(), part.datasize() ); } PartStreamer streamer(connection(), m_streamParser, currentItem); connect( &streamer, SIGNAL(responseAvailable(Akonadi::Server::Response)), this, SIGNAL(responseAvailable(Akonadi::Server::Response)) ); m_streamParser->beginList(); while ( !m_streamParser->atListEnd() ) { QByteArray partName; qint64 partSize; QByteArray command = m_streamParser->readString(); bool changed = false; if ( command.isEmpty() ) { throw HandlerException( "Syntax error" ); } if ( command.startsWith( '-' ) ) { command = command.mid( 1 ); Q_FOREACH ( const Part &part, existingParts ) { if ( part.partType().name() == QString::fromUtf8( command ) ) { DataStore::self()->removeItemParts( currentItem, QList<QByteArray>() << command ); mChangedParts << command; partsSizes.remove( command ); break; } } break; } else if ( command.startsWith( '+' ) ) { command = command.mid( 1 ); } if ( !streamer.stream( command, true, partName, partSize, &changed ) ) { return failureResponse( streamer.error() ); } if ( changed ) { mChangedParts << partName; partsSizes.insert( partName, partSize ); } } qint64 size = std::accumulate( partsSizes.begin(), partsSizes.end(), 0); currentItem.setSize( size ); // Store all changes if ( !currentItem.update() ) { return failureResponse( "Failed to store merged item" ); } return true; } bool Merge::notify( const PimItem &item, const Collection &collection ) { if ( !mChangedParts.isEmpty() ) { DataStore::self()->notificationCollector()->itemChanged( item, mChangedParts, collection ); } return true; } bool Merge::sendResponse( const QByteArray &responseStr, const PimItem &item ) { ImapSet set; set.add( QVector<qint64>() << item.id() ); Scope scope( Scope::Uid ); scope.setUidSet( set ); FetchScope fetchScope; // FetchHelper requires collection context fetchScope.setAllAttributes( true ); fetchScope.setFullPayload( true ); fetchScope.setAncestorDepth( 1 ); fetchScope.setCacheOnly( true ); fetchScope.setExternalPayloadSupported( true ); fetchScope.setFlagsRequested( true ); fetchScope.setGidRequested( true ); fetchScope.setMTimeRequested( true ); fetchScope.setRemoteIdRequested( true ); fetchScope.setRemoteRevisionRequested( true ); fetchScope.setSizeRequested( true ); fetchScope.setTagsRequested( true ); FetchHelper fetch( connection(), scope, fetchScope ); connect( &fetch, SIGNAL(responseAvailable(Akonadi::Server::Response)), this, SIGNAL(responseAvailable(Akonadi::Server::Response)) ); if ( !fetch.fetchItems( AKONADI_CMD_ITEMFETCH ) ) { return failureResponse( "Failed to retrieve merged item" ); } Response response; response.setTag( tag() ); response.setSuccess(); response.setString( responseStr ); Q_EMIT responseAvailable( response ); return true; } bool Merge::parseStream() { const QList<QByteArray> mergeParts = m_streamParser->readParenthesizedList(); DataStore *db = DataStore::self(); Transaction transaction( db ); Collection parentCol; ChangedAttributes itemFlags, itemTagsRID, itemTagsGID; PimItem item; // Parse the rest of the command, assuming X-AKAPPEND syntax if ( !buildPimItem( item, parentCol, itemFlags, itemTagsRID, itemTagsGID ) ) { return false; } bool silent = false; // Merging is always restricted to the same collection and mimetype SelectQueryBuilder<PimItem> qb; qb.addValueCondition( PimItem::collectionIdColumn(), Query::Equals, parentCol.id() ); qb.addValueCondition( PimItem::mimeTypeIdColumn(), Query::Equals, item.mimeTypeId() ); Q_FOREACH ( const QByteArray &part, mergeParts ) { if ( part == AKONADI_PARAM_GID ) { qb.addValueCondition( PimItem::gidColumn(), Query::Equals, item.gid() ); } else if ( part == AKONADI_PARAM_REMOTEID ) { qb.addValueCondition( PimItem::remoteIdColumn(), Query::Equals, item.remoteId() ); } else if ( part == AKONADI_PARAM_SILENT ) { silent = true; } else { throw HandlerException( "Only merging by RID or GID is allowed" ); } } if ( !qb.exec() ) { return failureResponse( "Failed to query database for item" ); } QVector<PimItem> result = qb.result(); if ( result.count() == 0 ) { // No item with such GID/RID exists, so call AkAppend::insert() and behave // like if this was a new item if ( !insertItem( item, parentCol, itemFlags.added, itemTagsRID.added, itemTagsGID.added ) ) { return false; } if ( !transaction.commit() ) { return failureResponse( "Failed to commit transaction" ); } AkAppend::notify( item, parentCol ); return AkAppend::sendResponse( "Append completed", item ); } else if ( result.count() == 1 ) { // Item with matching GID/RID combination exists, so merge this item into it // and send itemChanged() PimItem existingItem = result.first(); if ( !mergeItem( item, existingItem, itemFlags, itemTagsRID, itemTagsGID ) ) { return false; } if ( !transaction.commit() ) { return failureResponse( "Failed to commit transaction" ); } notify( existingItem, parentCol ); if ( silent ) { return AkAppend::sendResponse( "Merge completed", existingItem ); } else { return sendResponse( "Merge completed", existingItem ); } } else { Q_FOREACH (const PimItem &item, result) { qDebug() << item.id() << item.remoteId() << item.gid(); } // Nor GID or RID are guaranteed to be unique, so make sure we don't merge // something we don't want return failureResponse( "Multiple merge candidates, aborting" ); } } <commit_msg>Fix compiler warning in MERGE handler<commit_after>/* * Copyright (C) 2014 Daniel Vrátil <[email protected]> * * 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 "merge.h" #include "fetchhelper.h" #include "imapstreamparser.h" #include "storage/selectquerybuilder.h" #include "storage/datastore.h" #include "storage/transaction.h" #include "storage/parthelper.h" #include "storage/parttypehelper.h" #include "storage/itemretriever.h" #include "storage/partstreamer.h" #include "connection.h" #include "handlerhelper.h" #include <response.h> #include <libs/imapparser_p.h> #include <libs/protocol_p.h> #include <numeric> using namespace Akonadi; using namespace Akonadi::Server; Merge::Merge() : AkAppend() { } Merge::~Merge() { } bool Merge::mergeItem( PimItem &newItem, PimItem &currentItem, const ChangedAttributes &itemFlags, const ChangedAttributes &itemTagsRID, const ChangedAttributes &itemTagsGID ) { if ( newItem.rev() > 0 ) { currentItem.setRev( newItem.rev() ); } if ( !newItem.remoteId().isEmpty() && currentItem.remoteId() != newItem.remoteId() ) { currentItem.setRemoteId( newItem.remoteId() ); mChangedParts << AKONADI_PARAM_REMOTEID; } if ( !newItem.remoteRevision().isEmpty() && currentItem.remoteRevision() != newItem.remoteRevision() ) { currentItem.setRemoteRevision( newItem.remoteRevision() ); mChangedParts << AKONADI_PARAM_REMOTEREVISION; } if ( !newItem.gid().isEmpty() && currentItem.gid() != newItem.gid() ) { currentItem.setGid( newItem.gid() ); mChangedParts << AKONADI_PARAM_GID; } if ( newItem.datetime().isValid() ) { currentItem.setDatetime( newItem.datetime() ); } currentItem.setAtime( QDateTime::currentDateTime() ); // Only mark dirty when merged from application currentItem.setDirty( !connection()->context()->resource().isValid() ); const Collection col = Collection::retrieveById( newItem.collectionId() ); if ( itemFlags.incremental ) { bool flagsAdded = false, flagsRemoved = false; if ( !itemFlags.added.isEmpty() ) { const Flag::List addedFlags = HandlerHelper::resolveFlags( itemFlags.added ); DataStore::self()->appendItemsFlags( PimItem::List() << currentItem, addedFlags, &flagsAdded, true, col, true ); } if ( !itemFlags.removed.isEmpty() ) { const Flag::List removedFlags = HandlerHelper::resolveFlags( itemFlags.removed ); DataStore::self()->removeItemsFlags( PimItem::List() << currentItem, removedFlags, &flagsRemoved, true ); } if ( flagsAdded || flagsRemoved ) { mChangedParts << AKONADI_PARAM_FLAGS; } } else if ( !itemFlags.added.isEmpty() ) { bool flagsChanged = false; const Flag::List flags = HandlerHelper::resolveFlags( itemFlags.added ); DataStore::self()->setItemsFlags( PimItem::List() << currentItem, flags, &flagsChanged, true ); if ( flagsChanged ) { mChangedParts << AKONADI_PARAM_FLAGS; } } if ( itemTagsRID.incremental ) { bool tagsAdded = false, tagsRemoved = false; if ( !itemTagsRID.added.isEmpty() ) { const Tag::List addedTags = HandlerHelper::resolveTagsByRID( itemTagsRID.added, connection()->context() ); DataStore::self()->appendItemsTags( PimItem::List() << currentItem, addedTags, &tagsAdded, true, col, true ); } if ( !itemTagsRID.removed.isEmpty() ) { const Tag::List removedTags = HandlerHelper::resolveTagsByRID( itemTagsRID.removed, connection()->context() ); DataStore::self()->removeItemsTags( PimItem::List() << currentItem, removedTags, &tagsRemoved, true ); } if ( tagsAdded || tagsRemoved ) { mChangedParts << AKONADI_PARAM_TAGS; } } else if ( !itemTagsRID.added.isEmpty() ) { bool tagsChanged = false; const Tag::List tags = HandlerHelper::resolveTagsByRID( itemTagsRID.added, connection()->context() ); DataStore::self()->setItemsTags( PimItem::List() << currentItem, tags, &tagsChanged, true ); if ( tagsChanged ) { mChangedParts << AKONADI_PARAM_TAGS; } } if ( itemTagsGID.incremental ) { bool tagsAdded = false, tagsRemoved = false; if ( !itemTagsGID.added.isEmpty() ) { const Tag::List addedTags = HandlerHelper::resolveTagsByGID( itemTagsGID.added ); DataStore::self()->appendItemsTags( PimItem::List() << currentItem, addedTags, &tagsAdded, true, col, true ); } if ( !itemTagsGID.removed.isEmpty() ) { const Tag::List removedTags = HandlerHelper::resolveTagsByGID( itemTagsGID.removed ); DataStore::self()->removeItemsTags( PimItem::List() << currentItem, removedTags, &tagsRemoved, true ); } if ( tagsAdded || tagsRemoved ) { mChangedParts << AKONADI_PARAM_TAGS; } } else if ( !itemTagsGID.added.isEmpty() ) { bool tagsChanged = false; const Tag::List tags = HandlerHelper::resolveTagsByGID( itemTagsGID.added ); DataStore::self()->setItemsTags( PimItem::List() << currentItem, tags, &tagsChanged, true ); if ( tagsChanged ) { mChangedParts << AKONADI_PARAM_TAGS; } } Part::List existingParts = Part::retrieveFiltered( Part::pimItemIdColumn(), currentItem.id() ); QMap<QByteArray, qint64> partsSizes; Q_FOREACH ( const Part &part, existingParts ) { partsSizes.insert( PartTypeHelper::fullName( part.partType() ).toLatin1(), part.datasize() ); } PartStreamer streamer(connection(), m_streamParser, currentItem); connect( &streamer, SIGNAL(responseAvailable(Akonadi::Server::Response)), this, SIGNAL(responseAvailable(Akonadi::Server::Response)) ); m_streamParser->beginList(); while ( !m_streamParser->atListEnd() ) { QByteArray partName; qint64 partSize; QByteArray command = m_streamParser->readString(); bool changed = false; if ( command.isEmpty() ) { throw HandlerException( "Syntax error" ); } if ( command.startsWith( '-' ) ) { command = command.mid( 1 ); Q_FOREACH ( const Part &part, existingParts ) { if ( part.partType().name() == QString::fromUtf8( command ) ) { DataStore::self()->removeItemParts( currentItem, QList<QByteArray>() << command ); mChangedParts << command; partsSizes.remove( command ); break; } } break; } else if ( command.startsWith( '+' ) ) { command = command.mid( 1 ); } if ( !streamer.stream( command, true, partName, partSize, &changed ) ) { return failureResponse( streamer.error() ); } if ( changed ) { mChangedParts << partName; partsSizes.insert( partName, partSize ); } } qint64 size = std::accumulate( partsSizes.begin(), partsSizes.end(), 0); currentItem.setSize( size ); // Store all changes if ( !currentItem.update() ) { return failureResponse( "Failed to store merged item" ); } return true; } bool Merge::notify( const PimItem &item, const Collection &collection ) { if ( !mChangedParts.isEmpty() ) { DataStore::self()->notificationCollector()->itemChanged( item, mChangedParts, collection ); } return true; } bool Merge::sendResponse( const QByteArray &responseStr, const PimItem &item ) { ImapSet set; set.add( QVector<qint64>() << item.id() ); Scope scope( Scope::Uid ); scope.setUidSet( set ); FetchScope fetchScope; // FetchHelper requires collection context fetchScope.setAllAttributes( true ); fetchScope.setFullPayload( true ); fetchScope.setAncestorDepth( 1 ); fetchScope.setCacheOnly( true ); fetchScope.setExternalPayloadSupported( true ); fetchScope.setFlagsRequested( true ); fetchScope.setGidRequested( true ); fetchScope.setMTimeRequested( true ); fetchScope.setRemoteIdRequested( true ); fetchScope.setRemoteRevisionRequested( true ); fetchScope.setSizeRequested( true ); fetchScope.setTagsRequested( true ); FetchHelper fetch( connection(), scope, fetchScope ); connect( &fetch, SIGNAL(responseAvailable(Akonadi::Server::Response)), this, SIGNAL(responseAvailable(Akonadi::Server::Response)) ); if ( !fetch.fetchItems( AKONADI_CMD_ITEMFETCH ) ) { return failureResponse( "Failed to retrieve merged item" ); } Response response; response.setTag( tag() ); response.setSuccess(); response.setString( responseStr ); Q_EMIT responseAvailable( response ); return true; } bool Merge::parseStream() { const QList<QByteArray> mergeParts = m_streamParser->readParenthesizedList(); DataStore *db = DataStore::self(); Transaction transaction( db ); Collection parentCol; ChangedAttributes itemFlags, itemTagsRID, itemTagsGID; PimItem item; // Parse the rest of the command, assuming X-AKAPPEND syntax if ( !buildPimItem( item, parentCol, itemFlags, itemTagsRID, itemTagsGID ) ) { return false; } bool silent = false; // Merging is always restricted to the same collection and mimetype SelectQueryBuilder<PimItem> qb; qb.addValueCondition( PimItem::collectionIdColumn(), Query::Equals, parentCol.id() ); qb.addValueCondition( PimItem::mimeTypeIdColumn(), Query::Equals, item.mimeTypeId() ); Q_FOREACH ( const QByteArray &part, mergeParts ) { if ( part == AKONADI_PARAM_GID ) { qb.addValueCondition( PimItem::gidColumn(), Query::Equals, item.gid() ); } else if ( part == AKONADI_PARAM_REMOTEID ) { qb.addValueCondition( PimItem::remoteIdColumn(), Query::Equals, item.remoteId() ); } else if ( part == AKONADI_PARAM_SILENT ) { silent = true; } else { throw HandlerException( "Only merging by RID or GID is allowed" ); } } if ( !qb.exec() ) { return failureResponse( "Failed to query database for item" ); } QVector<PimItem> result = qb.result(); if ( result.count() == 0 ) { // No item with such GID/RID exists, so call AkAppend::insert() and behave // like if this was a new item if ( !insertItem( item, parentCol, itemFlags.added, itemTagsRID.added, itemTagsGID.added ) ) { return false; } if ( !transaction.commit() ) { return failureResponse( "Failed to commit transaction" ); } AkAppend::notify( item, parentCol ); return AkAppend::sendResponse( "Append completed", item ); } else if ( result.count() == 1 ) { // Item with matching GID/RID combination exists, so merge this item into it // and send itemChanged() PimItem existingItem = result.first(); if ( !mergeItem( item, existingItem, itemFlags, itemTagsRID, itemTagsGID ) ) { return false; } if ( !transaction.commit() ) { return failureResponse( "Failed to commit transaction" ); } notify( existingItem, parentCol ); if ( silent ) { return AkAppend::sendResponse( "Merge completed", existingItem ); } else { return sendResponse( "Merge completed", existingItem ); } } else { Q_FOREACH (const PimItem &item, result) { qDebug() << item.id() << item.remoteId() << item.gid(); } // Nor GID or RID are guaranteed to be unique, so make sure we don't merge // something we don't want return failureResponse( "Multiple merge candidates, aborting" ); } } <|endoftext|>
<commit_before>// Time echo -e "1 1\n1 2\n2 3\n3 4\n4 5" |./bacon playedin.csv // time echo -e "1 1\n1 2" |./bacon playedin.csv /* Some numbers: Max ActorID: 1971696 NRows: 17316773-1 Max MovieID: 1151758 */ #include <iostream> #include <ios> #include <fstream> #include <vector> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <list> #include <forward_list> #include <thread> //#include <mutex> #include <chrono> // should allow high precision timing using namespace std; //static std::mutex barrier; // BAD CODING!!! <3 // int *actor_keys = new int[1971696]; int *act2mov_actors = new int[1971696]; int *act2mov_movies = new int[17316773-1]; int *mov2act_movies = new int[1151758]; int *mov2act_actors = new int[17316773-1](); // Breadth-First Search int BFS( int *actor_keys, int *act2mov_actors, int *act2mov_movies, int *mov2act_movies, int *mov2act_actors, size_t actorid2, forward_list<size_t> current_nodes, bool *visited ) { // If BFS is called on an empty list of nodes return -1 if(current_nodes.empty()) { return -1; } // Now we want to find all neighbours of each of the current nodes forward_list<size_t> neighbours; // For all current actors for(size_t i : current_nodes) { // Get all movies // for better performance eliminate use of actor_keys while accessing the array // better use something like local IDs, i.e. number of occurance in the read list // and translate true ID to this number // this translation is only neede once when query is read for(size_t j = act2mov_actors[actor_keys[i]-1]; j < act2mov_actors[actor_keys[i]]; j++) { int movie = act2mov_movies[j]; // For each movie find all actors for(size_t k=mov2act_movies[movie-1]; k<mov2act_movies[movie]; k++){ size_t new_actor = mov2act_actors[k]; // If he has not been inspected yet add him to neighbours // maybe use a more condensed data structure if(!visited[new_actor]) { // If it is the actor2 we are looking for return 1 as distance if(new_actor==actorid2){ return 1; } visited[new_actor] = 1; neighbours.push_front(new_actor); } } } } // Now perform BFS on the neighbours we just found int count = BFS( actor_keys, act2mov_actors, act2mov_movies, mov2act_movies, mov2act_actors, actorid2, neighbours, visited); // If BFS returns -1 we pass that forward if(count == -1) { return -1; } // If BFS returns a distance we have to increase that distance by 1 return ++count; } void BFSThread(size_t thread_a1, size_t thread_a2, int *dist_thread, size_t i){ if(thread_a1 == thread_a2){ dist_thread[i] = 0; return; } bool *visited = new bool[1971696](); // Boolean to save if actor i has been visited or not // Nodes are the ones we are visiting right now - We'll want to find their neighbours with each iteration of BFS // unordered_set<size_t> current_nodes; forward_list<size_t> current_nodes; // We start with only actorid1 current_nodes.push_front(thread_a1); int dist; // Start Breadth-First-Search dist = BFS( actor_keys, act2mov_actors, act2mov_movies, mov2act_movies, mov2act_actors, thread_a2, current_nodes, visited); // Write on global dist variable // std::lock_guard<std::mutex> block_threads_until_finish_this_job(barrier); cout << "Process: " << i << " Distance: " << dist << endl; dist_thread[i] = dist; // delete unsused variable delete[] visited; } int main(int argc, char** argv) { // proper timing of actual code execution auto start_time = chrono::high_resolution_clock::now(); // Movie to actor map - Will be replaced later vector<vector<size_t>> M(1151758+1); // Open file and figre out length int handle = open(argv[1],O_RDONLY); if (handle<0) return 1; lseek(handle,0,SEEK_END); long length = lseek(handle,0,SEEK_CUR); // Map file into address space auto data = static_cast<const char*>(mmap(nullptr,length,PROT_READ,MAP_SHARED,handle,0)); auto dataLimit = data + length; /* Read file and create our datatypes We store the actor to movie relation in a CSR and movie to actor in a map */ const char* line = data; int actor_index = -1; int m1_current = 0; int last_actor = 0; for (const char* current=data;current!=dataLimit;) { const char* last=line; unsigned column=0; size_t actor=0; size_t movie=0; for (;current!=dataLimit;++current) { char c=*current; if (c==',') { last=current+1; ++column; }else if (c=='\n') { // Insert entry into Movie->Actor Map M[movie].push_back(actor); /* Check if the actor is different to the last one If yes increase actor_index and add entry to actor_keys */ if(actor != last_actor){ ++actor_index; actor_keys[actor] = actor_index; } act2mov_actors[actor_index] = m1_current+1; // Insert movie to list act2mov_movies[m1_current] = movie; // Update index ++m1_current; last_actor = actor; ++current; break; }else if (column==0) { actor=10*actor+c-'0'; }else if (column==1) { movie=10*movie+c-'0'; } } } cout << "File eingelesen" << endl; // return 0; // Create CSR for movie to actor relation int iterator = 0; for(size_t movie_id=1; movie_id<=1151758; movie_id++){ for(size_t actor : M.at(movie_id)){ mov2act_actors[iterator] = actor; //mov2act_movies[movie_id] = ++iterator; ++iterator; } // don't acces item too often mov2act_movies[movie_id] = iterator; } cout << "Created Movie to Actor!" << endl; // return 0; // While there is an input: read, store, compute size_t actorid1; size_t actorid2; vector<size_t> actor1; vector<size_t> actor2; // switch input // if there is a second argument read from this file // if not the use std::cin istream * input_stream = &cin; ifstream f; if(argc > 2) { f.open(argv[2]); input_stream = &f; cout << "Read from file: " << argv[2] << endl; } while( (*input_stream >> actorid1) && (*input_stream >> actorid2) ) { cout << "Input " << actorid1 << " : " << actorid2 << endl; actor1.push_back(actorid1); actor2.push_back(actorid2); } // while((cin >> actorid1) && (cin >> actorid2)) { // actor1.push_front(actorid1); // actor2.push_front(actorid2); // } size_t inputlen = actor1.size(); int *distance = new int[inputlen]; thread *thread_arr = new thread[inputlen]; for(int time_counter = 0; time_counter<1; ++time_counter) { //size_t inputlen = actor1.size(); //int *distance = new int[inputlen]; //thread *thread_arr = new thread[inputlen]; for(size_t i=0; i < inputlen; i++){ thread_arr[i] = thread(BFSThread, actor1[i], actor2[i], distance, i); } cout << "Threading started" << endl; for(size_t i=0; i < inputlen; i++){ thread_arr[i].join(); } } // timing auto end_time = chrono::high_resolution_clock::now(); auto passed_usecs = chrono::duration_cast<chrono::microseconds>(end_time - start_time); double elapsed_u = (double) passed_usecs.count(); double elapsed = elapsed_u / (1000.0 * 1000.0); // cout << "Passed time: " << passed_usecs.count() << " microseconds" << endl << endl; cout << endl << "Passed time: " << elapsed << " seconds" << endl << endl; for(size_t j=0; j<inputlen; j++){ cout << distance[j] << endl; } return 0; } <commit_msg>minor changes - same programm as after jonas but looked through some comments<commit_after>// Time echo -e "1 1\n1 2\n2 3\n3 4\n4 5" |./bacon playedin.csv // time echo -e "1 1\n1 2" |./bacon playedin.csv /* Some numbers: Max ActorID: 1971696 NRows: 17316773-1 Max MovieID: 1151758 */ #include <iostream> #include <ios> #include <fstream> #include <vector> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <list> #include <forward_list> #include <thread> //#include <mutex> #include <chrono> // should allow high precision timing using namespace std; //static std::mutex barrier; // BAD CODING!!! <3 // int *actor_keys = new int[1971696]; int *act2mov_actors = new int[1971696]; int *act2mov_movies = new int[17316773-1]; int *mov2act_movies = new int[1151758]; int *mov2act_actors = new int[17316773-1](); // Breadth-First Search int BFS( int *actor_keys, int *act2mov_actors, int *act2mov_movies, int *mov2act_movies, int *mov2act_actors, size_t actorid2, forward_list<size_t> current_nodes, bool *visited ) { // If BFS is called on an empty list of nodes return -1 if(current_nodes.empty()) { return -1; } // Now we want to find all neighbours of each of the current nodes forward_list<size_t> neighbours; // For all current actors for(size_t i : current_nodes) { // Get all movies // for better performance eliminate use of actor_keys while accessing the array // better use something like local IDs, i.e. number of occurance in the read list // and translate true ID to this number // this translation is only neede once when query is read for(size_t j = act2mov_actors[actor_keys[i]-1]; j < act2mov_actors[actor_keys[i]]; j++) { int movie = act2mov_movies[j]; // For each movie find all actors for(size_t k=mov2act_movies[movie-1]; k<mov2act_movies[movie]; k++){ size_t new_actor = mov2act_actors[k]; // If he has not been inspected yet add him to neighbours // maybe use a more condensed data structure if(!visited[new_actor]) { // If it is the actor2 we are looking for return 1 as distance if(new_actor==actorid2){ return 1; } visited[new_actor] = 1; neighbours.push_front(new_actor); } } } } // Now perform BFS on the neighbours we just found int count = BFS( actor_keys, act2mov_actors, act2mov_movies, mov2act_movies, mov2act_actors, actorid2, neighbours, visited); // If BFS returns -1 we pass that forward if(count == -1) { return -1; } // If BFS returns a distance we have to increase that distance by 1 return ++count; } void BFSThread(size_t thread_a1, size_t thread_a2, int *dist_thread, size_t i){ if(thread_a1 == thread_a2){ dist_thread[i] = 0; return; } bool *visited = new bool[1971696](); // Boolean to save if actor i has been visited or not // Nodes are the ones we are visiting right now - We'll want to find their neighbours with each iteration of BFS // unordered_set<size_t> current_nodes; forward_list<size_t> current_nodes; // We start with only actorid1 current_nodes.push_front(thread_a1); int dist; // Start Breadth-First-Search dist = BFS( actor_keys, act2mov_actors, act2mov_movies, mov2act_movies, mov2act_actors, thread_a2, current_nodes, visited); // Write on global dist variable // std::lock_guard<std::mutex> block_threads_until_finish_this_job(barrier); cout << "Process: " << i << " Distance: " << dist << endl; dist_thread[i] = dist; // delete unsused variable delete[] visited; } int main(int argc, char** argv) { // proper timing of actual code execution auto start_time = chrono::high_resolution_clock::now(); // Movie to actor map - Will be replaced later vector<vector<size_t>> M(1151758+1); // Open file and figre out length int handle = open(argv[1],O_RDONLY); if (handle<0) return 1; lseek(handle,0,SEEK_END); long length = lseek(handle,0,SEEK_CUR); // Map file into address space auto data = static_cast<const char*>(mmap(nullptr,length,PROT_READ,MAP_SHARED,handle,0)); auto dataLimit = data + length; /* Read file and create our datatypes We store the actor to movie relation in a CSR and movie to actor in a map */ const char* line = data; int actor_index = -1; int m1_current = 0; int last_actor = 0; for (const char* current=data;current!=dataLimit;) { const char* last=line; unsigned column=0; size_t actor=0; size_t movie=0; for (;current!=dataLimit;++current) { char c=*current; if (c==',') { last=current+1; ++column; }else if (c=='\n') { // Insert entry into Movie->Actor Map M[movie].push_back(actor); /* Check if the actor is different to the last one If yes increase actor_index and add entry to actor_keys */ if(actor != last_actor){ ++actor_index; actor_keys[actor] = actor_index; } act2mov_actors[actor_index] = m1_current+1; // Insert movie to list act2mov_movies[m1_current] = movie; // Update index ++m1_current; last_actor = actor; ++current; break; }else if (column==0) { actor=10*actor+c-'0'; }else if (column==1) { movie=10*movie+c-'0'; } } } cout << "File eingelesen" << endl; // Create CSR for movie to actor relation int iterator = 0; for(size_t movie_id=1; movie_id<=1151758; movie_id++){ for(size_t actor : M.at(movie_id)){ mov2act_actors[iterator] = actor; ++iterator; } mov2act_movies[movie_id] = iterator; } // While there is an input: read, store, compute size_t actorid1; size_t actorid2; vector<size_t> actor1; vector<size_t> actor2; // // switch input // // if there is a second argument read from this file // // if not the use std::cin // istream * input_stream = &cin; // ifstream f; // if(argc > 2) // { // f.open(argv[2]); // input_stream = &f; // cout << "Read from file: " << argv[2] << endl; // } // while( (*input_stream >> actorid1) && (*input_stream >> actorid2) ) // { // cout << "Input " << actorid1 << " : " << actorid2 << endl; // actor1.push_back(actorid1); // actor2.push_back(actorid2); // } while((cin >> actorid1) && (cin >> actorid2)) { actor1.push_back(actorid1); actor2.push_back(actorid2); } size_t inputlen = actor1.size(); int *distance = new int[inputlen]; thread *thread_arr = new thread[inputlen]; for(int time_counter = 0; time_counter<1; ++time_counter){ for(size_t i=0; i < inputlen; i++){ thread_arr[i] = thread(BFSThread, actor1[i], actor2[i], distance, i); } cout << "Threading started" << endl; for(size_t i=0; i < inputlen; i++){ thread_arr[i].join(); } } // timing auto end_time = chrono::high_resolution_clock::now(); auto passed_usecs = chrono::duration_cast<chrono::microseconds>(end_time - start_time); double elapsed_u = (double) passed_usecs.count(); double elapsed = elapsed_u / (1000.0 * 1000.0); // cout << "Passed time: " << passed_usecs.count() << " microseconds" << endl << endl; cout << endl << "Passed time: " << elapsed << " seconds" << endl << endl; for(size_t j=0; j<inputlen; j++){ cout << distance[j] << endl; } return 0; } <|endoftext|>
<commit_before>#include "dream.h" void dream_pars_default(dream_pars* p) { p->vflag = 0; p->maxEvals = 100000; p->optimAlg = 1; p->numChains = 5; p->fn = ""; p->out_fn = ""; p->appendFile = 0; p->report_interval = 1; p->diagnostics = 0; p->burnIn = 0; p->recalcLik = 0; p->noise = 0.05; p->bstar_zero = 1e-3; p->collapseOutliers = 1; p->gelmanEvals = 5000; p->loopSteps = 10; p->scaleReductionCrit = 1.01; p->deltaMax = 2; p->pCR_update = 1; p->nCR = 3; p->reenterBurnin = 0.2; p->fun = NULL; p->funPars = NULL; } void dream_pars_init_vars(dream_pars* p, size_t n) { p->nvar = n; p->nfree = n; p->varLo = (double*) calloc(n,sizeof(double)); p->varHi = (double*) calloc(n,sizeof(double)); p->varInit = (double*) calloc(n,sizeof(double)); p->varLock = (int*) calloc(n,sizeof(int)); p->varName = new string[n]; p->scale = new char[n]; } void dream_pars_free_vars(dream_pars* p) { free(p->varLo); free(p->varHi); free(p->varInit); free(p->varLock); delete[] p->varName; delete[] p->scale; p->nvar = 0; p->nfree = 0; } void dream_pars_read_json(dream_pars* p, rapidjson::Value& jpars) { // reading priors from JSON rapidjson::Value::MemberIterator m1; rapidjson::SizeType _rj; // find variable ranges rapidjson::Value::MemberIterator _d = jpars.FindMember("pars"); if (_d == jpars.MemberEnd()) throw "pars"; rapidjson::Value& d = _d->value; dream_pars_init_vars(p,d.Size()); // variables for (rapidjson::SizeType i = 0; i < d.Size(); ++i) { m1 = d[i].FindMember("name"); if (m1 != d[i].MemberEnd()) { if (! m1->value.IsString()) throw "Bad varible name."; else p->varName[i] = m1->value.GetString(); } m1 = d[i].FindMember("limits"); if (m1 != d[i].MemberEnd()) { if (! m1->value.IsArray()) throw "Bad variables limits."; if (m1->value.Size() != 2) throw "Bad variables limits."; _rj = 0; p->varLo[i] = m1->value[_rj].GetDouble(); _rj = 1; p->varHi[i] = m1->value[_rj].GetDouble(); } m1 = d[i].FindMember("lock"); if (m1 != d[i].MemberEnd()) { if (! m1->value.IsDouble()) { throw "Locked variable isn't a double."; } else { p->varLock[i] = 1; p->varHi[i] = m1->value.GetDouble(); p->varLo[i] = p->varHi[i]; p->varInit[i] = p->varHi[i]; --(p->nfree); } } m1 = d[i].FindMember("init"); if (m1 != d[i].MemberEnd()) { if (! m1->value.IsDouble()) throw "Bad initial value."; p->varInit[i] = m1->value.GetDouble(); } m1 = d[i].FindMember("scale"); if (m1 != d[i].MemberEnd()) { if (! m1->value.IsString()) throw "Bad scale."; p->scale[i] = m1->value.GetString()[0]; } else { p->scale[i] = 'n'; } } p->deltaMax = (p->nfree-1)/2; rapidjson::Value::MemberIterator dream = jpars.FindMember("dream"); if (dream == jpars.MemberEnd()) throw "No dream section in JSON."; rapidjson::Value& dv = dream->value; m1 = dv.FindMember("prefix"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsString()) throw "prefix"; p->out_fn = m1->value.GetString(); } m1 = dv.FindMember("num_chains"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "num_chains"; p->numChains = m1->value.GetInt(); } m1 = dv.FindMember("max_evals"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "max_evals"; p->maxEvals = m1->value.GetInt(); } m1 = dv.FindMember("burn_in"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "burn_in"; p->burnIn = m1->value.GetInt(); } m1 = dv.FindMember("recalc_lik"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "recalc_lik"; p->recalcLik = m1->value.GetInt(); } m1 = dv.FindMember("gelman_evals"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "gelman_evals"; p->gelmanEvals = m1->value.GetInt(); } m1 = dv.FindMember("vflag"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "vflag"; p->vflag = m1->value.GetInt(); } m1 = dv.FindMember("noise"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsDouble()) throw "noise"; p->noise = m1->value.GetDouble(); } } size_t dream_par_by_name(const dream_pars* p, string name) { size_t i = 0; while (i < p->nvar) { if (p->varName[i] == name) break; ++i; } return i; } <commit_msg>pars.<commit_after>#include "dream.h" void dream_pars_default(dream_pars* p) { p->vflag = 0; p->maxEvals = 100000; p->optimAlg = 1; p->numChains = 5; p->fn = ""; p->out_fn = ""; p->appendFile = 0; p->report_interval = 1; p->diagnostics = 0; p->burnIn = 0; p->recalcLik = 0; p->noise = 0.05; p->bstar_zero = 1e-3; p->collapseOutliers = 1; p->gelmanEvals = 5000; p->loopSteps = 10; p->scaleReductionCrit = 1.01; p->deltaMax = 2; p->pCR_update = 1; p->nCR = 3; p->reenterBurnin = 0.2; p->fun = NULL; p->funPars = NULL; } // --------------------------------------------------------------------------- void dream_pars_init_vars(dream_pars* p, size_t n) { p->nvar = n; p->nfree = n; p->varLo = (double*) calloc(n,sizeof(double)); p->varHi = (double*) calloc(n,sizeof(double)); p->varInit = (double*) calloc(n,sizeof(double)); p->varLock = (int*) calloc(n,sizeof(int)); p->varName = new string[n]; p->scale = new char[n]; } // --------------------------------------------------------------------------- void dream_pars_free_vars(dream_pars* p) { free(p->varLo); free(p->varHi); free(p->varInit); free(p->varLock); delete[] p->varName; delete[] p->scale; p->nvar = 0; p->nfree = 0; } // --------------------------------------------------------------------------- void dream_set_init(dream_pars* p, int n, const double* init, const string* name, const int* lock, const double* lo, const double* hi, const char* scale) { p->nvar = n; p->nfree = n; memcpy(p->varInit, init, n*sizeof(double)); memcpy(p->varName, name, n*sizeof(string)); memcpy(p->varLock, lock, n*sizeof(int)); memcpy(p->varLo, lo, n*sizeof(double)); memcpy(p->varHi, hi, n*sizeof(double)); memcpy(p->scale, scale, n*sizeof(char)); for (int i = 0; i < n; ++i) if (lock[i]) --(p->nfree); p->deltaMax = (p->nfree-1)/2; } // --------------------------------------------------------------------------- void dream_pars_from_json(dream_pars* p, rapidjson::Value& jpars) { // DEPRECATED !!!!!! // remove in next release... // reading priors from JSON rapidjson::Value::MemberIterator m1; rapidjson::SizeType _rj; // find variable ranges rapidjson::Value::MemberIterator _d = jpars.FindMember("pars"); if (_d == jpars.MemberEnd()) throw "pars"; size_t nshifts = 0; rapidjson::Value::MemberIterator _s = jpars.FindMember("shifts"); if (_s == jpars.MemberEnd()) throw "shifts"; else nshifts = _s->value.Size(); rapidjson::Value& d = _d->value; dream_pars_init_vars(p,(nshifts+1)*d.Size()); // variables size_t j = 0; string name = ""; double lo = 0.0; double hi = 0.0; char scale = 'n'; for (rapidjson::SizeType i = 0; i < d.Size(); ++i) { m1 = d[i].FindMember("name"); if (m1 != d[i].MemberEnd()) { if (! m1->value.IsString()) { name = ""; throw "Bad varible name."; } else { name = m1->value.GetString(); } } m1 = d[i].FindMember("limits"); if (m1 != d[i].MemberEnd()) { if (! m1->value.IsArray()) throw "Bad variables limits."; if (! m1->value.Size() == 2) throw "Bad variables limits."; _rj = 0; lo = m1->value[_rj].GetDouble(); _rj = 1; hi = m1->value[_rj].GetDouble(); } p->varName[j] = name; p->varLo[j] = lo; p->varHi[j] = hi; p->scale[i] = scale; m1 = d[i].FindMember("scale"); if (m1 != d[i].MemberEnd()) { if (! m1->value.IsString()) throw "Bad scale."; scale = m1->value.GetString()[0]; } else { } m1 = d[i].FindMember("lock"); if (m1 != d[i].MemberEnd()) { if (m1->value.IsArray()) { if (m1->value.Size() != nshifts) throw "varSize"; for (size_t k = 0; k < nshifts; ++k) { p->varName[j] = name; p->varLock[j] = 1; p->varHi[j] = m1->value[k].GetDouble(); p->varLo[j] = p->varHi[i]; p->varInit[j] = p->varHi[j]; --(p->nfree); ++j; } } else if (m1->value.IsDouble()) { p->varName[j] = name; p->varLock[j] = 1; p->varHi[j] = m1->value.GetDouble(); p->varLo[j] = p->varHi[j]; p->varInit[j] = p->varHi[j]; --(p->nfree); ++j; } else { throw "Locked variable isn't a double or an array."; } } else { m1 = d[i].FindMember("init"); p->varInit[i] = m1->value.GetDouble(); if (m1->value.IsArray()) { if (m1->value.Size() != nshifts) throw "varSize"; for (size_t k = 0; k < nshifts; ++k) { p->varName[j] = name; p->varLock[j] = 0; p->varHi[j] = hi; p->varLo[j] = lo; p->varInit[j] = m1->value[k].GetDouble(); ++j; } } else if (m1->value.IsDouble()) { p->varName[j] = name; p->varLock[j] = 0; p->varHi[j] = hi; p->varLo[j] = lo; p->varInit[j] = m1->value.GetDouble(); ++j; } else { throw "Init variable isn't a double or an array."; } } } p->deltaMax = (p->nfree-1)/2; } // --------------------------------------------------------------------------- void dream_pars_read_json(dream_pars* p, rapidjson::Value& jpars) { // reading priors from JSON rapidjson::Value::MemberIterator m1; rapidjson::SizeType _rj; rapidjson::Value::MemberIterator dream = jpars.FindMember("dream"); if (dream == jpars.MemberEnd()) throw "No dream section in JSON."; rapidjson::Value& dv = dream->value; m1 = dv.FindMember("prefix"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsString()) throw "prefix"; p->out_fn = m1->value.GetString(); } m1 = dv.FindMember("num_chains"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "num_chains"; p->numChains = m1->value.GetInt(); } m1 = dv.FindMember("max_evals"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "max_evals"; p->maxEvals = m1->value.GetInt(); } m1 = dv.FindMember("burn_in"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "burn_in"; p->burnIn = m1->value.GetInt(); } m1 = dv.FindMember("recalc_lik"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "recalc_lik"; p->recalcLik = m1->value.GetInt(); } m1 = dv.FindMember("gelman_evals"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "gelman_evals"; p->gelmanEvals = m1->value.GetInt(); } m1 = dv.FindMember("vflag"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsInt()) throw "vflag"; p->vflag = m1->value.GetInt(); } m1 = dv.FindMember("noise"); if (m1 != dv.MemberEnd()) { if (! m1->value.IsDouble()) throw "noise"; p->noise = m1->value.GetDouble(); } } // --------------------------------------------------------------------------- size_t dream_par_by_name(const dream_pars* p, string name) { size_t i = 0; while (i < p->nvar) { if (p->varName[i] == name) break; ++i; } return i; } <|endoftext|>
<commit_before><commit_msg>fix sfx2 with Library_merged<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTimerLog.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkTimerLog - Maintains timing table for performance analysis // .SECTION Description // vtkTimerLog contains walltime and cputime measurements associated // with a given event. These results can be later analyzed when // "dumping out" the table. // // In addition, vtkTimerLog allows the user to simply get the current // time, and to start/stop a simple timer separate from the timing // table logging. #include "vtkTimerLog.h" #ifndef _WIN32 #include <limits.h> // for CLK_TCK #endif // initialze the class variables int vtkTimerLog::MaxEntries = 100; int vtkTimerLog::NextEntry = 0; int vtkTimerLog::WrapFlag = 0; vtkTimerLogEntry *vtkTimerLog::TimerLog = NULL; #ifdef CLK_TCK int vtkTimerLog::TicksPerSecond = CLK_TCK; #else int vtkTimerLog::TicksPerSecond = 60; #endif #ifdef _WIN32 timeb vtkTimerLog::FirstWallTime; timeb vtkTimerLog::CurrentWallTime; #else timeval vtkTimerLog::FirstWallTime; timeval vtkTimerLog::CurrentWallTime; tms vtkTimerLog::FirstCpuTicks; tms vtkTimerLog::CurrentCpuTicks; #endif // Description: // Allocate timing table with MaxEntries elements. void vtkTimerLog::AllocateLog() { if (vtkTimerLog::TimerLog != NULL) delete [] vtkTimerLog::TimerLog; vtkTimerLog::TimerLog = new vtkTimerLogEntry[vtkTimerLog::MaxEntries]; } // Description: // Clear the timing table. walltime and cputime will also be set // to zero when the first new event is recorded. void vtkTimerLog::ResetLog() { vtkTimerLog::WrapFlag = 0; vtkTimerLog::NextEntry = 0; // may want to free TimerLog to force realloc so // that user can resize the table by changing MaxEntries. } // Description: // Record a timing event. The event is represented by a formatted // string. void vtkTimerLog::FormatAndMarkEvent(char *format, ...) { static char event[4096]; va_list var_args; va_start(var_args, format); vsprintf(event, format, var_args); va_end(var_args); vtkTimerLog::MarkEvent(event); } // Description: // Record a timing event and capture walltime and cputicks. void vtkTimerLog::MarkEvent(char *event) { int strsize; double time_diff; int ticks_diff; strsize = (strlen(event)) > VTK_LOG_EVENT_LENGTH - 1 ? VTK_LOG_EVENT_LENGTH-1 : strlen(event); // If this the first event we're recording, allocate the // internal timing table and initialize WallTime and CpuTicks // for this first event to zero. if (vtkTimerLog::NextEntry == 0 && ! vtkTimerLog::WrapFlag) { if (vtkTimerLog::TimerLog == NULL) { vtkTimerLog::AllocateLog(); } #ifdef _WIN32 ftime( &(vtkTimerLog::FirstWallTime) ); #else gettimeofday( &(vtkTimerLog::FirstWallTime), NULL ); times(&FirstCpuTicks); #endif TimerLog[0].WallTime = 0.0; TimerLog[0].CpuTicks = 0; strncpy(TimerLog[0].Event, event, strsize); TimerLog[0].Event[strsize] = '\0'; NextEntry = 1; return; } #ifdef _WIN32 static double scale = 1.0/1000.0; ftime( &(vtkTimerLog::CurrentWallTime) ); time_diff = vtkTimerLog::CurrentWallTime.time - vtkTimerLog::FirstWallTime.time; time_diff += (vtkTimerLog::CurrentWallTime.millitm - vtkTimerLog::FirstWallTime.millitm) * scale; ticks_diff = 0; #else static double scale = 1.0/1000000.0; gettimeofday( &(vtkTimerLog::CurrentWallTime), NULL ); time_diff = vtkTimerLog::CurrentWallTime.tv_sec - vtkTimerLog::FirstWallTime.tv_sec; time_diff += (vtkTimerLog::CurrentWallTime.tv_usec - vtkTimerLog::FirstWallTime.tv_usec) * scale; times(&CurrentCpuTicks); ticks_diff = (CurrentCpuTicks.tms_utime + CurrentCpuTicks.tms_stime) - (FirstCpuTicks.tms_utime + FirstCpuTicks.tms_stime); #endif TimerLog[NextEntry].WallTime = (float)time_diff; TimerLog[NextEntry].CpuTicks = ticks_diff; strncpy(TimerLog[NextEntry].Event, event, strsize); TimerLog[NextEntry].Event[strsize] = '\0'; NextEntry++; if (NextEntry == MaxEntries) { NextEntry = 0; WrapFlag = 1; } } // Description: // Write the timing table out to a file. Calculate some helpful // statistics (deltas and percentages) in the process. void vtkTimerLog::DumpLog(char *filename) { ofstream os(filename); int i; os << " Entry Wall Time (sec) Delta CPU Time (sec) Delta %CPU Event\n"; os << "----------------------------------------------------------------------\n"; if ( WrapFlag ) { DumpEntry(os, 0, TimerLog[NextEntry].WallTime, 0, TimerLog[NextEntry].CpuTicks, 0, TimerLog[NextEntry].Event); for (i=NextEntry+1; i<MaxEntries; i++) { DumpEntry(os, i-NextEntry, TimerLog[i].WallTime, TimerLog[i].WallTime - TimerLog[i-1].WallTime, TimerLog[i].CpuTicks, TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks, TimerLog[i].Event); } DumpEntry(os, MaxEntries-NextEntry, TimerLog[0].WallTime, TimerLog[0].WallTime - TimerLog[MaxEntries-1].WallTime, TimerLog[0].CpuTicks, TimerLog[0].CpuTicks - TimerLog[MaxEntries-1].CpuTicks, TimerLog[0].Event); for (i=1; i<NextEntry; i++) { DumpEntry(os, MaxEntries-NextEntry+i, TimerLog[i].WallTime, TimerLog[i].WallTime - TimerLog[i-1].WallTime, TimerLog[i].CpuTicks, TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks, TimerLog[i].Event); } } else { DumpEntry(os, 0, TimerLog[0].WallTime, 0, TimerLog[0].CpuTicks, 0, TimerLog[0].Event); for (i=1; i<NextEntry; i++) { DumpEntry(os, i, TimerLog[i].WallTime, TimerLog[i].WallTime - TimerLog[i-1].WallTime, TimerLog[i].CpuTicks, TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks, TimerLog[i].Event); } } os.close(); } // Description: // Print method for vtkTimerLog. void vtkTimerLog::PrintSelf(ostream& os, vtkIndent indent) { int i; vtkObject::PrintSelf(os, indent); os << indent << "MaxEntries: " << vtkTimerLog::MaxEntries << "\n"; os << indent << "NextEntry: " << vtkTimerLog::NextEntry << "\n"; os << indent << "WrapFlag: " << vtkTimerLog::WrapFlag << "\n"; os << indent << "TicksPerSecond: " << vtkTimerLog::TicksPerSecond << "\n"; os << "\n"; os << indent << "Entry \tWall Time\tCpuTicks\tEvent\n"; os << indent << "----------------------------------------------\n"; if ( WrapFlag ) { for (i=NextEntry; i<MaxEntries; i++) { os << indent << i << "\t\t" << TimerLog[i].WallTime << "\t\t" << TimerLog[i].CpuTicks << "\t\t" << TimerLog[i].Event << "\n"; } } for (i=0; i<NextEntry; i++) { os << indent << i << "\t\t" << TimerLog[i].WallTime << "\t\t" << TimerLog[i].CpuTicks << "\t\t" << TimerLog[i].Event << "\n"; } os << "\n" << indent << "StartTime: " << this->StartTime << "\n"; os << indent << "WrapFlag: " << vtkTimerLog::WrapFlag << "\n"; } // Methods to support simple timer functionality, separate from // timer table logging. // Description: // Returns the elapsed number of seconds since January 1, 1970. This // is also called Universal Coordinated Time. double vtkTimerLog::GetCurrentTime() { double currentTimeInSeconds; #ifdef _WIN32 timeb CurrentTime; static double scale = 1.0/1000.0; ftime( &CurrentTime ); currentTimeInSeconds = CurrentTime.time + scale * CurrentTime.millitm; #else timeval CurrentTime; static double scale = 1.0/1000000.0; gettimeofday( &CurrentTime, NULL ); currentTimeInSeconds = CurrentTime.tv_sec + scale * CurrentTime.tv_usec; #endif return (currentTimeInSeconds); } // Description: // Set the StartTime to the current time. Used with GetElapsedTime(). void vtkTimerLog::StartTimer() { this->StartTime = vtkTimerLog::GetCurrentTime(); } // Description: // Sets EndTime to the current time. Used with GetElapsedTime(). void vtkTimerLog::StopTimer() { this->EndTime = vtkTimerLog::GetCurrentTime(); } // Description: // Returns the difference between StartTime and EndTime as // a floating point value indicating the elapsed time in seconds. double vtkTimerLog::GetElapsedTime() { return (this->EndTime - this->StartTime); } void vtkTimerLog::DumpEntry(ostream& os, int index, float time, float deltatime, int tick, int deltatick, char *event) { os << index << " " << time << " " << deltatime << " " << (float)tick/TicksPerSecond << " " << (float)deltatick/TicksPerSecond << " "; if (deltatime == 0.0) os << "0.0 "; else os << 100.0*deltatick/TicksPerSecond/deltatime << " "; os << event << "\n"; } void vtkTimerLog::SetMaxEntries(int a) { vtkTimerLog::MaxEntries = a; } int vtkTimerLog::GetMaxEntries() { return vtkTimerLog::MaxEntries; } <commit_msg>ENH: added :: scope to ftime calls<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTimerLog.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkTimerLog - Maintains timing table for performance analysis // .SECTION Description // vtkTimerLog contains walltime and cputime measurements associated // with a given event. These results can be later analyzed when // "dumping out" the table. // // In addition, vtkTimerLog allows the user to simply get the current // time, and to start/stop a simple timer separate from the timing // table logging. #include "vtkTimerLog.h" #ifndef _WIN32 #include <limits.h> // for CLK_TCK #endif // initialze the class variables int vtkTimerLog::MaxEntries = 100; int vtkTimerLog::NextEntry = 0; int vtkTimerLog::WrapFlag = 0; vtkTimerLogEntry *vtkTimerLog::TimerLog = NULL; #ifdef CLK_TCK int vtkTimerLog::TicksPerSecond = CLK_TCK; #else int vtkTimerLog::TicksPerSecond = 60; #endif #ifdef _WIN32 timeb vtkTimerLog::FirstWallTime; timeb vtkTimerLog::CurrentWallTime; #else timeval vtkTimerLog::FirstWallTime; timeval vtkTimerLog::CurrentWallTime; tms vtkTimerLog::FirstCpuTicks; tms vtkTimerLog::CurrentCpuTicks; #endif // Description: // Allocate timing table with MaxEntries elements. void vtkTimerLog::AllocateLog() { if (vtkTimerLog::TimerLog != NULL) delete [] vtkTimerLog::TimerLog; vtkTimerLog::TimerLog = new vtkTimerLogEntry[vtkTimerLog::MaxEntries]; } // Description: // Clear the timing table. walltime and cputime will also be set // to zero when the first new event is recorded. void vtkTimerLog::ResetLog() { vtkTimerLog::WrapFlag = 0; vtkTimerLog::NextEntry = 0; // may want to free TimerLog to force realloc so // that user can resize the table by changing MaxEntries. } // Description: // Record a timing event. The event is represented by a formatted // string. void vtkTimerLog::FormatAndMarkEvent(char *format, ...) { static char event[4096]; va_list var_args; va_start(var_args, format); vsprintf(event, format, var_args); va_end(var_args); vtkTimerLog::MarkEvent(event); } // Description: // Record a timing event and capture walltime and cputicks. void vtkTimerLog::MarkEvent(char *event) { int strsize; double time_diff; int ticks_diff; strsize = (strlen(event)) > VTK_LOG_EVENT_LENGTH - 1 ? VTK_LOG_EVENT_LENGTH-1 : strlen(event); // If this the first event we're recording, allocate the // internal timing table and initialize WallTime and CpuTicks // for this first event to zero. if (vtkTimerLog::NextEntry == 0 && ! vtkTimerLog::WrapFlag) { if (vtkTimerLog::TimerLog == NULL) { vtkTimerLog::AllocateLog(); } #ifdef _WIN32 ::ftime( &(vtkTimerLog::FirstWallTime) ); #else gettimeofday( &(vtkTimerLog::FirstWallTime), NULL ); times(&FirstCpuTicks); #endif TimerLog[0].WallTime = 0.0; TimerLog[0].CpuTicks = 0; strncpy(TimerLog[0].Event, event, strsize); TimerLog[0].Event[strsize] = '\0'; NextEntry = 1; return; } #ifdef _WIN32 static double scale = 1.0/1000.0; ::ftime( &(vtkTimerLog::CurrentWallTime) ); time_diff = vtkTimerLog::CurrentWallTime.time - vtkTimerLog::FirstWallTime.time; time_diff += (vtkTimerLog::CurrentWallTime.millitm - vtkTimerLog::FirstWallTime.millitm) * scale; ticks_diff = 0; #else static double scale = 1.0/1000000.0; gettimeofday( &(vtkTimerLog::CurrentWallTime), NULL ); time_diff = vtkTimerLog::CurrentWallTime.tv_sec - vtkTimerLog::FirstWallTime.tv_sec; time_diff += (vtkTimerLog::CurrentWallTime.tv_usec - vtkTimerLog::FirstWallTime.tv_usec) * scale; times(&CurrentCpuTicks); ticks_diff = (CurrentCpuTicks.tms_utime + CurrentCpuTicks.tms_stime) - (FirstCpuTicks.tms_utime + FirstCpuTicks.tms_stime); #endif TimerLog[NextEntry].WallTime = (float)time_diff; TimerLog[NextEntry].CpuTicks = ticks_diff; strncpy(TimerLog[NextEntry].Event, event, strsize); TimerLog[NextEntry].Event[strsize] = '\0'; NextEntry++; if (NextEntry == MaxEntries) { NextEntry = 0; WrapFlag = 1; } } // Description: // Write the timing table out to a file. Calculate some helpful // statistics (deltas and percentages) in the process. void vtkTimerLog::DumpLog(char *filename) { ofstream os(filename); int i; os << " Entry Wall Time (sec) Delta CPU Time (sec) Delta %CPU Event\n"; os << "----------------------------------------------------------------------\n"; if ( WrapFlag ) { DumpEntry(os, 0, TimerLog[NextEntry].WallTime, 0, TimerLog[NextEntry].CpuTicks, 0, TimerLog[NextEntry].Event); for (i=NextEntry+1; i<MaxEntries; i++) { DumpEntry(os, i-NextEntry, TimerLog[i].WallTime, TimerLog[i].WallTime - TimerLog[i-1].WallTime, TimerLog[i].CpuTicks, TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks, TimerLog[i].Event); } DumpEntry(os, MaxEntries-NextEntry, TimerLog[0].WallTime, TimerLog[0].WallTime - TimerLog[MaxEntries-1].WallTime, TimerLog[0].CpuTicks, TimerLog[0].CpuTicks - TimerLog[MaxEntries-1].CpuTicks, TimerLog[0].Event); for (i=1; i<NextEntry; i++) { DumpEntry(os, MaxEntries-NextEntry+i, TimerLog[i].WallTime, TimerLog[i].WallTime - TimerLog[i-1].WallTime, TimerLog[i].CpuTicks, TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks, TimerLog[i].Event); } } else { DumpEntry(os, 0, TimerLog[0].WallTime, 0, TimerLog[0].CpuTicks, 0, TimerLog[0].Event); for (i=1; i<NextEntry; i++) { DumpEntry(os, i, TimerLog[i].WallTime, TimerLog[i].WallTime - TimerLog[i-1].WallTime, TimerLog[i].CpuTicks, TimerLog[i].CpuTicks - TimerLog[i-1].CpuTicks, TimerLog[i].Event); } } os.close(); } // Description: // Print method for vtkTimerLog. void vtkTimerLog::PrintSelf(ostream& os, vtkIndent indent) { int i; vtkObject::PrintSelf(os, indent); os << indent << "MaxEntries: " << vtkTimerLog::MaxEntries << "\n"; os << indent << "NextEntry: " << vtkTimerLog::NextEntry << "\n"; os << indent << "WrapFlag: " << vtkTimerLog::WrapFlag << "\n"; os << indent << "TicksPerSecond: " << vtkTimerLog::TicksPerSecond << "\n"; os << "\n"; os << indent << "Entry \tWall Time\tCpuTicks\tEvent\n"; os << indent << "----------------------------------------------\n"; if ( WrapFlag ) { for (i=NextEntry; i<MaxEntries; i++) { os << indent << i << "\t\t" << TimerLog[i].WallTime << "\t\t" << TimerLog[i].CpuTicks << "\t\t" << TimerLog[i].Event << "\n"; } } for (i=0; i<NextEntry; i++) { os << indent << i << "\t\t" << TimerLog[i].WallTime << "\t\t" << TimerLog[i].CpuTicks << "\t\t" << TimerLog[i].Event << "\n"; } os << "\n" << indent << "StartTime: " << this->StartTime << "\n"; os << indent << "WrapFlag: " << vtkTimerLog::WrapFlag << "\n"; } // Methods to support simple timer functionality, separate from // timer table logging. // Description: // Returns the elapsed number of seconds since January 1, 1970. This // is also called Universal Coordinated Time. double vtkTimerLog::GetCurrentTime() { double currentTimeInSeconds; #ifdef _WIN32 timeb CurrentTime; static double scale = 1.0/1000.0; ::ftime( &CurrentTime ); currentTimeInSeconds = CurrentTime.time + scale * CurrentTime.millitm; #else timeval CurrentTime; static double scale = 1.0/1000000.0; gettimeofday( &CurrentTime, NULL ); currentTimeInSeconds = CurrentTime.tv_sec + scale * CurrentTime.tv_usec; #endif return (currentTimeInSeconds); } // Description: // Set the StartTime to the current time. Used with GetElapsedTime(). void vtkTimerLog::StartTimer() { this->StartTime = vtkTimerLog::GetCurrentTime(); } // Description: // Sets EndTime to the current time. Used with GetElapsedTime(). void vtkTimerLog::StopTimer() { this->EndTime = vtkTimerLog::GetCurrentTime(); } // Description: // Returns the difference between StartTime and EndTime as // a floating point value indicating the elapsed time in seconds. double vtkTimerLog::GetElapsedTime() { return (this->EndTime - this->StartTime); } void vtkTimerLog::DumpEntry(ostream& os, int index, float time, float deltatime, int tick, int deltatick, char *event) { os << index << " " << time << " " << deltatime << " " << (float)tick/TicksPerSecond << " " << (float)deltatick/TicksPerSecond << " "; if (deltatime == 0.0) os << "0.0 "; else os << 100.0*deltatick/TicksPerSecond/deltatime << " "; os << event << "\n"; } void vtkTimerLog::SetMaxEntries(int a) { vtkTimerLog::MaxEntries = a; } int vtkTimerLog::GetMaxEntries() { return vtkTimerLog::MaxEntries; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef SPIRIT_LEXER_H #define SPIRIT_LEXER_H #include <fstream> #include <string> #include <utility> #include <stack> #include <boost/spirit/include/classic_position_iterator.hpp> #include <boost/spirit/include/lex_lexertl.hpp> #include <boost/spirit/include/classic_core.hpp> #include <boost/spirit/include/classic_functor_parser.hpp> #include <boost/spirit/include/classic_attribute.hpp> #include <boost/spirit/include/classic_symbols.hpp> namespace eddic { namespace lexer { namespace spirit = boost::spirit; namespace lex = boost::spirit::lex; /*! * \class SimpleLexer * \brief The EDDI lexer. * * This class is used to do lexical analysis on an EDDI source file. This file is based on a Boost Spirit Lexer. It's * used by the parser to parse a source file. */ template<typename L> class SpiritLexer : public lex::lexer<L> { public: SpiritLexer() { //Define keywords for_ = "for"; while_ = "while"; do_ = "do"; if_ = "if"; else_ = "else"; false_ = "false"; true_ = "true"; from_ = "from"; to_ = "to"; foreach_ = "foreach"; in_ = "in"; return_ = "return"; const_ = "const"; include = "include"; identifier = "[a-zA-Z_]?[a-zA-Z0-9_]+"; float_ = "[0-9]+\".\"[0-9]+"; integer = "[0-9]+"; litteral = "\\\"[^\\\"]*\\\""; left_parenth = '('; right_parenth = ')'; left_brace = '{'; right_brace = '}'; left_bracket = '['; right_bracket = ']'; stop = ';'; comma = ','; /* Assignment operators */ swap = "<=>"; assign = '='; /* compound assignment operators */ compound_add = "\\+="; compound_sub = "-="; compound_mul = "\\*="; compound_div = "\\/="; compound_mod = "%="; /* Math operators */ addition = '+'; subtraction = '-'; multiplication = '*'; division = '/'; modulo = '%'; /* Suffix and prefix math operators */ increment = "\\+\\+"; decrement = "--"; /* Logical operators */ and_ = "\\&\\&"; or_ = "\\|\\|"; /* Relational operators */ equals = "=="; not_equals = "!="; greater = ">"; less = "<"; greater_equals = ">="; less_equals = "<="; whitespaces = "[ \\t\\n]+"; multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/"; singleline_comment = "\\/\\/[^\n]*"; //Ignore whitespaces this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore]; this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket; this->self += comma | stop; this->self += assign | swap; this->self += compound_add | compound_sub | compound_mul | compound_div | compound_mod; this->self += addition | subtraction | multiplication | division | modulo; this->self += increment | decrement; this->self += and_ | or_; this->self += for_ | do_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include; this->self += equals | not_equals | greater_equals | less_equals | greater | less ; this->self += float_ | integer | identifier | litteral; //Ignore comments this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore]; this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore]; } typedef lex::token_def<lex::omit> ConsumedToken; typedef lex::token_def<std::string> StringToken; typedef lex::token_def<int> IntegerToken; typedef lex::token_def<char> CharToken; typedef lex::token_def<double> FloatToken; StringToken identifier, litteral; IntegerToken integer; FloatToken float_; CharToken addition, subtraction, multiplication, division, modulo; StringToken increment, decrement; StringToken compound_add, compound_sub, compound_mul, compound_div, compound_mod; StringToken equals, not_equals, greater, less, greater_equals, less_equals; StringToken and_, or_; ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket; ConsumedToken stop, comma; ConsumedToken assign, swap; //Keywords ConsumedToken if_, else_, for_, while_, do_, from_, in_, to_, foreach_, return_; ConsumedToken true_, false_; ConsumedToken const_, include; //Ignored tokens ConsumedToken whitespaces, singleline_comment, multiline_comment; }; typedef std::string::iterator base_iterator_type; typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type; typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok; typedef lex::lexertl::actor_lexer<Tok> lexer_type; //Typedef for the parsers typedef lexer::lexer_type::iterator_type Iterator; typedef lexer::SpiritLexer<lexer::lexer_type> Lexer; } //end of lexer } //end of eddic #endif <commit_msg>Add the float suffix the lexer<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef SPIRIT_LEXER_H #define SPIRIT_LEXER_H #include <fstream> #include <string> #include <utility> #include <stack> #include <boost/spirit/include/classic_position_iterator.hpp> #include <boost/spirit/include/lex_lexertl.hpp> #include <boost/spirit/include/classic_core.hpp> #include <boost/spirit/include/classic_functor_parser.hpp> #include <boost/spirit/include/classic_attribute.hpp> #include <boost/spirit/include/classic_symbols.hpp> namespace eddic { namespace lexer { namespace spirit = boost::spirit; namespace lex = boost::spirit::lex; /*! * \class SimpleLexer * \brief The EDDI lexer. * * This class is used to do lexical analysis on an EDDI source file. This file is based on a Boost Spirit Lexer. It's * used by the parser to parse a source file. */ template<typename L> class SpiritLexer : public lex::lexer<L> { public: SpiritLexer() { /* keywords */ for_ = "for"; while_ = "while"; do_ = "do"; if_ = "if"; else_ = "else"; false_ = "false"; true_ = "true"; from_ = "from"; to_ = "to"; foreach_ = "foreach"; in_ = "in"; return_ = "return"; const_ = "const"; include = "include"; /* Raw values */ identifier = "[a-zA-Z_]?[a-zA-Z0-9_]+"; float_ = "[0-9]+\".\"[0-9]+"; integer = "[0-9]+"; litteral = "\\\"[^\\\"]*\\\""; /* Suffixes */ float_suffix = "f"; /* Constructs */ left_parenth = '('; right_parenth = ')'; left_brace = '{'; right_brace = '}'; left_bracket = '['; right_bracket = ']'; stop = ';'; comma = ','; /* Assignment operators */ swap = "<=>"; assign = '='; /* compound assignment operators */ compound_add = "\\+="; compound_sub = "-="; compound_mul = "\\*="; compound_div = "\\/="; compound_mod = "%="; /* Math operators */ addition = '+'; subtraction = '-'; multiplication = '*'; division = '/'; modulo = '%'; /* Suffix and prefix math operators */ increment = "\\+\\+"; decrement = "--"; /* Logical operators */ and_ = "\\&\\&"; or_ = "\\|\\|"; /* Relational operators */ equals = "=="; not_equals = "!="; greater = ">"; less = "<"; greater_equals = ">="; less_equals = "<="; whitespaces = "[ \\t\\n]+"; multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/"; singleline_comment = "\\/\\/[^\n]*"; //Ignore whitespaces this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore]; this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket; this->self += comma | stop; this->self += assign | swap; this->self += compound_add | compound_sub | compound_mul | compound_div | compound_mod; this->self += addition | subtraction | multiplication | division | modulo; this->self += increment | decrement; this->self += and_ | or_; this->self += for_ | do_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include; this->self += equals | not_equals | greater_equals | less_equals | greater | less ; this->self += float_ | integer | identifier | litteral; this->self += float_suffix; //Ignore comments this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore]; this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore]; } typedef lex::token_def<lex::omit> ConsumedToken; typedef lex::token_def<std::string> StringToken; typedef lex::token_def<int> IntegerToken; typedef lex::token_def<char> CharToken; typedef lex::token_def<double> FloatToken; StringToken identifier, litteral; IntegerToken integer; FloatToken float_; CharToken addition, subtraction, multiplication, division, modulo; StringToken increment, decrement; StringToken compound_add, compound_sub, compound_mul, compound_div, compound_mod; StringToken equals, not_equals, greater, less, greater_equals, less_equals; StringToken and_, or_; StringToken float_suffix; ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket; ConsumedToken stop, comma; ConsumedToken assign, swap; //Keywords ConsumedToken if_, else_, for_, while_, do_, from_, in_, to_, foreach_, return_; ConsumedToken true_, false_; ConsumedToken const_, include; //Ignored tokens ConsumedToken whitespaces, singleline_comment, multiline_comment; }; typedef std::string::iterator base_iterator_type; typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type; typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok; typedef lex::lexertl::actor_lexer<Tok> lexer_type; //Typedef for the parsers typedef lexer::lexer_type::iterator_type Iterator; typedef lexer::SpiritLexer<lexer::lexer_type> Lexer; } //end of lexer } //end of eddic #endif <|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_ALLOCA #include "libtorrent/config.hpp" #ifdef TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))); #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))); #endif #endif <commit_msg>remove unnecessary semicolon<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_ALLOCA #include "libtorrent/config.hpp" #ifdef TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))) #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #endif #endif <|endoftext|>
<commit_before>#include "FCStdAfx.h" #include "Quad_Multirotor_Motor_Mixer.h" #include "uav_properties/Quad_Multirotor_Properties.h" #include "physics/constants.h" #include "hal.def.h" namespace silk { namespace node { Quad_Multirotor_Motor_Mixer::Quad_Multirotor_Motor_Mixer(HAL& hal) : m_hal(hal) , m_descriptor(new hal::Quad_Multirotor_Motor_Mixer_Descriptor()) , m_config(new hal::Quad_Multirotor_Motor_Mixer_Config()) { } ts::Result<void> Quad_Multirotor_Motor_Mixer::init(hal::INode_Descriptor const& descriptor) { QLOG_TOPIC("Quad_Multirotor_Motor_Mixer::init"); auto specialized = dynamic_cast<hal::Quad_Multirotor_Motor_Mixer_Descriptor const*>(&descriptor); if (!specialized) { return make_error("Wrong descriptor type"); } *m_descriptor = *specialized; return init(); } ts::Result<void> Quad_Multirotor_Motor_Mixer::init() { std::shared_ptr<const Quad_Multirotor_Properties> multirotor_properties = m_hal.get_specialized_uav_properties<Quad_Multirotor_Properties>(); if (!multirotor_properties) { return make_error("No quad multirotor properties found"); } if (multirotor_properties->get_motors().size() != 4) { return make_error("Invalid quad multirotor properties found - motor count != 4"); } const std::vector<Quad_Multirotor_Properties::Motor>& motors = multirotor_properties->get_motors(); for (Quad_Multirotor_Properties::Motor const& mc: motors) { if (math::dot(mc.thrust_vector, math::vec3f(0, 0, 1.f)) < 0.9999f) { return make_error("Bad quad multirotor properties: motors have wrong thrust vectors"); } } if (!math::equals(motors[0].position, -motors[2].position, 0.99f) || motors[0].clockwise != motors[2].clockwise) { return make_error("Bad quad multirotor properties: motors 0 and 2 are not antipodal"); } if (!math::equals(motors[1].position, -motors[3].position, 0.99f) || motors[1].clockwise != motors[3].clockwise) { return make_error("Bad quad multirotor properties: motors 1 and 3 are not antipodal"); } for (std::shared_ptr<Stream>& os: m_outputs) { os = std::make_shared<Stream>(); os->rate = m_descriptor->get_rate(); } return ts::success; } ts::Result<void> Quad_Multirotor_Motor_Mixer::start(Clock::time_point tp) { //TODO - use an basic_output_stream instead of the ad-hoc streams return ts::success; } auto Quad_Multirotor_Motor_Mixer::get_inputs() const -> std::vector<Input> { std::vector<Input> inputs = {{ { stream::ITorque::TYPE, m_descriptor->get_rate(), "torque", m_accumulator.get_stream_path(0) }, { stream::IFloat::TYPE, m_descriptor->get_rate(), "collective_thrust", m_accumulator.get_stream_path(1) } }}; return inputs; } auto Quad_Multirotor_Motor_Mixer::get_outputs() const -> std::vector<Output> { if (m_outputs.size() == 0 || m_outputs[0] == nullptr) { return std::vector<Output>(); } std::vector<Output> outputs(m_outputs.size()); for (size_t i = 0; i < m_outputs.size(); i++) { outputs[i].name = q::util::format<std::string>("throttle_{}", i); outputs[i].stream = m_outputs[i]; } return outputs; } void Quad_Multirotor_Motor_Mixer::process() { QLOG_TOPIC("Quad_Multirotor_Motor_Mixer::process"); for (std::shared_ptr<Stream>& os: m_outputs) { os->samples.clear(); } std::shared_ptr<const Quad_Multirotor_Properties> multirotor_properties = m_hal.get_specialized_uav_properties<Quad_Multirotor_Properties>(); if (!multirotor_properties) { return; } if (multirotor_properties->get_motors().size() != m_outputs.size()) { QLOGE("Motor count changed since initialization!!!! Case not handled"); return; } m_accumulator.process([this, &multirotor_properties](stream::ITorque::Sample const& t_sample, stream::IFloat::Sample const& f_sample) { bool is_healthy = false; if (t_sample.is_healthy & f_sample.is_healthy) { compute_throttles(*multirotor_properties, f_sample.value, t_sample.value); is_healthy = true; } for (std::shared_ptr<Stream> output: m_outputs) { Stream::Sample& sample = output->last_sample; sample.value = output->throttle; sample.is_healthy = is_healthy; output->samples.push_back(sample); } }); } static float compute_throttle_from_thrust(float max_thrust, float thrust) { if (math::is_zero(max_thrust, math::epsilon<float>())) { return 0; } float ratio = thrust / max_thrust; //thrust increases approximately with throttle^2 float throttle = math::sqrt<float, math::safe>(ratio); return throttle; } static float compute_thrust_from_throttle(float max_thrust, float throttle) { float thrust = math::square(math::clamp(throttle, 0.f, 1.f)) * max_thrust; return thrust; } void Quad_Multirotor_Motor_Mixer::compute_throttles(Quad_Multirotor_Properties const& multirotor_properties, stream::IFloat::Value const& collective_thrust, stream::ITorque::Value const& _target) { //T = r X F //T = |r| * |F| * sin(a) // T - torque // r - position of the force relative to the center of mass // F - force applied // a - angle between the force vector and the position vector (usually 90 degrees) if (collective_thrust < std::numeric_limits<float>::epsilon() * 10.f) { for (size_t i = 0; i < m_outputs.size(); i++) { Stream& out = *m_outputs[i]; out.thrust = 0.f; out.throttle = 0.f; } return; } float motor_count = static_cast<float>(m_outputs.size()); float collective_thrust_per_motor = collective_thrust / motor_count; //min and max allowed thrusts per motor float max_thrust_per_motor = multirotor_properties.get_motor_thrust(); float min_thrust_per_motor = compute_thrust_from_throttle(m_config->get_armed_min_throttle(), max_thrust_per_motor); //the min collective thrust per motor is - at minimum - twice the min thrust per motor. //this is to that even at minimum, there is still some dynamic range left float min_collective_thrust_per_motor = math::max(collective_thrust_per_motor, min_thrust_per_motor * 2.f); collective_thrust_per_motor = math::max(collective_thrust_per_motor, min_collective_thrust_per_motor); //this is half the dynamic range, computed so that there is no spill either above max or below min float max_half_dynamic_range = math::min( collective_thrust_per_motor - min_thrust_per_motor, //how much space we have between the collective thrust and the min thrust (max_thrust_per_motor - min_thrust_per_motor) / 2.f //the middle thrust point ); //split the target torque in XY (roll, pitch) and Z (yaw) stream::ITorque::Value xy_target = stream::ITorque::Value(_target.x, _target.y, 0.f); stream::ITorque::Value half_xy_target = xy_target / 2.f; //for xy, the quad has 2 halves participating float z_target_per_motor = _target.z / motor_count; float motor_z_torque = multirotor_properties.get_motor_z_torque(); float max_computed_thrust_per_motor = std::numeric_limits<float>::lowest(); float min_computed_thrust_per_motor = std::numeric_limits<float>::max(); for (size_t i = 0; i < m_outputs.size(); i++) { Quad_Multirotor_Properties::Motor const& mc = multirotor_properties.get_motors()[i]; Stream& out = *m_outputs[i]; float thrust = 0.f; //XY torque if (math::length_sq(half_xy_target) > std::numeric_limits<float>::epsilon() * 10.f) { //the length of F depends on how much this motor can participate in the torque //a motor parallel with the torque will have |F| == 0 //a motor perpendicular will have |F| = 1 math::vec3f F = math::cross(math::normalized<float, math::safe>(half_xy_target), math::normalized<float, math::safe>(mc.position)); //doing the dot product dives us directionality for the motor thrust float positional_factor = math::dot(F, mc.thrust_vector); //|F| = |T| / (|p| * sin a) //sin a == 1 (for a quad with the motor thrust pointing upwards) //so |F| = |T| / |p| thrust = positional_factor * math::length(half_xy_target) / math::length(mc.position); } //distribute the z torque { float mu = math::clamp(z_target_per_motor / (multirotor_properties.get_motor_z_torque() * (mc.clockwise ? 1 : -1)), 0.f, 1.f); thrust += mu * max_thrust_per_motor; } //clamp to half dynamic range thrust = math::sgn(thrust) * math::min(math::abs(thrust), max_half_dynamic_range); thrust += collective_thrust_per_motor; max_computed_thrust_per_motor = math::max(max_computed_thrust_per_motor, thrust); min_computed_thrust_per_motor = math::min(min_computed_thrust_per_motor, thrust); out.thrust = thrust; } //there could be some spill over the max now. Redistribute it to all motors QASSERT(min_computed_thrust_per_motor >= min_thrust_per_motor - math::epsilon<float>()); if (max_computed_thrust_per_motor > max_thrust_per_motor + math::epsilon<float>()) { float spill = max_computed_thrust_per_motor - max_thrust_per_motor; min_computed_thrust_per_motor -= spill; QASSERT(min_computed_thrust_per_motor >= min_thrust_per_motor - math::epsilon<float>()); for (size_t i = 0; i < m_outputs.size(); i++) { Quad_Multirotor_Properties::Motor const& mc = multirotor_properties.get_motors()[i]; Stream& out = *m_outputs[i]; out.thrust = math::max(out.thrust - spill, min_thrust_per_motor); } } //convert thrust to throttle and clip for (auto& out: m_outputs) { out->throttle = compute_throttle_from_thrust(max_thrust_per_motor, out->thrust); } } ts::Result<void> Quad_Multirotor_Motor_Mixer::set_input_stream_path(size_t idx, std::string const& path) { return m_accumulator.set_stream_path(idx, path, m_descriptor->get_rate(), m_hal); } ts::Result<void> Quad_Multirotor_Motor_Mixer::set_config(hal::INode_Config const& config) { QLOG_TOPIC("Quad_Multirotor_Motor_Mixer::set_config"); auto specialized = dynamic_cast<hal::Quad_Multirotor_Motor_Mixer_Config const*>(&config); if (!specialized) { return make_error("Wrong config type"); } *m_config = *specialized; return ts::success; } auto Quad_Multirotor_Motor_Mixer::get_config() const -> std::shared_ptr<const hal::INode_Config> { return m_config; } auto Quad_Multirotor_Motor_Mixer::get_descriptor() const -> std::shared_ptr<const hal::INode_Descriptor> { return m_descriptor; } ts::Result<std::shared_ptr<messages::INode_Message>> Quad_Multirotor_Motor_Mixer::send_message(messages::INode_Message const& message) { return make_error("Unknown message"); } } } <commit_msg>Cosmetic fix<commit_after>#include "FCStdAfx.h" #include "Quad_Multirotor_Motor_Mixer.h" #include "uav_properties/Quad_Multirotor_Properties.h" #include "physics/constants.h" #include "hal.def.h" namespace silk { namespace node { Quad_Multirotor_Motor_Mixer::Quad_Multirotor_Motor_Mixer(HAL& hal) : m_hal(hal) , m_descriptor(new hal::Quad_Multirotor_Motor_Mixer_Descriptor()) , m_config(new hal::Quad_Multirotor_Motor_Mixer_Config()) { } ts::Result<void> Quad_Multirotor_Motor_Mixer::init(hal::INode_Descriptor const& descriptor) { QLOG_TOPIC("Quad_Multirotor_Motor_Mixer::init"); auto specialized = dynamic_cast<hal::Quad_Multirotor_Motor_Mixer_Descriptor const*>(&descriptor); if (!specialized) { return make_error("Wrong descriptor type"); } *m_descriptor = *specialized; return init(); } ts::Result<void> Quad_Multirotor_Motor_Mixer::init() { std::shared_ptr<const Quad_Multirotor_Properties> multirotor_properties = m_hal.get_specialized_uav_properties<Quad_Multirotor_Properties>(); if (!multirotor_properties) { return make_error("No quad multirotor properties found"); } if (multirotor_properties->get_motors().size() != 4) { return make_error("Invalid quad multirotor properties found - motor count != 4"); } const std::vector<Quad_Multirotor_Properties::Motor>& motors = multirotor_properties->get_motors(); for (Quad_Multirotor_Properties::Motor const& mc: motors) { if (math::dot(mc.thrust_vector, math::vec3f(0, 0, 1.f)) < 0.9999f) { return make_error("Bad quad multirotor properties: motors have wrong thrust vectors"); } } if (!math::equals(motors[0].position, -motors[2].position, 0.99f) || motors[0].clockwise != motors[2].clockwise) { return make_error("Bad quad multirotor properties: motors 0 and 2 are not antipodal"); } if (!math::equals(motors[1].position, -motors[3].position, 0.99f) || motors[1].clockwise != motors[3].clockwise) { return make_error("Bad quad multirotor properties: motors 1 and 3 are not antipodal"); } for (std::shared_ptr<Stream>& os: m_outputs) { os = std::make_shared<Stream>(); os->rate = m_descriptor->get_rate(); } return ts::success; } ts::Result<void> Quad_Multirotor_Motor_Mixer::start(Clock::time_point tp) { //TODO - use an basic_output_stream instead of the ad-hoc streams return ts::success; } auto Quad_Multirotor_Motor_Mixer::get_inputs() const -> std::vector<Input> { std::vector<Input> inputs = {{ { stream::ITorque::TYPE, m_descriptor->get_rate(), "torque", m_accumulator.get_stream_path(0) }, { stream::IFloat::TYPE, m_descriptor->get_rate(), "collective_thrust", m_accumulator.get_stream_path(1) } }}; return inputs; } auto Quad_Multirotor_Motor_Mixer::get_outputs() const -> std::vector<Output> { if (m_outputs.size() == 0 || m_outputs[0] == nullptr) { return std::vector<Output>(); } std::vector<Output> outputs(m_outputs.size()); for (size_t i = 0; i < m_outputs.size(); i++) { outputs[i].name = q::util::format<std::string>("throttle_{}", i); outputs[i].stream = m_outputs[i]; } return outputs; } void Quad_Multirotor_Motor_Mixer::process() { QLOG_TOPIC("Quad_Multirotor_Motor_Mixer::process"); for (std::shared_ptr<Stream>& os: m_outputs) { os->samples.clear(); } std::shared_ptr<const Quad_Multirotor_Properties> multirotor_properties = m_hal.get_specialized_uav_properties<Quad_Multirotor_Properties>(); if (!multirotor_properties) { return; } if (multirotor_properties->get_motors().size() != m_outputs.size()) { QLOGE("Motor count changed since initialization!!!! Case not handled"); return; } m_accumulator.process([this, &multirotor_properties](stream::ITorque::Sample const& t_sample, stream::IFloat::Sample const& f_sample) { bool is_healthy = false; if (t_sample.is_healthy & f_sample.is_healthy) { compute_throttles(*multirotor_properties, f_sample.value, t_sample.value); is_healthy = true; } for (std::shared_ptr<Stream> output: m_outputs) { Stream::Sample& sample = output->last_sample; sample.value = output->throttle; sample.is_healthy = is_healthy; output->samples.push_back(sample); } }); } static float compute_throttle_from_thrust(float max_thrust, float thrust) { if (math::is_zero(max_thrust, math::epsilon<float>())) { return 0; } float ratio = thrust / max_thrust; //thrust increases approximately with throttle^2 float throttle = math::sqrt<float, math::safe>(ratio); return throttle; } static float compute_thrust_from_throttle(float max_thrust, float throttle) { float thrust = math::square(math::clamp(throttle, 0.f, 1.f)) * max_thrust; return thrust; } void Quad_Multirotor_Motor_Mixer::compute_throttles(Quad_Multirotor_Properties const& multirotor_properties, stream::IFloat::Value const& collective_thrust, stream::ITorque::Value const& _target) { //T = r X F //T = |r| * |F| * sin(a) // T - torque // r - position of the force relative to the center of mass // F - force applied // a - angle between the force vector and the position vector (usually 90 degrees) if (collective_thrust < std::numeric_limits<float>::epsilon() * 10.f) { for (size_t i = 0; i < m_outputs.size(); i++) { Stream& out = *m_outputs[i]; out.thrust = 0.f; out.throttle = 0.f; } return; } float motor_count = static_cast<float>(m_outputs.size()); float collective_thrust_per_motor = collective_thrust / motor_count; //min and max allowed thrusts per motor float max_thrust_per_motor = multirotor_properties.get_motor_thrust(); float min_thrust_per_motor = compute_thrust_from_throttle(m_config->get_armed_min_throttle(), max_thrust_per_motor); //the min collective thrust per motor is - at minimum - twice the min thrust per motor. //this is to that even at minimum, there is still some dynamic range left float min_collective_thrust_per_motor = math::max(collective_thrust_per_motor, min_thrust_per_motor * 2.f); collective_thrust_per_motor = math::max(collective_thrust_per_motor, min_collective_thrust_per_motor); //this is half the dynamic range, computed so that there is no spill either above max or below min float max_half_dynamic_range = math::min( collective_thrust_per_motor - min_thrust_per_motor, //how much space we have between the collective thrust and the min thrust (max_thrust_per_motor - min_thrust_per_motor) / 2.f //the middle thrust point ); //split the target torque in XY (roll, pitch) and Z (yaw) stream::ITorque::Value xy_target = stream::ITorque::Value(_target.x, _target.y, 0.f); stream::ITorque::Value half_xy_target = xy_target / 2.f; //for xy, the quad has 2 halves participating float z_target_per_motor = _target.z / motor_count; float motor_z_torque = multirotor_properties.get_motor_z_torque(); float max_computed_thrust_per_motor = std::numeric_limits<float>::lowest(); float min_computed_thrust_per_motor = std::numeric_limits<float>::max(); for (size_t i = 0; i < m_outputs.size(); i++) { Quad_Multirotor_Properties::Motor const& mc = multirotor_properties.get_motors()[i]; Stream& out = *m_outputs[i]; float thrust = 0.f; //XY torque if (math::length_sq(half_xy_target) > std::numeric_limits<float>::epsilon() * 10.f) { //the length of F depends on how much this motor can participate in the torque //a motor parallel with the torque will have |F| == 0 //a motor perpendicular will have |F| = 1 math::vec3f F = math::cross(math::normalized<float, math::safe>(half_xy_target), math::normalized<float, math::safe>(mc.position)); //doing the dot product dives us directionality for the motor thrust float positional_factor = math::dot(F, mc.thrust_vector); //|F| = |T| / (|p| * sin a) //sin a == 1 (for a quad with the motor thrust pointing upwards) //so |F| = |T| / |p| thrust = positional_factor * math::length(half_xy_target) / math::length(mc.position); } //distribute the z torque { float mu = math::clamp(z_target_per_motor / (multirotor_properties.get_motor_z_torque() * (mc.clockwise ? 1 : -1)), 0.f, 1.f); thrust += mu * max_thrust_per_motor; } //clamp to half dynamic range thrust = math::sgn(thrust) * math::min(math::abs(thrust), max_half_dynamic_range); thrust += collective_thrust_per_motor; max_computed_thrust_per_motor = math::max(max_computed_thrust_per_motor, thrust); min_computed_thrust_per_motor = math::min(min_computed_thrust_per_motor, thrust); out.thrust = thrust; } //there could be some spill over the max now. Redistribute it to all motors QASSERT(min_computed_thrust_per_motor >= min_thrust_per_motor - math::epsilon<float>()); if (max_computed_thrust_per_motor > max_thrust_per_motor + math::epsilon<float>()) { float spill = max_computed_thrust_per_motor - max_thrust_per_motor; min_computed_thrust_per_motor -= spill; QASSERT(min_computed_thrust_per_motor >= min_thrust_per_motor - math::epsilon<float>()); for (size_t i = 0; i < m_outputs.size(); i++) { Quad_Multirotor_Properties::Motor const& mc = multirotor_properties.get_motors()[i]; Stream& out = *m_outputs[i]; out.thrust = math::max(out.thrust - spill, min_thrust_per_motor); } } //convert thrust to throttle and clip for (std::shared_ptr<Stream>& out: m_outputs) { out->throttle = compute_throttle_from_thrust(max_thrust_per_motor, out->thrust); } } ts::Result<void> Quad_Multirotor_Motor_Mixer::set_input_stream_path(size_t idx, std::string const& path) { return m_accumulator.set_stream_path(idx, path, m_descriptor->get_rate(), m_hal); } ts::Result<void> Quad_Multirotor_Motor_Mixer::set_config(hal::INode_Config const& config) { QLOG_TOPIC("Quad_Multirotor_Motor_Mixer::set_config"); auto specialized = dynamic_cast<hal::Quad_Multirotor_Motor_Mixer_Config const*>(&config); if (!specialized) { return make_error("Wrong config type"); } *m_config = *specialized; return ts::success; } auto Quad_Multirotor_Motor_Mixer::get_config() const -> std::shared_ptr<const hal::INode_Config> { return m_config; } auto Quad_Multirotor_Motor_Mixer::get_descriptor() const -> std::shared_ptr<const hal::INode_Descriptor> { return m_descriptor; } ts::Result<std::shared_ptr<messages::INode_Message>> Quad_Multirotor_Motor_Mixer::send_message(messages::INode_Message const& message) { return make_error("Unknown message"); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, 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_POLICY_HPP_INCLUDED #define TORRENT_POLICY_HPP_INCLUDED #include <algorithm> #include <vector> #ifdef _MSC_VER #pragma warning(push, 1) #endif #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer.hpp" #include "libtorrent/piece_picker.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/size_type.hpp" #include "libtorrent/invariant_check.hpp" #include "libtorrent/config.hpp" #include "libtorrent/time.hpp" namespace libtorrent { class torrent; class peer_connection; enum { // the limits of the download queue size min_request_queue = 2, // the amount of free upload allowed before // the peer is choked free_upload_amount = 4 * 16 * 1024 }; void request_a_block(torrent& t, peer_connection& c); class TORRENT_EXPORT policy { public: policy(torrent* t); // this is called every 10 seconds to allow // for peer choking management void pulse(); struct peer; // this is called once for every peer we get from // the tracker, pex, lsd or dht. policy::peer* peer_from_tracker(const tcp::endpoint& remote, const peer_id& pid , int source, char flags); // false means duplicate connection bool update_peer_port(int port, policy::peer* p, int src); // called when an incoming connection is accepted // false means the connection was refused or failed bool new_connection(peer_connection& c); // the given connection was just closed void connection_closed(const peer_connection& c); // the peer has got at least one interesting piece void peer_is_interesting(peer_connection& c); // the peer unchoked us void unchoked(peer_connection& c); // the peer is interested in our pieces void interested(peer_connection& c); // the peer is not interested in our pieces void not_interested(peer_connection& c); void ip_filter_updated(); #ifndef NDEBUG bool has_connection(const peer_connection* p); void check_invariant() const; #endif struct peer { enum connection_type { not_connectable, connectable }; peer(tcp::endpoint const& ip, connection_type t, int src); size_type total_download() const; size_type total_upload() const; tcp::endpoint ip() const { return tcp::endpoint(addr, port); } void set_ip(tcp::endpoint const& endp) { addr = endp.address(); port = endp.port(); } // this is the accumulated amount of // uploaded and downloaded data to this // peer. It only accounts for what was // shared during the last connection to // this peer. i.e. These are only updated // when the connection is closed. For the // total amount of upload and download // we'll have to add thes figures with the // statistics from the peer_connection. size_type prev_amount_upload; size_type prev_amount_download; // the ip address this peer is or was connected on address addr; // the time when this peer was optimistically unchoked // the last time. libtorrent::ptime last_optimistically_unchoked; // the time when the peer connected to us // or disconnected if it isn't connected right now libtorrent::ptime connected; // if the peer is connected now, this // will refer to a valid peer_connection peer_connection* connection; #ifndef TORRENT_DISABLE_GEO_IP #ifndef NDEBUG // only used in debug mode to assert that // the first entry in the AS pair keeps the same boost::uint16_t inet_as_num; #endif // The AS this peer belongs to std::pair<const int, int>* inet_as; #endif // the port this peer is or was connected on uint16_t port; // the number of failed connection attempts // this peer has boost::uint8_t failcount; // for every valid piece we receive where this // peer was one of the participants, we increase // this value. For every invalid piece we receive // where this peer was a participant, we decrease // this value. If it sinks below a threshold, its // considered a bad peer and will be banned. boost::int8_t trust_points; // a bitmap combining the peer_source flags // from peer_info. boost::uint8_t source; // the number of times this peer has been // part of a piece that failed the hash check boost::uint8_t hashfails; // type specifies if the connection was incoming // or outgoing. If we ever saw this peer as connectable // it will remain as connectable unsigned type:4; // the number of times we have allowed a fast // reconnect for this peer. unsigned fast_reconnects:4; #ifndef TORRENT_DISABLE_ENCRYPTION // Hints encryption support of peer. Only effective // for and when the outgoing encryption policy // allows both encrypted and non encrypted // connections (pe_settings::out_enc_policy // == enabled). The initial state of this flag // determines the initial connection attempt // type (true = encrypted, false = standard). // This will be toggled everytime either an // encrypted or non-encrypted handshake fails. bool pe_support:1; #endif // true if this peer currently is unchoked // because of an optimistic unchoke. // when the optimistic unchoke is moved to // another peer, this peer will be choked // if this is true bool optimistically_unchoked:1; // this is true if the peer is a seed bool seed:1; // if this is true, the peer has previously // participated in a piece that failed the piece // hash check. This will put the peer on parole // and only request entire pieces. If a piece pass // that was partially requested from this peer it // will leave parole mode and continue download // pieces as normal peers. bool on_parole:1; // is set to true if this peer has been banned bool banned:1; #ifndef TORRENT_DISABLE_DHT // this is set to true when this peer as been // pinged by the DHT bool added_to_dht:1; #endif }; int num_peers() const { return m_peers.size(); } typedef std::multimap<address, peer>::iterator iterator; typedef std::multimap<address, peer>::const_iterator const_iterator; iterator begin_peer() { return m_peers.begin(); } iterator end_peer() { return m_peers.end(); } const_iterator begin_peer() const { return m_peers.begin(); } const_iterator end_peer() const { return m_peers.end(); } bool connect_one_peer(); bool has_peer(policy::peer const* p) const; int num_seeds() const { return m_num_seeds; } int num_connect_candidates() const { return m_num_connect_candidates; } void recalculate_connect_candidates() { if (m_num_connect_candidates == 0) m_num_connect_candidates = 1; } void erase_peer(iterator i); private: bool compare_peer(policy::peer const& lhs, policy::peer const& rhs , address const& external_ip) const; iterator find_connect_candidate(); bool is_connect_candidate(peer const& p, bool finished); std::multimap<address, peer> m_peers; // since the peer list can grow too large // to scan all of it, start at this iterator iterator m_round_robin; torrent* m_torrent; // free download we have got that hasn't // been distributed yet. size_type m_available_free_upload; // The number of peers in our peer list // that are connect candidates. i.e. they're // not already connected and they have not // yet reached their max try count and they // have the connectable state (we have a listen // port for them). int m_num_connect_candidates; // the number of seeds in the peer list int m_num_seeds; }; } #endif // TORRENT_POLICY_HPP_INCLUDED <commit_msg>Fix building with msvc<commit_after>/* Copyright (c) 2003, 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_POLICY_HPP_INCLUDED #define TORRENT_POLICY_HPP_INCLUDED #include <algorithm> #include <vector> #ifdef _MSC_VER #pragma warning(push, 1) #endif #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer.hpp" #include "libtorrent/piece_picker.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/size_type.hpp" #include "libtorrent/invariant_check.hpp" #include "libtorrent/config.hpp" #include "libtorrent/time.hpp" namespace libtorrent { class torrent; class peer_connection; enum { // the limits of the download queue size min_request_queue = 2, // the amount of free upload allowed before // the peer is choked free_upload_amount = 4 * 16 * 1024 }; void request_a_block(torrent& t, peer_connection& c); class TORRENT_EXPORT policy { public: policy(torrent* t); // this is called every 10 seconds to allow // for peer choking management void pulse(); struct peer; // this is called once for every peer we get from // the tracker, pex, lsd or dht. policy::peer* peer_from_tracker(const tcp::endpoint& remote, const peer_id& pid , int source, char flags); // false means duplicate connection bool update_peer_port(int port, policy::peer* p, int src); // called when an incoming connection is accepted // false means the connection was refused or failed bool new_connection(peer_connection& c); // the given connection was just closed void connection_closed(const peer_connection& c); // the peer has got at least one interesting piece void peer_is_interesting(peer_connection& c); // the peer unchoked us void unchoked(peer_connection& c); // the peer is interested in our pieces void interested(peer_connection& c); // the peer is not interested in our pieces void not_interested(peer_connection& c); void ip_filter_updated(); #ifndef NDEBUG bool has_connection(const peer_connection* p); void check_invariant() const; #endif struct peer { enum connection_type { not_connectable, connectable }; peer(tcp::endpoint const& ip, connection_type t, int src); size_type total_download() const; size_type total_upload() const; tcp::endpoint ip() const { return tcp::endpoint(addr, port); } void set_ip(tcp::endpoint const& endp) { addr = endp.address(); port = endp.port(); } // this is the accumulated amount of // uploaded and downloaded data to this // peer. It only accounts for what was // shared during the last connection to // this peer. i.e. These are only updated // when the connection is closed. For the // total amount of upload and download // we'll have to add thes figures with the // statistics from the peer_connection. size_type prev_amount_upload; size_type prev_amount_download; // the ip address this peer is or was connected on address addr; // the time when this peer was optimistically unchoked // the last time. libtorrent::ptime last_optimistically_unchoked; // the time when the peer connected to us // or disconnected if it isn't connected right now libtorrent::ptime connected; // if the peer is connected now, this // will refer to a valid peer_connection peer_connection* connection; #ifndef TORRENT_DISABLE_GEO_IP #ifndef NDEBUG // only used in debug mode to assert that // the first entry in the AS pair keeps the same boost::uint16_t inet_as_num; #endif // The AS this peer belongs to std::pair<const int, int>* inet_as; #endif // the port this peer is or was connected on boost::uint16_t port; // the number of failed connection attempts // this peer has boost::uint8_t failcount; // for every valid piece we receive where this // peer was one of the participants, we increase // this value. For every invalid piece we receive // where this peer was a participant, we decrease // this value. If it sinks below a threshold, its // considered a bad peer and will be banned. boost::int8_t trust_points; // a bitmap combining the peer_source flags // from peer_info. boost::uint8_t source; // the number of times this peer has been // part of a piece that failed the hash check boost::uint8_t hashfails; // type specifies if the connection was incoming // or outgoing. If we ever saw this peer as connectable // it will remain as connectable unsigned type:4; // the number of times we have allowed a fast // reconnect for this peer. unsigned fast_reconnects:4; #ifndef TORRENT_DISABLE_ENCRYPTION // Hints encryption support of peer. Only effective // for and when the outgoing encryption policy // allows both encrypted and non encrypted // connections (pe_settings::out_enc_policy // == enabled). The initial state of this flag // determines the initial connection attempt // type (true = encrypted, false = standard). // This will be toggled everytime either an // encrypted or non-encrypted handshake fails. bool pe_support:1; #endif // true if this peer currently is unchoked // because of an optimistic unchoke. // when the optimistic unchoke is moved to // another peer, this peer will be choked // if this is true bool optimistically_unchoked:1; // this is true if the peer is a seed bool seed:1; // if this is true, the peer has previously // participated in a piece that failed the piece // hash check. This will put the peer on parole // and only request entire pieces. If a piece pass // that was partially requested from this peer it // will leave parole mode and continue download // pieces as normal peers. bool on_parole:1; // is set to true if this peer has been banned bool banned:1; #ifndef TORRENT_DISABLE_DHT // this is set to true when this peer as been // pinged by the DHT bool added_to_dht:1; #endif }; int num_peers() const { return m_peers.size(); } typedef std::multimap<address, peer>::iterator iterator; typedef std::multimap<address, peer>::const_iterator const_iterator; iterator begin_peer() { return m_peers.begin(); } iterator end_peer() { return m_peers.end(); } const_iterator begin_peer() const { return m_peers.begin(); } const_iterator end_peer() const { return m_peers.end(); } bool connect_one_peer(); bool has_peer(policy::peer const* p) const; int num_seeds() const { return m_num_seeds; } int num_connect_candidates() const { return m_num_connect_candidates; } void recalculate_connect_candidates() { if (m_num_connect_candidates == 0) m_num_connect_candidates = 1; } void erase_peer(iterator i); private: bool compare_peer(policy::peer const& lhs, policy::peer const& rhs , address const& external_ip) const; iterator find_connect_candidate(); bool is_connect_candidate(peer const& p, bool finished); std::multimap<address, peer> m_peers; // since the peer list can grow too large // to scan all of it, start at this iterator iterator m_round_robin; torrent* m_torrent; // free download we have got that hasn't // been distributed yet. size_type m_available_free_upload; // The number of peers in our peer list // that are connect candidates. i.e. they're // not already connected and they have not // yet reached their max try count and they // have the connectable state (we have a listen // port for them). int m_num_connect_candidates; // the number of seeds in the peer list int m_num_seeds; }; } #endif // TORRENT_POLICY_HPP_INCLUDED <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * Copyright (c) 2015 Kohei Yoshida * * 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 "mdds/global.hpp" #include <cassert> #include <algorithm> #ifdef MDDS_TRIE_MAP_DEBUG #include <iostream> #endif namespace mdds { namespace draft { namespace detail { struct trie_node { char key; const void* value; std::deque<trie_node> children; trie_node(char _key) : key(_key), value(nullptr) {} }; #ifdef MDDS_TRIE_MAP_DEBUG template<typename _ValueT> void dump_node(std::string& buffer, const trie_node& node) { using namespace std; using value_type = _ValueT; if (node.value) { // This node has value. cout << buffer << ":" << *static_cast<const value_type*>(node.value) << endl; } std::for_each(node.children.begin(), node.children.end(), [&](const trie_node& node) { buffer.push_back(node.key); dump_node<value_type>(buffer, node); buffer.pop_back(); } ); } template<typename _ValueT> void dump_trie(const trie_node& root) { std::string buffer; dump_node<_ValueT>(buffer, root); } template<typename _ValueT> void dump_packed_trie(const std::vector<uintptr_t>& packed) { using namespace std; using value_type = _ValueT; cout << "packed size: " << packed.size() << endl; size_t n = packed.size(); size_t i = 0; cout << i << ": root node offset: " << packed[i] << endl; ++i; while (i < n) { const value_type* value = reinterpret_cast<const value_type*>(packed[i]); cout << i << ": node value pointer: " << value; if (value) cout << ", value: " << *value; cout << endl; ++i; size_t index_size = packed[i]; cout << i << ": index size: " << index_size << endl; ++i; index_size /= 2; for (size_t j = 0; j < index_size; ++j) { char key = packed[i]; cout << i << ": key: " << key << endl; ++i; size_t offset = packed[i]; cout << i << ": offset: " << offset << endl; ++i; } } } #endif template<typename _ValueT> void traverse_range( trie_node& root, const typename packed_trie_map<_ValueT>::entry* start, const typename packed_trie_map<_ValueT>::entry* end, size_t pos) { using namespace std; using entry = typename packed_trie_map<_ValueT>::entry; const entry* p = start; const entry* range_start = start; const entry* range_end = nullptr; char range_char = 0; size_t range_count = 0; for (; p != end; ++p) { if (pos > p->keylen) continue; if (pos == p->keylen) { root.value = &p->value; continue; } ++range_count; char c = p->key[pos]; if (!range_char) range_char = c; else if (range_char != c) { // End of current character range. range_end = p; root.children.emplace_back(range_char); traverse_range<_ValueT>(root.children.back(), range_start, range_end, pos+1); range_start = range_end; range_char = range_start->key[pos]; range_end = nullptr; range_count = 1; } } if (range_count) { assert(range_char); root.children.emplace_back(range_char); traverse_range<_ValueT>(root.children.back(), range_start, end, pos+1); } } inline size_t compact_node(std::vector<uintptr_t>& packed, const trie_node& node) { std::vector<std::tuple<size_t,char>> child_offsets; child_offsets.reserve(node.children.size()); // Process child nodes first. std::for_each(node.children.begin(), node.children.end(), [&](const trie_node& node) { size_t child_offset = compact_node(packed, node); child_offsets.emplace_back(child_offset, node.key); } ); // Process this node. size_t offset = packed.size(); packed.push_back(uintptr_t(node.value)); packed.push_back(uintptr_t(child_offsets.size()*2)); std::for_each(child_offsets.begin(), child_offsets.end(), [&](const std::tuple<size_t,char>& v) { char key = std::get<1>(v); size_t child_offset = std::get<0>(v); packed.push_back(key); packed.push_back(offset-child_offset); } ); return offset; } inline void compact(std::vector<uintptr_t>& packed, const trie_node& root) { std::vector<uintptr_t> init(size_t(1), uintptr_t(0)); packed.swap(init); size_t root_offset = compact_node(packed, root); packed[0] = root_offset; } } template<typename _ValueT> packed_trie_map<_ValueT>::packed_trie_map( const entry* entries, size_type entry_size, value_type null_value) : m_null_value(null_value) { const entry* p = entries; const entry* p_end = p + entry_size; // Populate the normal tree first. detail::trie_node root(0); detail::traverse_range<value_type>(root, p, p_end, 0); #if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_TRIE) detail::dump_trie<value_type>(root); #endif // Compact the trie into a packed array. detail::compact(m_packed, root); #if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_PACKED) detail::dump_packed_trie<value_type>(m_packed); #endif } template<typename _ValueT> typename packed_trie_map<_ValueT>::value_type packed_trie_map<_ValueT>::find(const char* input, size_type len) const { if (m_packed.empty()) return m_null_value; const char* key_end = input + len; size_t root_offset = m_packed[0]; const uintptr_t* root = m_packed.data() + root_offset; const value_type* pv = descend_node(root, input, key_end); return pv ? *pv : m_null_value; } template<typename _ValueT> const typename packed_trie_map<_ValueT>::value_type* packed_trie_map<_ValueT>::descend_node( const uintptr_t* p, const char* key, const char* key_end) const { const value_type* v = reinterpret_cast<const value_type*>(*p); if (key == key_end) return v; const uintptr_t* p0 = p; // store the head offset position of this node. // Find the child node with a matching key character. ++p; size_t index_size = *p; size_t n = index_size / 2; ++p; for (size_t i = 0; i < n; ++i) { char node_key = *p++; size_t offset = *p++; if (*key != node_key) continue; const uintptr_t* p_child = p0 - offset; ++key; return descend_node(p_child, key, key_end); } return nullptr; } #ifdef MDDS_TRIE_MAP_DEBUG template<typename _ValueT> void packed_trie_map<_ValueT>::dump() const { if (m_packed.empty()) return; std::string buffer; size_t root_offset = m_packed[0]; const uintptr_t* p = m_packed.data() + root_offset; dump_compact_trie_node(buffer, p); } template<typename _ValueT> void packed_trie_map<_ValueT>::dump_compact_trie_node(std::string& buffer, const uintptr_t* p) const { using namespace std; const uintptr_t* p0 = p; // store the head offset position of this node. const value_type* v = reinterpret_cast<const value_type*>(*p); if (v) cout << buffer << ": " << *v << endl; ++p; size_t index_size = *p; size_t n = index_size / 2; ++p; for (size_t i = 0; i < n; ++i) { char key = *p++; size_t offset = *p++; buffer.push_back(key); const uintptr_t* p_child = p0 - offset; dump_compact_trie_node(buffer, p_child); buffer.pop_back(); } } #endif }} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Add TODO for later task.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * Copyright (c) 2015 Kohei Yoshida * * 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 "mdds/global.hpp" #include <cassert> #include <algorithm> #ifdef MDDS_TRIE_MAP_DEBUG #include <iostream> #endif namespace mdds { namespace draft { namespace detail { struct trie_node { char key; const void* value; std::deque<trie_node> children; trie_node(char _key) : key(_key), value(nullptr) {} }; #ifdef MDDS_TRIE_MAP_DEBUG template<typename _ValueT> void dump_node(std::string& buffer, const trie_node& node) { using namespace std; using value_type = _ValueT; if (node.value) { // This node has value. cout << buffer << ":" << *static_cast<const value_type*>(node.value) << endl; } std::for_each(node.children.begin(), node.children.end(), [&](const trie_node& node) { buffer.push_back(node.key); dump_node<value_type>(buffer, node); buffer.pop_back(); } ); } template<typename _ValueT> void dump_trie(const trie_node& root) { std::string buffer; dump_node<_ValueT>(buffer, root); } template<typename _ValueT> void dump_packed_trie(const std::vector<uintptr_t>& packed) { using namespace std; using value_type = _ValueT; cout << "packed size: " << packed.size() << endl; size_t n = packed.size(); size_t i = 0; cout << i << ": root node offset: " << packed[i] << endl; ++i; while (i < n) { const value_type* value = reinterpret_cast<const value_type*>(packed[i]); cout << i << ": node value pointer: " << value; if (value) cout << ", value: " << *value; cout << endl; ++i; size_t index_size = packed[i]; cout << i << ": index size: " << index_size << endl; ++i; index_size /= 2; for (size_t j = 0; j < index_size; ++j) { char key = packed[i]; cout << i << ": key: " << key << endl; ++i; size_t offset = packed[i]; cout << i << ": offset: " << offset << endl; ++i; } } } #endif template<typename _ValueT> void traverse_range( trie_node& root, const typename packed_trie_map<_ValueT>::entry* start, const typename packed_trie_map<_ValueT>::entry* end, size_t pos) { using namespace std; using entry = typename packed_trie_map<_ValueT>::entry; const entry* p = start; const entry* range_start = start; const entry* range_end = nullptr; char range_char = 0; size_t range_count = 0; for (; p != end; ++p) { if (pos > p->keylen) continue; if (pos == p->keylen) { root.value = &p->value; continue; } ++range_count; char c = p->key[pos]; if (!range_char) range_char = c; else if (range_char != c) { // End of current character range. range_end = p; root.children.emplace_back(range_char); traverse_range<_ValueT>(root.children.back(), range_start, range_end, pos+1); range_start = range_end; range_char = range_start->key[pos]; range_end = nullptr; range_count = 1; } } if (range_count) { assert(range_char); root.children.emplace_back(range_char); traverse_range<_ValueT>(root.children.back(), range_start, end, pos+1); } } inline size_t compact_node(std::vector<uintptr_t>& packed, const trie_node& node) { std::vector<std::tuple<size_t,char>> child_offsets; child_offsets.reserve(node.children.size()); // Process child nodes first. std::for_each(node.children.begin(), node.children.end(), [&](const trie_node& node) { size_t child_offset = compact_node(packed, node); child_offsets.emplace_back(child_offset, node.key); } ); // Process this node. size_t offset = packed.size(); packed.push_back(uintptr_t(node.value)); packed.push_back(uintptr_t(child_offsets.size()*2)); std::for_each(child_offsets.begin(), child_offsets.end(), [&](const std::tuple<size_t,char>& v) { char key = std::get<1>(v); size_t child_offset = std::get<0>(v); packed.push_back(key); packed.push_back(offset-child_offset); } ); return offset; } inline void compact(std::vector<uintptr_t>& packed, const trie_node& root) { std::vector<uintptr_t> init(size_t(1), uintptr_t(0)); packed.swap(init); size_t root_offset = compact_node(packed, root); packed[0] = root_offset; } } template<typename _ValueT> packed_trie_map<_ValueT>::packed_trie_map( const entry* entries, size_type entry_size, value_type null_value) : m_null_value(null_value) { const entry* p = entries; const entry* p_end = p + entry_size; // Populate the normal tree first. detail::trie_node root(0); detail::traverse_range<value_type>(root, p, p_end, 0); #if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_TRIE) detail::dump_trie<value_type>(root); #endif // Compact the trie into a packed array. detail::compact(m_packed, root); #if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_PACKED) detail::dump_packed_trie<value_type>(m_packed); #endif } template<typename _ValueT> typename packed_trie_map<_ValueT>::value_type packed_trie_map<_ValueT>::find(const char* input, size_type len) const { if (m_packed.empty()) return m_null_value; const char* key_end = input + len; size_t root_offset = m_packed[0]; const uintptr_t* root = m_packed.data() + root_offset; const value_type* pv = descend_node(root, input, key_end); return pv ? *pv : m_null_value; } template<typename _ValueT> const typename packed_trie_map<_ValueT>::value_type* packed_trie_map<_ValueT>::descend_node( const uintptr_t* p, const char* key, const char* key_end) const { const value_type* v = reinterpret_cast<const value_type*>(*p); if (key == key_end) return v; const uintptr_t* p0 = p; // store the head offset position of this node. // Find the child node with a matching key character. ++p; size_t index_size = *p; size_t n = index_size / 2; ++p; // TODO : turn this into a binary search. for (size_t i = 0; i < n; ++i) { const uintptr_t* p_this = p + i*2; char node_key = *p_this; size_t offset = *(p_this+1); if (*key != node_key) continue; const uintptr_t* p_child = p0 - offset; ++key; return descend_node(p_child, key, key_end); } return nullptr; } #ifdef MDDS_TRIE_MAP_DEBUG template<typename _ValueT> void packed_trie_map<_ValueT>::dump() const { if (m_packed.empty()) return; std::string buffer; size_t root_offset = m_packed[0]; const uintptr_t* p = m_packed.data() + root_offset; dump_compact_trie_node(buffer, p); } template<typename _ValueT> void packed_trie_map<_ValueT>::dump_compact_trie_node(std::string& buffer, const uintptr_t* p) const { using namespace std; const uintptr_t* p0 = p; // store the head offset position of this node. const value_type* v = reinterpret_cast<const value_type*>(*p); if (v) cout << buffer << ": " << *v << endl; ++p; size_t index_size = *p; size_t n = index_size / 2; ++p; for (size_t i = 0; i < n; ++i) { char key = *p++; size_t offset = *p++; buffer.push_back(key); const uintptr_t* p_child = p0 - offset; dump_compact_trie_node(buffer, p_child); buffer.pop_back(); } } #endif }} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef PLANET_FILESYSTEM_HPP #define PLANET_FILESYSTEM_HPP #include <planet/common.hpp> #include <planet/fs_core.hpp> namespace planet { class filesystem { private: shared_ptr<ops_type_db> ops_db_; shared_ptr<core_file_system> root_; public: typedef ops_type_db::priority priority; template<typename ...Types> filesystem(mode_t root_mode) { root_ = shared_ptr<core_file_system>(new core_file_system()); ops_db_ = make_shared<ops_type_db>(root_); // This is not circular reference of shared_ptr root_->ops_db_ = ops_db_; // root_.ops_db_ is a weak_ptr // Create root directory of this filesystem st_inode new_inode; new_inode.mode = root_mode | S_IFDIR; root_->root = std::make_shared<dentry>("/", "dir_ops_type", new_inode); // Install default file and directory operation root_-> template install_ops<file_ops_type>(priority::low); root_-> template install_ops<dir_ops_type>(priority::low); } ~filesystem() { // Destroy ops_db_ first because ops_db_ has a reference to root_ ops_db_.reset(); ::syslog(LOG_NOTICE, "filesystem: dtor: core_file_system: use_count=%ld", root_.use_count()); } shared_ptr<core_file_system> root() { return root_; } std::vector<ops_type_db::info_type> info() const { return ops_db_->info(); } }; } // namespace planet #endif // PLANET_FILESYSTEM_HPP <commit_msg>filesystem: Fix bug using destructed shared_ptr (SEGV)<commit_after>#ifndef PLANET_FILESYSTEM_HPP #define PLANET_FILESYSTEM_HPP #include <planet/common.hpp> #include <planet/fs_core.hpp> namespace planet { class filesystem { private: shared_ptr<ops_type_db> ops_db_; shared_ptr<core_file_system> root_; public: typedef ops_type_db::priority priority; template<typename ...Types> filesystem(mode_t root_mode) { root_ = shared_ptr<core_file_system>(new core_file_system()); ops_db_ = make_shared<ops_type_db>(root_); // This is not circular reference of shared_ptr root_->ops_db_ = ops_db_; // root_.ops_db_ is a weak_ptr // Create root directory of this filesystem st_inode new_inode; new_inode.mode = root_mode | S_IFDIR; root_->root = std::make_shared<dentry>("/", "dir_ops_type", new_inode); // Install default file and directory operation root_-> template install_ops<file_ops_type>(priority::low); root_-> template install_ops<dir_ops_type>(priority::low); } ~filesystem() { // Destroy ops_db_ first because ops_db_ has a reference to root_ ops_db_->clear(); ops_db_.reset(); ::syslog(LOG_NOTICE, "filesystem: dtor: core_file_system: use_count=%ld", root_.use_count()); } shared_ptr<core_file_system> root() { return root_; } std::vector<ops_type_db::info_type> info() const { return ops_db_->info(); } }; } // namespace planet #endif // PLANET_FILESYSTEM_HPP <|endoftext|>